2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server.devicepolicy;
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_EUICC;
47 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
48 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
49 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
51 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
52 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
53 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
54 import static org.xmlpull.v1.XmlPullParser.END_TAG;
55 import static org.xmlpull.v1.XmlPullParser.TEXT;
57 import android.Manifest.permission;
58 import android.accessibilityservice.AccessibilityServiceInfo;
59 import android.accounts.Account;
60 import android.accounts.AccountManager;
61 import android.annotation.NonNull;
62 import android.annotation.Nullable;
63 import android.annotation.UserIdInt;
64 import android.app.Activity;
65 import android.app.ActivityManager;
66 import android.app.ActivityManagerInternal;
67 import android.app.AlarmManager;
68 import android.app.AppGlobals;
69 import android.app.IActivityManager;
70 import android.app.IApplicationThread;
71 import android.app.IServiceConnection;
72 import android.app.Notification;
73 import android.app.NotificationManager;
74 import android.app.PendingIntent;
75 import android.app.StatusBarManager;
76 import android.app.admin.DeviceAdminInfo;
77 import android.app.admin.DeviceAdminReceiver;
78 import android.app.admin.DevicePolicyManager;
79 import android.app.admin.DevicePolicyManagerInternal;
80 import android.app.admin.IDevicePolicyManager;
81 import android.app.admin.NetworkEvent;
82 import android.app.admin.PasswordMetrics;
83 import android.app.admin.SystemUpdateInfo;
84 import android.app.admin.SecurityLog;
85 import android.app.admin.SecurityLog.SecurityEvent;
86 import android.app.admin.SystemUpdatePolicy;
87 import android.app.backup.IBackupManager;
88 import android.app.trust.TrustManager;
89 import android.content.BroadcastReceiver;
90 import android.content.ComponentName;
91 import android.content.Context;
92 import android.content.Intent;
93 import android.content.IntentFilter;
94 import android.content.pm.ActivityInfo;
95 import android.content.pm.ApplicationInfo;
96 import android.content.pm.IPackageManager;
97 import android.content.pm.PackageInfo;
98 import android.content.pm.PackageManager;
99 import android.content.pm.PackageManager.NameNotFoundException;
100 import android.content.pm.PackageManagerInternal;
101 import android.content.pm.ParceledListSlice;
102 import android.content.pm.PermissionInfo;
103 import android.content.pm.ResolveInfo;
104 import android.content.pm.ServiceInfo;
105 import android.content.pm.StringParceledListSlice;
106 import android.content.pm.UserInfo;
107 import android.content.res.Resources;
108 import android.database.ContentObserver;
109 import android.graphics.Bitmap;
110 import android.graphics.Color;
111 import android.media.AudioManager;
112 import android.media.IAudioService;
113 import android.net.ConnectivityManager;
114 import android.net.IIpConnectivityMetrics;
115 import android.net.ProxyInfo;
116 import android.net.Uri;
117 import android.net.metrics.IpConnectivityLog;
118 import android.net.wifi.WifiInfo;
119 import android.net.wifi.WifiManager;
120 import android.os.Binder;
121 import android.os.Build;
122 import android.os.Bundle;
123 import android.os.Environment;
124 import android.os.FileUtils;
125 import android.os.Handler;
126 import android.os.IBinder;
127 import android.os.Looper;
128 import android.os.ParcelFileDescriptor;
129 import android.os.PersistableBundle;
130 import android.os.PowerManager;
131 import android.os.PowerManagerInternal;
132 import android.os.Process;
133 import android.os.RecoverySystem;
134 import android.os.RemoteCallback;
135 import android.os.RemoteException;
136 import android.os.ServiceManager;
137 import android.os.SystemClock;
138 import android.os.SystemProperties;
139 import android.os.UserHandle;
140 import android.os.UserManager;
141 import android.os.UserManagerInternal;
142 import android.os.storage.StorageManager;
143 import android.provider.ContactsContract.QuickContact;
144 import android.provider.ContactsInternal;
145 import android.provider.Settings;
146 import android.provider.Settings.Global;
147 import android.security.IKeyChainAliasCallback;
148 import android.security.IKeyChainService;
149 import android.security.KeyChain;
150 import android.security.KeyChain.KeyChainConnection;
151 import android.service.persistentdata.PersistentDataBlockManager;
152 import android.telephony.TelephonyManager;
153 import android.text.TextUtils;
154 import android.util.ArrayMap;
155 import android.util.ArraySet;
156 import android.util.EventLog;
157 import android.util.Log;
158 import android.util.Pair;
159 import android.util.Slog;
160 import android.util.SparseArray;
161 import android.util.Xml;
162 import android.view.IWindowManager;
163 import android.view.accessibility.AccessibilityManager;
164 import android.view.accessibility.IAccessibilityManager;
165 import android.view.inputmethod.InputMethodInfo;
166 import android.view.inputmethod.InputMethodManager;
168 import com.android.internal.R;
169 import com.android.internal.annotations.GuardedBy;
170 import com.android.internal.annotations.VisibleForTesting;
171 import com.android.internal.logging.MetricsLogger;
172 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
173 import com.android.internal.notification.SystemNotificationChannels;
174 import com.android.internal.os.BackgroundThread;
175 import com.android.internal.statusbar.IStatusBarService;
176 import com.android.internal.util.DumpUtils;
177 import com.android.internal.util.FastXmlSerializer;
178 import com.android.internal.util.JournaledFile;
179 import com.android.internal.util.Preconditions;
180 import com.android.internal.util.XmlUtils;
181 import com.android.internal.widget.LockPatternUtils;
182 import com.android.server.LocalServices;
183 import com.android.server.SystemService;
184 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
185 import com.android.server.pm.UserRestrictionsUtils;
186 import com.google.android.collect.Sets;
188 import org.xmlpull.v1.XmlPullParser;
189 import org.xmlpull.v1.XmlPullParserException;
190 import org.xmlpull.v1.XmlSerializer;
193 import java.io.FileDescriptor;
194 import java.io.FileInputStream;
195 import java.io.FileNotFoundException;
196 import java.io.FileOutputStream;
197 import java.io.IOException;
198 import java.io.PrintWriter;
199 import java.nio.charset.StandardCharsets;
200 import java.text.DateFormat;
201 import java.util.ArrayList;
202 import java.util.Arrays;
203 import java.util.Collection;
204 import java.util.Collections;
205 import java.util.Date;
206 import java.util.List;
207 import java.util.Map.Entry;
208 import java.util.Set;
209 import java.util.concurrent.TimeUnit;
210 import java.util.concurrent.atomic.AtomicBoolean;
213 * Implementation of the device policy APIs.
215 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
217 protected static final String LOG_TAG = "DevicePolicyManager";
219 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
221 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
223 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
225 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
227 private static final String TAG_STATUS_BAR = "statusbar";
229 private static final String ATTR_DISABLED = "disabled";
231 private static final String ATTR_NAME = "name";
233 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
234 "do-not-ask-credentials-on-boot";
236 private static final String TAG_AFFILIATION_ID = "affiliation-id";
238 private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval";
240 private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request";
242 private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval";
244 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
246 private static final String TAG_CURRENT_INPUT_METHOD_SET = "current-ime-set";
248 private static final String TAG_OWNER_INSTALLED_CA_CERT = "owner-installed-ca-cert";
250 private static final String ATTR_ID = "id";
252 private static final String ATTR_VALUE = "value";
254 private static final String ATTR_ALIAS = "alias";
256 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
258 private static final String TAG_PASSWORD_TOKEN_HANDLE = "password-token";
260 private static final String TAG_PASSWORD_VALIDITY = "password-validity";
262 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
264 private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);
266 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
268 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
269 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
271 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
272 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
273 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
274 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
275 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
276 "device-provisioning-config-applied";
277 private static final String ATTR_DEVICE_PAIRED = "device-paired";
278 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
279 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
280 = "application-restrictions-manager";
282 // Comprehensive list of delegations.
283 private static final String DELEGATIONS[] = {
284 DELEGATION_CERT_INSTALL,
285 DELEGATION_APP_RESTRICTIONS,
286 DELEGATION_BLOCK_UNINSTALL,
287 DELEGATION_ENABLE_SYSTEM_APP,
288 DELEGATION_KEEP_UNINSTALLED_PACKAGES,
289 DELEGATION_PACKAGE_ACCESS,
290 DELEGATION_PERMISSION_GRANT
294 * System property whose value is either "true" or "false", indicating whether
295 * device owner is present.
297 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
299 private static final int STATUS_BAR_DISABLE_MASK =
300 StatusBarManager.DISABLE_EXPAND |
301 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
302 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
303 StatusBarManager.DISABLE_SEARCH;
305 private static final int STATUS_BAR_DISABLE2_MASK =
306 StatusBarManager.DISABLE2_QUICK_SETTINGS;
308 private static final Set<String> SECURE_SETTINGS_WHITELIST;
309 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
310 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
311 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
313 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
314 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
315 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
316 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
318 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
319 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
320 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
322 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
323 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
324 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
325 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
326 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
327 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
328 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
329 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
330 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
332 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
333 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
334 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
335 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
336 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
337 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
341 * Keyguard features that when set on a profile affect the profile content or challenge only.
342 * These cannot be set on the managed profile's parent DPM instance
344 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
345 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
347 /** Keyguard features that are allowed to be set on a managed profile */
348 private static final int PROFILE_KEYGUARD_FEATURES =
349 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
351 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
354 * Minimum timeout in milliseconds after which unlocking with weak auth times out,
355 * i.e. the user has to use a strong authentication method like password, PIN or pattern.
357 private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
360 * Strings logged with {@link
361 * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}.
363 private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
364 private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
366 final Context mContext;
367 final Injector mInjector;
368 final IPackageManager mIPackageManager;
369 final UserManager mUserManager;
370 final UserManagerInternal mUserManagerInternal;
371 final TelephonyManager mTelephonyManager;
372 private final LockPatternUtils mLockPatternUtils;
373 private final DevicePolicyConstants mConstants;
374 private final DeviceAdminServiceController mDeviceAdminServiceController;
377 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
378 * is requested for user u.
380 private final Set<Pair<String, Integer>> mPackagesToRemove =
381 new ArraySet<Pair<String, Integer>>();
383 final LocalService mLocalService;
385 // Stores and loads state on device and profile owners.
387 final Owners mOwners;
389 private final Binder mToken = new Binder();
392 * Whether or not device admin feature is supported. If it isn't return defaults for all
398 * Whether or not this device is a watch.
402 private final CertificateMonitor mCertificateMonitor;
403 private final SecurityLogMonitor mSecurityLogMonitor;
404 private NetworkLogger mNetworkLogger;
406 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
407 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
409 private SetupContentObserver mSetupContentObserver;
411 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
414 if(mRemoteBugreportServiceIsActive.get()) {
420 /** Listens only if mHasFeature == true. */
421 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
424 public void onReceive(Context context, Intent intent) {
425 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
426 && mRemoteBugreportServiceIsActive.get()) {
427 onBugreportFinished(intent);
432 /** Listens only if mHasFeature == true. */
433 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
436 public void onReceive(Context context, Intent intent) {
437 String action = intent.getAction();
438 mInjector.getNotificationManager().cancel(LOG_TAG,
439 RemoteBugreportUtils.NOTIFICATION_ID);
440 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
441 onBugreportSharingAccepted();
442 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
443 onBugreportSharingDeclined();
445 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
449 public static final class Lifecycle extends SystemService {
450 private DevicePolicyManagerService mService;
452 public Lifecycle(Context context) {
454 mService = new DevicePolicyManagerService(context);
458 public void onStart() {
459 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
463 public void onBootPhase(int phase) {
464 mService.systemReady(phase);
468 public void onStartUser(int userHandle) {
469 mService.handleStartUser(userHandle);
473 public void onUnlockUser(int userHandle) {
474 mService.handleUnlockUser(userHandle);
478 public void onStopUser(int userHandle) {
479 mService.handleStopUser(userHandle);
483 public static class DevicePolicyData {
484 @NonNull PasswordMetrics mActivePasswordMetrics = new PasswordMetrics();
485 int mFailedPasswordAttempts = 0;
486 boolean mPasswordStateHasBeenSetSinceBoot = false;
487 boolean mPasswordValidAtLastCheckpoint = false;
490 int mPasswordOwner = -1;
491 long mLastMaximumTimeToLock = -1;
492 boolean mUserSetupComplete = false;
493 boolean mPaired = false;
494 int mUserProvisioningState;
495 int mPermissionPolicy;
497 boolean mDeviceProvisioningConfigApplied = false;
499 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
500 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
501 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
503 // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
504 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
506 // This is the list of component allowed to start lock task mode.
507 List<String> mLockTaskPackages = new ArrayList<>();
509 boolean mStatusBarDisabled = false;
511 ComponentName mRestrictionsProvider;
513 // Map of delegate package to delegation scopes
514 final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>();
516 boolean doNotAskCredentialsOnBoot = false;
518 Set<String> mAffiliationIds = new ArraySet<>();
520 long mLastSecurityLogRetrievalTime = -1;
522 long mLastBugReportRequestTime = -1;
524 long mLastNetworkLogsRetrievalTime = -1;
526 boolean mCurrentInputMethodSet = false;
528 // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
529 Set<String> mOwnerInstalledCaCerts = new ArraySet<>();
531 // Used for initialization of users created by createAndManageUser.
532 boolean mAdminBroadcastPending = false;
533 PersistableBundle mInitBundle = null;
535 long mPasswordTokenHandle = 0;
537 public DevicePolicyData(int userHandle) {
538 mUserHandle = userHandle;
542 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
544 final Handler mHandler;
545 final Handler mBackgroundHandler;
547 /** Listens only if mHasFeature == true. */
548 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
550 public void onReceive(Context context, Intent intent) {
551 final String action = intent.getAction();
552 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
556 * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
557 * however it's too early in the boot process to register with IIpConnectivityMetrics
558 * to listen for events.
560 if (Intent.ACTION_USER_STARTED.equals(action)
561 && userHandle == mOwners.getDeviceOwnerUserId()) {
562 synchronized (DevicePolicyManagerService.this) {
563 if (isNetworkLoggingEnabledInternalLocked()) {
564 setNetworkLoggingActiveInternal(true);
568 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
569 && userHandle == mOwners.getDeviceOwnerUserId()
570 && getDeviceOwnerRemoteBugreportUri() != null) {
571 IntentFilter filterConsent = new IntentFilter();
572 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
573 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
574 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
575 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
576 RemoteBugreportUtils.NOTIFICATION_ID,
577 RemoteBugreportUtils.buildNotification(mContext,
578 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
581 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
582 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
584 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
585 + action + " for user " + userHandle);
587 mHandler.post(new Runnable() {
590 handlePasswordExpirationNotification(userHandle);
595 if (Intent.ACTION_USER_ADDED.equals(action)) {
596 sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
597 synchronized (DevicePolicyManagerService.this) {
598 // It might take a while for the user to become affiliated. Make security
599 // and network logging unavailable in the meantime.
600 maybePauseDeviceWideLoggingLocked();
602 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
603 sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
604 synchronized (DevicePolicyManagerService.this) {
605 // Check whether the user is affiliated, *before* removing its data.
606 boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
607 removeUserData(userHandle);
608 if (!isRemovedUserAffiliated) {
609 // We discard the logs when unaffiliated users are deleted (so that the
610 // device owner cannot retrieve data about that user after it's gone).
611 discardDeviceWideLogsLocked();
612 // Resume logging if all remaining users are affiliated.
613 maybeResumeDeviceWideLoggingLocked();
616 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
617 synchronized (DevicePolicyManagerService.this) {
618 // Reset the policy data
619 mUserData.remove(userHandle);
620 sendAdminEnabledBroadcastLocked(userHandle);
622 handlePackagesChanged(null /* check all admins */, userHandle);
623 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
624 handlePackagesChanged(null /* check all admins */, userHandle);
625 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
626 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
627 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
628 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
629 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
630 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
631 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
632 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
633 clearWipeProfileNotification();
637 private void sendUserAddedOrRemovedCommand(String action, int userHandle) {
638 synchronized (DevicePolicyManagerService.this) {
639 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
640 if (deviceOwner != null) {
641 Bundle extras = new Bundle();
642 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
643 sendAdminCommandLocked(deviceOwner, action, extras, null);
649 static class ActiveAdmin {
650 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
651 private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
652 private static final String TAG_DISABLE_CAMERA = "disable-camera";
653 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
654 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
655 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
656 = "disable-bt-contacts-sharing";
657 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
658 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
659 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
660 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
661 private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled";
662 private static final String TAG_ACCOUNT_TYPE = "account-type";
663 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
664 = "permitted-accessiblity-services";
665 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
666 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
667 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
668 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
669 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
670 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
671 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
672 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
673 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
674 private static final String TAG_PERMITTED_IMES = "permitted-imes";
675 private static final String TAG_PERMITTED_NOTIFICATION_LISTENERS =
676 "permitted-notification-listeners";
677 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
678 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
679 private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
680 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
681 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
682 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
683 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
684 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
685 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
686 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
687 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
688 private static final String ATTR_VALUE = "value";
689 private static final String TAG_PASSWORD_QUALITY = "password-quality";
690 private static final String TAG_POLICIES = "policies";
691 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
692 "cross-profile-widget-providers";
693 private static final String TAG_PROVIDER = "provider";
694 private static final String TAG_PACKAGE_LIST_ITEM = "item";
695 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
696 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
697 private static final String TAG_DEFAULT_ENABLED_USER_RESTRICTIONS =
698 "default-enabled-user-restrictions";
699 private static final String TAG_RESTRICTION = "restriction";
700 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
701 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
702 private static final String TAG_PARENT_ADMIN = "parent-admin";
703 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
704 private static final String TAG_ORGANIZATION_NAME = "organization-name";
705 private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification";
706 private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications";
708 final DeviceAdminInfo info;
711 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
712 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
714 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
715 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
716 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
717 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
718 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
719 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
720 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
722 PasswordMetrics minimumPasswordMetrics = new PasswordMetrics(
723 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH,
724 DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE,
725 DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC,
726 DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER);
728 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
729 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
731 long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
733 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
734 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
736 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
737 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
739 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
740 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
742 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
744 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
746 boolean encryptionRequested = false;
747 boolean testOnlyAdmin = false;
748 boolean disableCamera = false;
749 boolean disableCallerId = false;
750 boolean disableContactsSearch = false;
751 boolean disableBluetoothContactSharing = true;
752 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
753 boolean requireAutoTime = false; // Can only be set by a device owner.
754 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
755 boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner.
757 // one notification after enabling + one more after reboots
758 static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 2;
759 int numNetworkLoggingNotifications = 0;
760 long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch
762 ActiveAdmin parentAdmin;
763 final boolean isParent;
765 static class TrustAgentInfo {
766 public PersistableBundle options;
767 TrustAgentInfo(PersistableBundle bundle) {
772 final Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
774 // The list of permitted accessibility services package namesas set by a profile
775 // or device owner. Null means all accessibility services are allowed, empty means
776 // none except system services are allowed.
777 List<String> permittedAccessiblityServices;
779 // The list of permitted input methods package names as set by a profile or device owner.
780 // Null means all input methods are allowed, empty means none except system imes are
782 List<String> permittedInputMethods;
784 // The list of packages allowed to use a NotificationListenerService to receive events for
785 // notifications from this user. Null means that all packages are allowed. Empty list means
786 // that only packages from the system are allowed.
787 List<String> permittedNotificationListeners;
789 // List of package names to keep cached.
790 List<String> keepUninstalledPackages;
792 // TODO: review implementation decisions with frameworks team
793 boolean specifiesGlobalProxy = false;
794 String globalProxySpec = null;
795 String globalProxyExclusionList = null;
797 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
799 List<String> crossProfileWidgetProviders;
801 Bundle userRestrictions;
803 // User restrictions that have already been enabled by default for this admin (either when
804 // setting the device or profile owner, or during a system update if one of those "enabled
805 // by default" restrictions is newly added).
806 final Set<String> defaultEnabledRestrictionsAlreadySet = new ArraySet<>();
808 // Support text provided by the admin to display to the user.
809 CharSequence shortSupportMessage = null;
810 CharSequence longSupportMessage = null;
812 // Background color of confirm credentials screen. Default: teal.
813 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
814 int organizationColor = DEF_ORGANIZATION_COLOR;
816 // Default title of confirm credentials screen
817 String organizationName = null;
819 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
824 ActiveAdmin getParentActiveAdmin() {
825 Preconditions.checkState(!isParent);
827 if (parentAdmin == null) {
828 parentAdmin = new ActiveAdmin(info, /* parent */ true);
833 boolean hasParentActiveAdmin() {
834 return parentAdmin != null;
837 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
839 public UserHandle getUserHandle() {
840 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
843 void writeToXml(XmlSerializer out)
844 throws IllegalArgumentException, IllegalStateException, IOException {
845 out.startTag(null, TAG_POLICIES);
846 info.writePoliciesToXml(out);
847 out.endTag(null, TAG_POLICIES);
848 if (minimumPasswordMetrics.quality
849 != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
850 out.startTag(null, TAG_PASSWORD_QUALITY);
851 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality));
852 out.endTag(null, TAG_PASSWORD_QUALITY);
853 if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) {
854 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
856 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length));
857 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
859 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
860 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
861 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
862 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
864 if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
865 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
867 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase));
868 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
870 if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
871 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
873 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase));
874 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
876 if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) {
877 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
879 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters));
880 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
882 if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
883 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
885 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric));
886 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
888 if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
889 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
891 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols));
892 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
894 if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
895 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
897 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter));
898 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
901 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
902 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
903 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
904 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
906 if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
907 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
908 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
909 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
911 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
912 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
913 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
914 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
916 if (specifiesGlobalProxy) {
917 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
918 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
919 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
920 if (globalProxySpec != null) {
921 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
922 out.attribute(null, ATTR_VALUE, globalProxySpec);
923 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
925 if (globalProxyExclusionList != null) {
926 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
927 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
928 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
931 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
932 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
933 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
934 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
936 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
937 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
938 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
939 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
941 if (encryptionRequested) {
942 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
943 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
944 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
947 out.startTag(null, TAG_TEST_ONLY_ADMIN);
948 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
949 out.endTag(null, TAG_TEST_ONLY_ADMIN);
952 out.startTag(null, TAG_DISABLE_CAMERA);
953 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
954 out.endTag(null, TAG_DISABLE_CAMERA);
956 if (disableCallerId) {
957 out.startTag(null, TAG_DISABLE_CALLER_ID);
958 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
959 out.endTag(null, TAG_DISABLE_CALLER_ID);
961 if (disableContactsSearch) {
962 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
963 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
964 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
966 if (!disableBluetoothContactSharing) {
967 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
968 out.attribute(null, ATTR_VALUE,
969 Boolean.toString(disableBluetoothContactSharing));
970 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
972 if (disableScreenCapture) {
973 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
974 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
975 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
977 if (requireAutoTime) {
978 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
979 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
980 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
982 if (forceEphemeralUsers) {
983 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
984 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
985 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
987 if (isNetworkLoggingEnabled) {
988 out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
989 out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled));
990 out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS,
991 Integer.toString(numNetworkLoggingNotifications));
992 out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION,
993 Long.toString(lastNetworkLoggingNotificationTimeMs));
994 out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
996 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
997 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
998 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
999 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1001 if (!accountTypesWithManagementDisabled.isEmpty()) {
1002 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
1003 writeAttributeValuesToXml(
1004 out, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1005 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
1007 if (!trustAgentInfos.isEmpty()) {
1008 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
1009 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1010 for (Entry<String, TrustAgentInfo> entry : set) {
1011 TrustAgentInfo trustAgentInfo = entry.getValue();
1012 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
1013 out.attribute(null, ATTR_VALUE, entry.getKey());
1014 if (trustAgentInfo.options != null) {
1015 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1017 trustAgentInfo.options.saveToXml(out);
1018 } catch (XmlPullParserException e) {
1019 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
1021 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1023 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
1025 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1027 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
1028 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1029 writeAttributeValuesToXml(out, TAG_PROVIDER, crossProfileWidgetProviders);
1030 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1032 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
1033 permittedAccessiblityServices);
1034 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
1035 writePackageListToXml(out, TAG_PERMITTED_NOTIFICATION_LISTENERS,
1036 permittedNotificationListeners);
1037 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
1038 if (hasUserRestrictions()) {
1039 UserRestrictionsUtils.writeRestrictions(
1040 out, userRestrictions, TAG_USER_RESTRICTIONS);
1042 if (!defaultEnabledRestrictionsAlreadySet.isEmpty()) {
1043 out.startTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1044 writeAttributeValuesToXml(
1045 out, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1046 out.endTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1048 if (!TextUtils.isEmpty(shortSupportMessage)) {
1049 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1050 out.text(shortSupportMessage.toString());
1051 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1053 if (!TextUtils.isEmpty(longSupportMessage)) {
1054 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
1055 out.text(longSupportMessage.toString());
1056 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
1058 if (parentAdmin != null) {
1059 out.startTag(null, TAG_PARENT_ADMIN);
1060 parentAdmin.writeToXml(out);
1061 out.endTag(null, TAG_PARENT_ADMIN);
1063 if (organizationColor != DEF_ORGANIZATION_COLOR) {
1064 out.startTag(null, TAG_ORGANIZATION_COLOR);
1065 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
1066 out.endTag(null, TAG_ORGANIZATION_COLOR);
1068 if (organizationName != null) {
1069 out.startTag(null, TAG_ORGANIZATION_NAME);
1070 out.text(organizationName);
1071 out.endTag(null, TAG_ORGANIZATION_NAME);
1075 void writePackageListToXml(XmlSerializer out, String outerTag,
1076 List<String> packageList)
1077 throws IllegalArgumentException, IllegalStateException, IOException {
1078 if (packageList == null) {
1082 out.startTag(null, outerTag);
1083 writeAttributeValuesToXml(out, TAG_PACKAGE_LIST_ITEM, packageList);
1084 out.endTag(null, outerTag);
1087 void writeAttributeValuesToXml(XmlSerializer out, String tag,
1088 @NonNull Collection<String> values) throws IOException {
1089 for (String value : values) {
1090 out.startTag(null, tag);
1091 out.attribute(null, ATTR_VALUE, value);
1092 out.endTag(null, tag);
1096 void readFromXml(XmlPullParser parser)
1097 throws XmlPullParserException, IOException {
1098 int outerDepth = parser.getDepth();
1100 while ((type=parser.next()) != END_DOCUMENT
1101 && (type != END_TAG || parser.getDepth() > outerDepth)) {
1102 if (type == END_TAG || type == TEXT) {
1105 String tag = parser.getName();
1106 if (TAG_POLICIES.equals(tag)) {
1107 info.readPoliciesFromXml(parser);
1108 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
1109 minimumPasswordMetrics.quality = Integer.parseInt(
1110 parser.getAttributeValue(null, ATTR_VALUE));
1111 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
1112 minimumPasswordMetrics.length = Integer.parseInt(
1113 parser.getAttributeValue(null, ATTR_VALUE));
1114 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
1115 passwordHistoryLength = Integer.parseInt(
1116 parser.getAttributeValue(null, ATTR_VALUE));
1117 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
1118 minimumPasswordMetrics.upperCase = Integer.parseInt(
1119 parser.getAttributeValue(null, ATTR_VALUE));
1120 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
1121 minimumPasswordMetrics.lowerCase = Integer.parseInt(
1122 parser.getAttributeValue(null, ATTR_VALUE));
1123 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
1124 minimumPasswordMetrics.letters = Integer.parseInt(
1125 parser.getAttributeValue(null, ATTR_VALUE));
1126 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
1127 minimumPasswordMetrics.numeric = Integer.parseInt(
1128 parser.getAttributeValue(null, ATTR_VALUE));
1129 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
1130 minimumPasswordMetrics.symbols = Integer.parseInt(
1131 parser.getAttributeValue(null, ATTR_VALUE));
1132 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
1133 minimumPasswordMetrics.nonLetter = Integer.parseInt(
1134 parser.getAttributeValue(null, ATTR_VALUE));
1135 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
1136 maximumTimeToUnlock = Long.parseLong(
1137 parser.getAttributeValue(null, ATTR_VALUE));
1138 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
1139 strongAuthUnlockTimeout = Long.parseLong(
1140 parser.getAttributeValue(null, ATTR_VALUE));
1141 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
1142 maximumFailedPasswordsForWipe = Integer.parseInt(
1143 parser.getAttributeValue(null, ATTR_VALUE));
1144 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
1145 specifiesGlobalProxy = Boolean.parseBoolean(
1146 parser.getAttributeValue(null, ATTR_VALUE));
1147 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1149 parser.getAttributeValue(null, ATTR_VALUE);
1150 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1151 globalProxyExclusionList =
1152 parser.getAttributeValue(null, ATTR_VALUE);
1153 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1154 passwordExpirationTimeout = Long.parseLong(
1155 parser.getAttributeValue(null, ATTR_VALUE));
1156 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1157 passwordExpirationDate = Long.parseLong(
1158 parser.getAttributeValue(null, ATTR_VALUE));
1159 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1160 encryptionRequested = Boolean.parseBoolean(
1161 parser.getAttributeValue(null, ATTR_VALUE));
1162 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1163 testOnlyAdmin = Boolean.parseBoolean(
1164 parser.getAttributeValue(null, ATTR_VALUE));
1165 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1166 disableCamera = Boolean.parseBoolean(
1167 parser.getAttributeValue(null, ATTR_VALUE));
1168 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1169 disableCallerId = Boolean.parseBoolean(
1170 parser.getAttributeValue(null, ATTR_VALUE));
1171 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1172 disableContactsSearch = Boolean.parseBoolean(
1173 parser.getAttributeValue(null, ATTR_VALUE));
1174 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1175 disableBluetoothContactSharing = Boolean.parseBoolean(parser
1176 .getAttributeValue(null, ATTR_VALUE));
1177 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1178 disableScreenCapture = Boolean.parseBoolean(
1179 parser.getAttributeValue(null, ATTR_VALUE));
1180 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1181 requireAutoTime = Boolean.parseBoolean(
1182 parser.getAttributeValue(null, ATTR_VALUE));
1183 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1184 forceEphemeralUsers = Boolean.parseBoolean(
1185 parser.getAttributeValue(null, ATTR_VALUE));
1186 } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) {
1187 isNetworkLoggingEnabled = Boolean.parseBoolean(
1188 parser.getAttributeValue(null, ATTR_VALUE));
1189 lastNetworkLoggingNotificationTimeMs = Long.parseLong(
1190 parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION));
1191 numNetworkLoggingNotifications = Integer.parseInt(
1192 parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS));
1193 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1194 disabledKeyguardFeatures = Integer.parseInt(
1195 parser.getAttributeValue(null, ATTR_VALUE));
1196 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1197 readAttributeValues(
1198 parser, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1199 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1200 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1201 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1202 crossProfileWidgetProviders = new ArrayList<>();
1203 readAttributeValues(parser, TAG_PROVIDER, crossProfileWidgetProviders);
1204 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1205 permittedAccessiblityServices = readPackageList(parser, tag);
1206 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1207 permittedInputMethods = readPackageList(parser, tag);
1208 } else if (TAG_PERMITTED_NOTIFICATION_LISTENERS.equals(tag)) {
1209 permittedNotificationListeners = readPackageList(parser, tag);
1210 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1211 keepUninstalledPackages = readPackageList(parser, tag);
1212 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1213 userRestrictions = UserRestrictionsUtils.readRestrictions(parser);
1214 } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) {
1215 readAttributeValues(
1216 parser, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1217 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1218 type = parser.next();
1219 if (type == XmlPullParser.TEXT) {
1220 shortSupportMessage = parser.getText();
1222 Log.w(LOG_TAG, "Missing text when loading short support message");
1224 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1225 type = parser.next();
1226 if (type == XmlPullParser.TEXT) {
1227 longSupportMessage = parser.getText();
1229 Log.w(LOG_TAG, "Missing text when loading long support message");
1231 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1232 Preconditions.checkState(!isParent);
1234 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1235 parentAdmin.readFromXml(parser);
1236 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1237 organizationColor = Integer.parseInt(
1238 parser.getAttributeValue(null, ATTR_VALUE));
1239 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1240 type = parser.next();
1241 if (type == XmlPullParser.TEXT) {
1242 organizationName = parser.getText();
1244 Log.w(LOG_TAG, "Missing text when loading organization name");
1247 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1248 XmlUtils.skipCurrentTag(parser);
1253 private List<String> readPackageList(XmlPullParser parser,
1254 String tag) throws XmlPullParserException, IOException {
1255 List<String> result = new ArrayList<String>();
1256 int outerDepth = parser.getDepth();
1258 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1259 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1260 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1263 String outerTag = parser.getName();
1264 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1265 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1266 if (packageName != null) {
1267 result.add(packageName);
1269 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1272 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1278 private void readAttributeValues(
1279 XmlPullParser parser, String tag, Collection<String> result)
1280 throws XmlPullParserException, IOException {
1282 int outerDepthDAM = parser.getDepth();
1284 while ((typeDAM=parser.next()) != END_DOCUMENT
1285 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1286 if (typeDAM == END_TAG || typeDAM == TEXT) {
1289 String tagDAM = parser.getName();
1290 if (tag.equals(tagDAM)) {
1291 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1293 Slog.e(LOG_TAG, "Expected tag " + tag + " but found " + tagDAM);
1298 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1299 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1300 int outerDepthDAM = parser.getDepth();
1302 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1303 while ((typeDAM=parser.next()) != END_DOCUMENT
1304 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1305 if (typeDAM == END_TAG || typeDAM == TEXT) {
1308 String tagDAM = parser.getName();
1309 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1310 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1311 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1312 result.put(component, trustAgentInfo);
1314 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1320 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1321 throws XmlPullParserException, IOException {
1322 int outerDepthDAM = parser.getDepth();
1324 TrustAgentInfo result = new TrustAgentInfo(null);
1325 while ((typeDAM=parser.next()) != END_DOCUMENT
1326 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1327 if (typeDAM == END_TAG || typeDAM == TEXT) {
1330 String tagDAM = parser.getName();
1331 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1332 result.options = PersistableBundle.restoreFromXml(parser);
1334 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1340 boolean hasUserRestrictions() {
1341 return userRestrictions != null && userRestrictions.size() > 0;
1344 Bundle ensureUserRestrictions() {
1345 if (userRestrictions == null) {
1346 userRestrictions = new Bundle();
1348 return userRestrictions;
1351 void dump(String prefix, PrintWriter pw) {
1352 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1353 pw.print(prefix); pw.print("testOnlyAdmin=");
1354 pw.println(testOnlyAdmin);
1355 pw.print(prefix); pw.println("policies:");
1356 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1358 for (int i=0; i<pols.size(); i++) {
1359 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1362 pw.print(prefix); pw.print("passwordQuality=0x");
1363 pw.println(Integer.toHexString(minimumPasswordMetrics.quality));
1364 pw.print(prefix); pw.print("minimumPasswordLength=");
1365 pw.println(minimumPasswordMetrics.length);
1366 pw.print(prefix); pw.print("passwordHistoryLength=");
1367 pw.println(passwordHistoryLength);
1368 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1369 pw.println(minimumPasswordMetrics.upperCase);
1370 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1371 pw.println(minimumPasswordMetrics.lowerCase);
1372 pw.print(prefix); pw.print("minimumPasswordLetters=");
1373 pw.println(minimumPasswordMetrics.letters);
1374 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1375 pw.println(minimumPasswordMetrics.numeric);
1376 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1377 pw.println(minimumPasswordMetrics.symbols);
1378 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1379 pw.println(minimumPasswordMetrics.nonLetter);
1380 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1381 pw.println(maximumTimeToUnlock);
1382 pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1383 pw.println(strongAuthUnlockTimeout);
1384 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1385 pw.println(maximumFailedPasswordsForWipe);
1386 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1387 pw.println(specifiesGlobalProxy);
1388 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1389 pw.println(passwordExpirationTimeout);
1390 pw.print(prefix); pw.print("passwordExpirationDate=");
1391 pw.println(passwordExpirationDate);
1392 if (globalProxySpec != null) {
1393 pw.print(prefix); pw.print("globalProxySpec=");
1394 pw.println(globalProxySpec);
1396 if (globalProxyExclusionList != null) {
1397 pw.print(prefix); pw.print("globalProxyEclusionList=");
1398 pw.println(globalProxyExclusionList);
1400 pw.print(prefix); pw.print("encryptionRequested=");
1401 pw.println(encryptionRequested);
1402 pw.print(prefix); pw.print("disableCamera=");
1403 pw.println(disableCamera);
1404 pw.print(prefix); pw.print("disableCallerId=");
1405 pw.println(disableCallerId);
1406 pw.print(prefix); pw.print("disableContactsSearch=");
1407 pw.println(disableContactsSearch);
1408 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1409 pw.println(disableBluetoothContactSharing);
1410 pw.print(prefix); pw.print("disableScreenCapture=");
1411 pw.println(disableScreenCapture);
1412 pw.print(prefix); pw.print("requireAutoTime=");
1413 pw.println(requireAutoTime);
1414 pw.print(prefix); pw.print("forceEphemeralUsers=");
1415 pw.println(forceEphemeralUsers);
1416 pw.print(prefix); pw.print("isNetworkLoggingEnabled=");
1417 pw.println(isNetworkLoggingEnabled);
1418 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1419 pw.println(disabledKeyguardFeatures);
1420 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1421 pw.println(crossProfileWidgetProviders);
1422 if (permittedAccessiblityServices != null) {
1423 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1424 pw.println(permittedAccessiblityServices);
1426 if (permittedInputMethods != null) {
1427 pw.print(prefix); pw.print("permittedInputMethods=");
1428 pw.println(permittedInputMethods);
1430 if (permittedNotificationListeners != null) {
1431 pw.print(prefix); pw.print("permittedNotificationListeners=");
1432 pw.println(permittedNotificationListeners);
1434 if (keepUninstalledPackages != null) {
1435 pw.print(prefix); pw.print("keepUninstalledPackages=");
1436 pw.println(keepUninstalledPackages);
1438 pw.print(prefix); pw.print("organizationColor=");
1439 pw.println(organizationColor);
1440 if (organizationName != null) {
1441 pw.print(prefix); pw.print("organizationName=");
1442 pw.println(organizationName);
1444 pw.print(prefix); pw.println("userRestrictions:");
1445 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1446 pw.print(prefix); pw.print("defaultEnabledRestrictionsAlreadySet=");
1447 pw.println(defaultEnabledRestrictionsAlreadySet);
1448 pw.print(prefix); pw.print("isParent=");
1449 pw.println(isParent);
1450 if (parentAdmin != null) {
1451 pw.print(prefix); pw.println("parentAdmin:");
1452 parentAdmin.dump(prefix + " ", pw);
1457 private void handlePackagesChanged(@Nullable String packageName, int userHandle) {
1458 boolean removedAdmin = false;
1460 Slog.d(LOG_TAG, "Handling package changes package " + packageName
1461 + " for user " + userHandle);
1463 DevicePolicyData policy = getUserData(userHandle);
1464 synchronized (this) {
1465 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1466 ActiveAdmin aa = policy.mAdminList.get(i);
1468 // If we're checking all packages or if the specific one we're checking matches,
1469 // then check if the package and receiver still exist.
1470 final String adminPackage = aa.info.getPackageName();
1471 if (packageName == null || packageName.equals(adminPackage)) {
1472 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1473 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1474 PackageManager.MATCH_DIRECT_BOOT_AWARE
1475 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1476 userHandle) == null) {
1477 removedAdmin = true;
1478 policy.mAdminList.remove(i);
1479 policy.mAdminMap.remove(aa.info.getComponent());
1482 } catch (RemoteException re) {
1483 // Shouldn't happen.
1487 validatePasswordOwnerLocked(policy);
1490 boolean removedDelegate = false;
1492 // Check if a delegate was removed.
1493 for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
1494 final String delegatePackage = policy.mDelegationMap.keyAt(i);
1495 if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
1496 policy.mDelegationMap.removeAt(i);
1497 removedDelegate = true;
1501 // If it's an owner package, we may need to refresh the bound connection.
1502 final ComponentName owner = getOwnerComponent(userHandle);
1503 if ((packageName != null) && (owner != null)
1504 && (owner.getPackageName().equals(packageName))) {
1505 startOwnerService(userHandle, "package-broadcast");
1508 // Persist updates if the removed package was an admin or delegate.
1509 if (removedAdmin || removedDelegate) {
1510 saveSettingsLocked(policy.mUserHandle);
1514 // The removed admin might have disabled camera, so update user restrictions.
1515 pushUserRestrictions(userHandle);
1519 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1521 return targetPackage != null
1522 && (changedPackage == null || changedPackage.equals(targetPackage))
1523 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1524 } catch (RemoteException e) {
1532 * Unit test will subclass it to inject mocks.
1535 static class Injector {
1537 public final Context mContext;
1539 Injector(Context context) {
1543 Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
1544 final String packageName = mContext.getPackageName();
1545 return mContext.createPackageContextAsUser(packageName, 0, user);
1548 Resources getResources() {
1549 return mContext.getResources();
1552 Owners newOwners() {
1553 return new Owners(getUserManager(), getUserManagerInternal(),
1554 getPackageManagerInternal());
1557 UserManager getUserManager() {
1558 return UserManager.get(mContext);
1561 UserManagerInternal getUserManagerInternal() {
1562 return LocalServices.getService(UserManagerInternal.class);
1565 PackageManagerInternal getPackageManagerInternal() {
1566 return LocalServices.getService(PackageManagerInternal.class);
1569 NotificationManager getNotificationManager() {
1570 return mContext.getSystemService(NotificationManager.class);
1573 IIpConnectivityMetrics getIIpConnectivityMetrics() {
1574 return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1575 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1578 PackageManager getPackageManager() {
1579 return mContext.getPackageManager();
1582 PowerManagerInternal getPowerManagerInternal() {
1583 return LocalServices.getService(PowerManagerInternal.class);
1586 TelephonyManager getTelephonyManager() {
1587 return TelephonyManager.from(mContext);
1590 TrustManager getTrustManager() {
1591 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1594 AlarmManager getAlarmManager() {
1595 return (AlarmManager) mContext.getSystemService(AlarmManager.class);
1598 IWindowManager getIWindowManager() {
1599 return IWindowManager.Stub
1600 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1603 IActivityManager getIActivityManager() {
1604 return ActivityManager.getService();
1607 IPackageManager getIPackageManager() {
1608 return AppGlobals.getPackageManager();
1611 IBackupManager getIBackupManager() {
1612 return IBackupManager.Stub.asInterface(
1613 ServiceManager.getService(Context.BACKUP_SERVICE));
1616 IAudioService getIAudioService() {
1617 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1620 boolean isBuildDebuggable() {
1621 return Build.IS_DEBUGGABLE;
1624 LockPatternUtils newLockPatternUtils() {
1625 return new LockPatternUtils(mContext);
1628 boolean storageManagerIsFileBasedEncryptionEnabled() {
1629 return StorageManager.isFileEncryptedNativeOnly();
1632 boolean storageManagerIsNonDefaultBlockEncrypted() {
1633 long identity = Binder.clearCallingIdentity();
1635 return StorageManager.isNonDefaultBlockEncrypted();
1637 Binder.restoreCallingIdentity(identity);
1641 boolean storageManagerIsEncrypted() {
1642 return StorageManager.isEncrypted();
1645 boolean storageManagerIsEncryptable() {
1646 return StorageManager.isEncryptable();
1649 Looper getMyLooper() {
1650 return Looper.myLooper();
1653 WifiManager getWifiManager() {
1654 return mContext.getSystemService(WifiManager.class);
1657 long binderClearCallingIdentity() {
1658 return Binder.clearCallingIdentity();
1661 void binderRestoreCallingIdentity(long token) {
1662 Binder.restoreCallingIdentity(token);
1665 int binderGetCallingUid() {
1666 return Binder.getCallingUid();
1669 int binderGetCallingPid() {
1670 return Binder.getCallingPid();
1673 UserHandle binderGetCallingUserHandle() {
1674 return Binder.getCallingUserHandle();
1677 boolean binderIsCallingUidMyUid() {
1678 return getCallingUid() == Process.myUid();
1681 final int userHandleGetCallingUserId() {
1682 return UserHandle.getUserId(binderGetCallingUid());
1685 File environmentGetUserSystemDirectory(int userId) {
1686 return Environment.getUserSystemDirectory(userId);
1689 void powerManagerGoToSleep(long time, int reason, int flags) {
1690 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1693 void powerManagerReboot(String reason) {
1694 mContext.getSystemService(PowerManager.class).reboot(reason);
1697 void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force,
1698 boolean wipeEuicc) throws IOException {
1699 RecoverySystem.rebootWipeUserData(mContext, shutdown, reason, force, wipeEuicc);
1702 boolean systemPropertiesGetBoolean(String key, boolean def) {
1703 return SystemProperties.getBoolean(key, def);
1706 long systemPropertiesGetLong(String key, long def) {
1707 return SystemProperties.getLong(key, def);
1710 String systemPropertiesGet(String key, String def) {
1711 return SystemProperties.get(key, def);
1714 String systemPropertiesGet(String key) {
1715 return SystemProperties.get(key);
1718 void systemPropertiesSet(String key, String value) {
1719 SystemProperties.set(key, value);
1722 boolean userManagerIsSplitSystemUser() {
1723 return UserManager.isSplitSystemUser();
1726 String getDevicePolicyFilePathForSystemUser() {
1727 return "/data/system/";
1730 PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode,
1731 @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
1732 return PendingIntent.getActivityAsUser(
1733 context, requestCode, intent, flags, options, user);
1736 void registerContentObserver(Uri uri, boolean notifyForDescendents,
1737 ContentObserver observer, int userHandle) {
1738 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1739 observer, userHandle);
1742 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1743 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1744 name, def, userHandle);
1747 String settingsSecureGetStringForUser(String name, int userHandle) {
1748 return Settings.Secure.getStringForUser(mContext.getContentResolver(), name,
1752 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1753 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1754 name, value, userHandle);
1757 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1758 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1759 name, value, userHandle);
1762 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1763 Settings.Global.putStringForUser(mContext.getContentResolver(),
1764 name, value, userHandle);
1767 void settingsSecurePutInt(String name, int value) {
1768 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1771 int settingsGlobalGetInt(String name, int def) {
1772 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1775 String settingsGlobalGetString(String name) {
1776 return Settings.Global.getString(mContext.getContentResolver(), name);
1779 void settingsGlobalPutInt(String name, int value) {
1780 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1783 void settingsSecurePutString(String name, String value) {
1784 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1787 void settingsGlobalPutString(String name, String value) {
1788 Settings.Global.putString(mContext.getContentResolver(), name, value);
1791 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1792 SecurityLog.setLoggingEnabledProperty(enabled);
1795 boolean securityLogGetLoggingEnabledProperty() {
1796 return SecurityLog.getLoggingEnabledProperty();
1799 boolean securityLogIsLoggingEnabled() {
1800 return SecurityLog.isLoggingEnabled();
1803 KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException {
1804 return KeyChain.bindAsUser(mContext, user);
1809 * Instantiates the service.
1811 public DevicePolicyManagerService(Context context) {
1812 this(new Injector(context));
1816 DevicePolicyManagerService(Injector injector) {
1817 mInjector = injector;
1818 mContext = Preconditions.checkNotNull(injector.mContext);
1819 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1820 mConstants = DevicePolicyConstants.loadFromString(
1821 mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS));
1823 mOwners = Preconditions.checkNotNull(injector.newOwners());
1825 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1826 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1827 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1828 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1830 mLocalService = new LocalService();
1831 mLockPatternUtils = injector.newLockPatternUtils();
1833 // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false?
1834 mSecurityLogMonitor = new SecurityLogMonitor(this);
1836 mHasFeature = mInjector.getPackageManager()
1837 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1838 mIsWatch = mInjector.getPackageManager()
1839 .hasSystemFeature(PackageManager.FEATURE_WATCH);
1840 mBackgroundHandler = BackgroundThread.getHandler();
1842 // Needed when mHasFeature == false, because it controls the certificate warning text.
1843 mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler);
1845 mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants);
1848 // Skip the rest of the initialization
1852 IntentFilter filter = new IntentFilter();
1853 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1854 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1855 filter.addAction(Intent.ACTION_USER_ADDED);
1856 filter.addAction(Intent.ACTION_USER_REMOVED);
1857 filter.addAction(Intent.ACTION_USER_STARTED);
1858 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1859 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1860 filter = new IntentFilter();
1861 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1862 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1863 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1864 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1865 filter.addDataScheme("package");
1866 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1867 filter = new IntentFilter();
1868 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1869 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1871 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1873 mSetupContentObserver = new SetupContentObserver(mHandler);
1877 * Creates and loads the policy data from xml.
1878 * @param userHandle the user for whom to load the policy data
1882 DevicePolicyData getUserData(int userHandle) {
1883 synchronized (this) {
1884 DevicePolicyData policy = mUserData.get(userHandle);
1885 if (policy == null) {
1886 policy = new DevicePolicyData(userHandle);
1887 mUserData.append(userHandle, policy);
1888 loadSettingsLocked(policy, userHandle);
1895 * Creates and loads the policy data from xml for data that is shared between
1896 * various profiles of a user. In contrast to {@link #getUserData(int)}
1897 * it allows access to data of users other than the calling user.
1899 * This function should only be used for shared data, e.g. everything regarding
1900 * passwords and should be removed once multiple screen locks are present.
1901 * @param userHandle the user for whom to load the policy data
1904 DevicePolicyData getUserDataUnchecked(int userHandle) {
1905 long ident = mInjector.binderClearCallingIdentity();
1907 return getUserData(userHandle);
1909 mInjector.binderRestoreCallingIdentity(ident);
1913 void removeUserData(int userHandle) {
1914 synchronized (this) {
1915 if (userHandle == UserHandle.USER_SYSTEM) {
1916 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1919 mOwners.removeProfileOwner(userHandle);
1920 mOwners.writeProfileOwner(userHandle);
1922 DevicePolicyData policy = mUserData.get(userHandle);
1923 if (policy != null) {
1924 mUserData.remove(userHandle);
1926 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1927 DEVICE_POLICIES_XML);
1928 policyFile.delete();
1929 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1931 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1935 synchronized (this) {
1937 setDeviceOwnerSystemPropertyLocked();
1938 findOwnerComponentIfNecessaryLocked();
1939 migrateUserRestrictionsIfNecessaryLocked();
1940 maybeSetDefaultDeviceOwnerUserRestrictionsLocked();
1942 // TODO PO may not have a class name either due to b/17652534. Address that too.
1944 updateDeviceOwnerLocked();
1948 /** Apply default restrictions that haven't been applied to device owners yet. */
1949 private void maybeSetDefaultDeviceOwnerUserRestrictionsLocked() {
1950 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
1951 if (deviceOwner != null) {
1952 maybeSetDefaultRestrictionsForAdminLocked(mOwners.getDeviceOwnerUserId(),
1953 deviceOwner, UserRestrictionsUtils.getDefaultEnabledForDeviceOwner());
1957 /** Apply default restrictions that haven't been applied to profile owners yet. */
1958 private void maybeSetDefaultProfileOwnerUserRestrictions() {
1959 synchronized (this) {
1960 for (final int userId : mOwners.getProfileOwnerKeys()) {
1961 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
1962 // The following restrictions used to be applied to managed profiles by different
1963 // means (via Settings or by disabling components). Now they are proper user
1964 // restrictions so we apply them to managed profile owners. Non-managed secondary
1965 // users didn't have those restrictions so we skip them to keep existing behavior.
1966 if (profileOwner == null || !mUserManager.isManagedProfile(userId)) {
1969 maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner,
1970 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
1971 ensureUnknownSourcesRestrictionForProfileOwnerLocked(
1972 userId, profileOwner, false /* newOwner */);
1978 * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the
1979 * set of restrictions for this profile owner.
1981 private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId,
1982 ActiveAdmin profileOwner, boolean newOwner) {
1983 if (newOwner || mInjector.settingsSecureGetIntForUser(
1984 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
1985 profileOwner.ensureUserRestrictions().putBoolean(
1986 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
1987 saveUserRestrictionsLocked(userId);
1988 mInjector.settingsSecurePutIntForUser(
1989 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
1994 * Apply default restrictions that haven't been applied to a given admin yet.
1996 private void maybeSetDefaultRestrictionsForAdminLocked(
1997 int userId, ActiveAdmin admin, Set<String> defaultRestrictions) {
1998 if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
1999 return; // The same set of default restrictions has been already applied.
2001 Slog.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId);
2004 Slog.d(LOG_TAG,"Default enabled restrictions: "
2005 + defaultRestrictions
2006 + ". Restrictions already enabled: "
2007 + admin.defaultEnabledRestrictionsAlreadySet);
2010 final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions);
2011 restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet);
2012 if (!restrictionsToSet.isEmpty()) {
2013 for (final String restriction : restrictionsToSet) {
2014 admin.ensureUserRestrictions().putBoolean(restriction, true);
2016 admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet);
2017 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet);
2018 saveUserRestrictionsLocked(userId);
2022 private void setDeviceOwnerSystemPropertyLocked() {
2023 final boolean deviceProvisioned =
2024 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0;
2025 // If the device is not provisioned and there is currently no device owner, do not set the
2026 // read-only system property yet, since Device owner may still be provisioned. For Wear
2027 // devices, if there is already a device owner then it's OK to set the property to true now,
2028 // regardless the provision state.
2029 final boolean isWatchWithDeviceOwner = mIsWatch && mOwners.hasDeviceOwner();
2030 if (!isWatchWithDeviceOwner && !deviceProvisioned) {
2033 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
2034 // always false at this point.
2035 if (StorageManager.inCryptKeeperBounce()) {
2039 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
2040 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
2042 if (mOwners.hasDeviceOwner()) {
2043 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
2044 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
2046 if (mInjector.securityLogGetLoggingEnabledProperty()) {
2047 mSecurityLogMonitor.start();
2048 maybePauseDeviceWideLoggingLocked();
2051 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
2052 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
2057 private void findOwnerComponentIfNecessaryLocked() {
2058 if (!mOwners.hasDeviceOwner()) {
2061 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
2063 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
2064 return; // Already a full component name.
2067 final ComponentName doComponent = findAdminComponentWithPackageLocked(
2068 doComponentName.getPackageName(),
2069 mOwners.getDeviceOwnerUserId());
2070 if (doComponent == null) {
2071 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
2073 mOwners.setDeviceOwnerWithRestrictionsMigrated(
2075 mOwners.getDeviceOwnerName(),
2076 mOwners.getDeviceOwnerUserId(),
2077 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
2078 mOwners.writeDeviceOwner();
2080 Log.v(LOG_TAG, "Device owner component filled in");
2086 * We didn't use to persist user restrictions for each owners but only persisted in user
2089 private void migrateUserRestrictionsIfNecessaryLocked() {
2090 boolean migrated = false;
2091 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
2092 // except for the "system controlled" ones.
2093 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
2095 Log.v(LOG_TAG, "Migrating DO user restrictions");
2099 // Migrate user 0 restrictions to DO.
2100 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
2102 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
2103 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
2105 // Push DO user restrictions to user manager.
2106 pushUserRestrictions(UserHandle.USER_SYSTEM);
2108 mOwners.setDeviceOwnerUserRestrictionsMigrated();
2113 // The following restrictions can be set on secondary users by the device owner, so we
2114 // assume they're not from the PO.
2115 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
2116 UserManager.DISALLOW_OUTGOING_CALLS,
2117 UserManager.DISALLOW_SMS);
2119 for (UserInfo ui : mUserManager.getUsers()) {
2120 final int userId = ui.id;
2121 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
2123 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
2127 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
2129 final Set<String> exceptionList =
2130 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
2132 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
2133 exceptionList, /* isDeviceOwner =*/ false);
2135 // Note if a secondary user has no PO but has a DA that disables camera, we
2136 // don't get here and won't push the camera user restriction to UserManager
2137 // here. That's okay because we'll push user restrictions anyway when a user
2138 // starts. But we still do it because we want to let user manager persist
2140 pushUserRestrictions(userId);
2142 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
2145 if (VERBOSE_LOG && migrated) {
2146 Log.v(LOG_TAG, "User restrictions migrated.");
2150 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
2151 Set<String> exceptionList, boolean isDeviceOwner) {
2152 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
2153 user.getIdentifier());
2155 final Bundle newBaseRestrictions = new Bundle();
2156 final Bundle newOwnerRestrictions = new Bundle();
2158 for (String key : origRestrictions.keySet()) {
2159 if (!origRestrictions.getBoolean(key)) {
2162 final boolean canOwnerChange = isDeviceOwner
2163 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
2164 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
2166 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
2167 newBaseRestrictions.putBoolean(key, true);
2169 newOwnerRestrictions.putBoolean(key, true);
2174 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
2175 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
2176 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
2178 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
2179 newBaseRestrictions);
2181 if (admin != null) {
2182 admin.ensureUserRestrictions().clear();
2183 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
2185 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
2187 saveSettingsLocked(user.getIdentifier());
2190 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
2191 final DevicePolicyData policy = getUserData(userId);
2192 final int n = policy.mAdminList.size();
2193 ComponentName found = null;
2195 for (int i = 0; i < n; i++) {
2196 final ActiveAdmin admin = policy.mAdminList.get(i);
2197 if (packageName.equals(admin.info.getPackageName())) {
2200 found = admin.info.getComponent();
2206 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
2212 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
2213 * reminders. Clears alarm if no expirations are configured.
2215 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
2216 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
2217 final long now = System.currentTimeMillis();
2218 final long timeToExpire = expiration - now;
2219 final long alarmTime;
2220 if (expiration == 0) {
2221 // No expirations are currently configured: Cancel alarm.
2223 } else if (timeToExpire <= 0) {
2224 // The password has already expired: Repeat every 24 hours.
2225 alarmTime = now + MS_PER_DAY;
2227 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
2228 // the expiration time.
2229 long alarmInterval = timeToExpire % MS_PER_DAY;
2230 if (alarmInterval == 0) {
2231 alarmInterval = MS_PER_DAY;
2233 alarmTime = now + alarmInterval;
2236 long token = mInjector.binderClearCallingIdentity();
2238 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
2239 AlarmManager am = mInjector.getAlarmManager();
2240 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2241 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2242 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
2243 UserHandle.of(affectedUserHandle));
2245 if (alarmTime != 0) {
2246 am.set(AlarmManager.RTC, alarmTime, pi);
2249 mInjector.binderRestoreCallingIdentity(token);
2253 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2254 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2256 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2257 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2263 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2265 enforceManagedProfile(userHandle, "call APIs on the parent profile");
2267 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2268 if (admin != null && parent) {
2269 admin = admin.getParentActiveAdmin();
2274 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2275 throws SecurityException {
2276 final int callingUid = mInjector.binderGetCallingUid();
2278 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
2279 if (result != null) {
2284 final int userId = UserHandle.getUserId(callingUid);
2285 final DevicePolicyData policy = getUserData(userId);
2286 ActiveAdmin admin = policy.mAdminMap.get(who);
2287 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2288 throw new SecurityException("Admin " + admin.info.getComponent()
2289 + " does not own the device");
2291 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2292 throw new SecurityException("Admin " + admin.info.getComponent()
2293 + " does not own the profile");
2295 throw new SecurityException("Admin " + admin.info.getComponent()
2296 + " did not specify uses-policy for: "
2297 + admin.info.getTagForPolicy(reqPolicy));
2299 throw new SecurityException("No active admin owned by uid "
2300 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
2304 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2305 throws SecurityException {
2307 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2308 "call APIs on the parent profile");
2310 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2311 return parent ? admin.getParentActiveAdmin() : admin;
2314 * Find the admin for the component and userId bit of the uid, then check
2315 * the admin's uid matches the uid.
2317 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2318 final int userId = UserHandle.getUserId(uid);
2319 final DevicePolicyData policy = getUserData(userId);
2320 ActiveAdmin admin = policy.mAdminMap.get(who);
2321 if (admin == null) {
2322 throw new SecurityException("No active admin " + who);
2324 if (admin.getUid() != uid) {
2325 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2330 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2332 // Try to find an admin which can use reqPolicy
2333 final int userId = UserHandle.getUserId(uid);
2334 final DevicePolicyData policy = getUserData(userId);
2336 ActiveAdmin admin = policy.mAdminMap.get(who);
2337 if (admin == null) {
2338 throw new SecurityException("No active admin " + who);
2340 if (admin.getUid() != uid) {
2341 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2343 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2347 for (ActiveAdmin admin : policy.mAdminList) {
2348 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2359 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2361 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2362 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2364 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2366 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2367 // DO always has the PO power.
2368 return ownsDevice || ownsProfile;
2370 return admin.info.usesPolicy(reqPolicy);
2374 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2375 sendAdminCommandLocked(admin, action, null);
2378 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2379 sendAdminCommandLocked(admin, action, null, result);
2383 * Send an update to one specific admin, get notified when that admin returns a result.
2385 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2386 BroadcastReceiver result) {
2387 Intent intent = new Intent(action);
2388 intent.setComponent(admin.info.getComponent());
2389 if (UserManager.isDeviceInDemoMode(mContext)) {
2390 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2392 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2393 intent.putExtra("expiration", admin.passwordExpirationDate);
2395 if (adminExtras != null) {
2396 intent.putExtras(adminExtras);
2398 if (result != null) {
2399 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2400 null, result, mHandler, Activity.RESULT_OK, null, null);
2402 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2407 * Send an update to all admins of a user that enforce a specified policy.
2409 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) {
2410 final DevicePolicyData policy = getUserData(userHandle);
2411 final int count = policy.mAdminList.size();
2412 for (int i = 0; i < count; i++) {
2413 final ActiveAdmin admin = policy.mAdminList.get(i);
2414 if (admin.info.usesPolicy(reqPolicy)) {
2415 sendAdminCommandLocked(admin, action, adminExtras, null);
2421 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2422 * enforce a specified policy.
2424 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2425 int userHandle, Bundle adminExtras) {
2426 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2427 for (int profileId : profileIds) {
2428 sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras);
2433 * Sends a broadcast to each profile that share the password unlock with the given user id.
2435 private void sendAdminCommandForLockscreenPoliciesLocked(
2436 String action, int reqPolicy, int userHandle) {
2437 final Bundle extras = new Bundle();
2438 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
2439 if (isSeparateProfileChallengeEnabled(userHandle)) {
2440 sendAdminCommandLocked(action, reqPolicy, userHandle, extras);
2442 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras);
2446 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2447 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2448 DevicePolicyData policy = getUserData(userHandle);
2449 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2450 policy.mRemovingAdmins.add(adminReceiver);
2451 sendAdminCommandLocked(admin,
2452 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2453 new BroadcastReceiver() {
2455 public void onReceive(Context context, Intent intent) {
2456 removeAdminArtifacts(adminReceiver, userHandle);
2457 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2464 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2465 boolean throwForMissiongPermission) {
2469 enforceFullCrossUsersPermission(userHandle);
2470 ActivityInfo ai = null;
2472 ai = mIPackageManager.getReceiverInfo(adminName,
2473 PackageManager.GET_META_DATA |
2474 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2475 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2476 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2477 } catch (RemoteException e) {
2478 // shouldn't happen.
2481 throw new IllegalArgumentException("Unknown admin: " + adminName);
2484 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2485 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2486 + permission.BIND_DEVICE_ADMIN;
2487 Slog.w(LOG_TAG, message);
2488 if (throwForMissiongPermission &&
2489 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2490 throw new IllegalArgumentException(message);
2495 return new DeviceAdminInfo(mContext, ai);
2496 } catch (XmlPullParserException | IOException e) {
2497 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2503 private JournaledFile makeJournaledFile(int userHandle) {
2504 final String base = userHandle == UserHandle.USER_SYSTEM
2505 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2506 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2507 DEVICE_POLICIES_XML).getAbsolutePath();
2509 Log.v(LOG_TAG, "Opening " + base);
2511 return new JournaledFile(new File(base), new File(base + ".tmp"));
2514 private void saveSettingsLocked(int userHandle) {
2515 DevicePolicyData policy = getUserData(userHandle);
2516 JournaledFile journal = makeJournaledFile(userHandle);
2517 FileOutputStream stream = null;
2519 stream = new FileOutputStream(journal.chooseForWrite(), false);
2520 XmlSerializer out = new FastXmlSerializer();
2521 out.setOutput(stream, StandardCharsets.UTF_8.name());
2522 out.startDocument(null, true);
2524 out.startTag(null, "policies");
2525 if (policy.mRestrictionsProvider != null) {
2526 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2527 policy.mRestrictionsProvider.flattenToString());
2529 if (policy.mUserSetupComplete) {
2530 out.attribute(null, ATTR_SETUP_COMPLETE,
2531 Boolean.toString(true));
2533 if (policy.mPaired) {
2534 out.attribute(null, ATTR_DEVICE_PAIRED,
2535 Boolean.toString(true));
2537 if (policy.mDeviceProvisioningConfigApplied) {
2538 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2539 Boolean.toString(true));
2541 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2542 out.attribute(null, ATTR_PROVISIONING_STATE,
2543 Integer.toString(policy.mUserProvisioningState));
2545 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2546 out.attribute(null, ATTR_PERMISSION_POLICY,
2547 Integer.toString(policy.mPermissionPolicy));
2550 // Serialize delegations.
2551 for (int i = 0; i < policy.mDelegationMap.size(); ++i) {
2552 final String delegatePackage = policy.mDelegationMap.keyAt(i);
2553 final List<String> scopes = policy.mDelegationMap.valueAt(i);
2555 // Every "delegation" tag serializes the information of one delegate-scope pair.
2556 for (String scope : scopes) {
2557 out.startTag(null, "delegation");
2558 out.attribute(null, "delegatePackage", delegatePackage);
2559 out.attribute(null, "scope", scope);
2560 out.endTag(null, "delegation");
2564 final int N = policy.mAdminList.size();
2565 for (int i=0; i<N; i++) {
2566 ActiveAdmin ap = policy.mAdminList.get(i);
2568 out.startTag(null, "admin");
2569 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2571 out.endTag(null, "admin");
2575 if (policy.mPasswordOwner >= 0) {
2576 out.startTag(null, "password-owner");
2577 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2578 out.endTag(null, "password-owner");
2581 if (policy.mFailedPasswordAttempts != 0) {
2582 out.startTag(null, "failed-password-attempts");
2583 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2584 out.endTag(null, "failed-password-attempts");
2587 // For FDE devices only, we save this flag so we can report on password sufficiency
2588 // before the user enters their password for the first time after a reboot. For
2589 // security reasons, we don't want to store the full set of active password metrics.
2590 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2591 out.startTag(null, TAG_PASSWORD_VALIDITY);
2592 out.attribute(null, ATTR_VALUE,
2593 Boolean.toString(policy.mPasswordValidAtLastCheckpoint));
2594 out.endTag(null, TAG_PASSWORD_VALIDITY);
2597 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2598 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2599 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2600 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2603 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2604 String component = policy.mLockTaskPackages.get(i);
2605 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2606 out.attribute(null, "name", component);
2607 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2610 if (policy.mStatusBarDisabled) {
2611 out.startTag(null, TAG_STATUS_BAR);
2612 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2613 out.endTag(null, TAG_STATUS_BAR);
2616 if (policy.doNotAskCredentialsOnBoot) {
2617 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2618 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2621 for (String id : policy.mAffiliationIds) {
2622 out.startTag(null, TAG_AFFILIATION_ID);
2623 out.attribute(null, ATTR_ID, id);
2624 out.endTag(null, TAG_AFFILIATION_ID);
2627 if (policy.mLastSecurityLogRetrievalTime >= 0) {
2628 out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2629 out.attribute(null, ATTR_VALUE,
2630 Long.toString(policy.mLastSecurityLogRetrievalTime));
2631 out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2634 if (policy.mLastBugReportRequestTime >= 0) {
2635 out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2636 out.attribute(null, ATTR_VALUE,
2637 Long.toString(policy.mLastBugReportRequestTime));
2638 out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2641 if (policy.mLastNetworkLogsRetrievalTime >= 0) {
2642 out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2643 out.attribute(null, ATTR_VALUE,
2644 Long.toString(policy.mLastNetworkLogsRetrievalTime));
2645 out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2648 if (policy.mAdminBroadcastPending) {
2649 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2650 out.attribute(null, ATTR_VALUE,
2651 Boolean.toString(policy.mAdminBroadcastPending));
2652 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2655 if (policy.mInitBundle != null) {
2656 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2657 policy.mInitBundle.saveToXml(out);
2658 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2661 if (policy.mPasswordTokenHandle != 0) {
2662 out.startTag(null, TAG_PASSWORD_TOKEN_HANDLE);
2663 out.attribute(null, ATTR_VALUE,
2664 Long.toString(policy.mPasswordTokenHandle));
2665 out.endTag(null, TAG_PASSWORD_TOKEN_HANDLE);
2668 if (policy.mCurrentInputMethodSet) {
2669 out.startTag(null, TAG_CURRENT_INPUT_METHOD_SET);
2670 out.endTag(null, TAG_CURRENT_INPUT_METHOD_SET);
2673 for (final String cert : policy.mOwnerInstalledCaCerts) {
2674 out.startTag(null, TAG_OWNER_INSTALLED_CA_CERT);
2675 out.attribute(null, ATTR_ALIAS, cert);
2676 out.endTag(null, TAG_OWNER_INSTALLED_CA_CERT);
2679 out.endTag(null, "policies");
2683 FileUtils.sync(stream);
2686 sendChangedNotification(userHandle);
2687 } catch (XmlPullParserException | IOException e) {
2688 Slog.w(LOG_TAG, "failed writing file", e);
2690 if (stream != null) {
2693 } catch (IOException ex) {
2700 private void sendChangedNotification(int userHandle) {
2701 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2702 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2703 long ident = mInjector.binderClearCallingIdentity();
2705 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2707 mInjector.binderRestoreCallingIdentity(ident);
2711 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2712 JournaledFile journal = makeJournaledFile(userHandle);
2713 FileInputStream stream = null;
2714 File file = journal.chooseForRead();
2715 boolean needsRewrite = false;
2717 stream = new FileInputStream(file);
2718 XmlPullParser parser = Xml.newPullParser();
2719 parser.setInput(stream, StandardCharsets.UTF_8.name());
2722 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2723 && type != XmlPullParser.START_TAG) {
2725 String tag = parser.getName();
2726 if (!"policies".equals(tag)) {
2727 throw new XmlPullParserException(
2728 "Settings do not start with policies tag: found " + tag);
2731 // Extract the permission provider component name if available
2732 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2733 if (permissionProvider != null) {
2734 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2736 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2737 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2738 policy.mUserSetupComplete = true;
2740 String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
2741 if (paired != null && Boolean.toString(true).equals(paired)) {
2742 policy.mPaired = true;
2744 String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2745 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2746 if (deviceProvisioningConfigApplied != null
2747 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2748 policy.mDeviceProvisioningConfigApplied = true;
2750 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2751 if (!TextUtils.isEmpty(provisioningState)) {
2752 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2754 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2755 if (!TextUtils.isEmpty(permissionPolicy)) {
2756 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2758 // Check for delegation compatibility with pre-O.
2759 // TODO(edmanp) remove in P.
2761 final String certDelegate = parser.getAttributeValue(null,
2762 ATTR_DELEGATED_CERT_INSTALLER);
2763 if (certDelegate != null) {
2764 List<String> scopes = policy.mDelegationMap.get(certDelegate);
2765 if (scopes == null) {
2766 scopes = new ArrayList<>();
2767 policy.mDelegationMap.put(certDelegate, scopes);
2769 if (!scopes.contains(DELEGATION_CERT_INSTALL)) {
2770 scopes.add(DELEGATION_CERT_INSTALL);
2771 needsRewrite = true;
2774 final String appRestrictionsDelegate = parser.getAttributeValue(null,
2775 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2776 if (appRestrictionsDelegate != null) {
2777 List<String> scopes = policy.mDelegationMap.get(appRestrictionsDelegate);
2778 if (scopes == null) {
2779 scopes = new ArrayList<>();
2780 policy.mDelegationMap.put(appRestrictionsDelegate, scopes);
2782 if (!scopes.contains(DELEGATION_APP_RESTRICTIONS)) {
2783 scopes.add(DELEGATION_APP_RESTRICTIONS);
2784 needsRewrite = true;
2789 type = parser.next();
2790 int outerDepth = parser.getDepth();
2791 policy.mLockTaskPackages.clear();
2792 policy.mAdminList.clear();
2793 policy.mAdminMap.clear();
2794 policy.mAffiliationIds.clear();
2795 policy.mOwnerInstalledCaCerts.clear();
2796 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2797 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2798 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2801 tag = parser.getName();
2802 if ("admin".equals(tag)) {
2803 String name = parser.getAttributeValue(null, "name");
2805 DeviceAdminInfo dai = findAdmin(
2806 ComponentName.unflattenFromString(name), userHandle,
2807 /* throwForMissionPermission= */ false);
2809 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2811 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2812 + dai.getActivityInfo().applicationInfo.uid + " for user "
2816 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2817 ap.readFromXml(parser);
2818 policy.mAdminMap.put(ap.info.getComponent(), ap);
2820 } catch (RuntimeException e) {
2821 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2823 } else if ("delegation".equals(tag)) {
2824 // Parse delegation info.
2825 final String delegatePackage = parser.getAttributeValue(null,
2827 final String scope = parser.getAttributeValue(null, "scope");
2829 // Get a reference to the scopes list for the delegatePackage.
2830 List<String> scopes = policy.mDelegationMap.get(delegatePackage);
2831 // Or make a new list if none was found.
2832 if (scopes == null) {
2833 scopes = new ArrayList<>();
2834 policy.mDelegationMap.put(delegatePackage, scopes);
2836 // Add the new scope to the list of delegatePackage if it's not already there.
2837 if (!scopes.contains(scope)) {
2840 } else if ("failed-password-attempts".equals(tag)) {
2841 policy.mFailedPasswordAttempts = Integer.parseInt(
2842 parser.getAttributeValue(null, "value"));
2843 } else if ("password-owner".equals(tag)) {
2844 policy.mPasswordOwner = Integer.parseInt(
2845 parser.getAttributeValue(null, "value"));
2846 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2847 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2848 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2849 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2850 } else if (TAG_STATUS_BAR.equals(tag)) {
2851 policy.mStatusBarDisabled = Boolean.parseBoolean(
2852 parser.getAttributeValue(null, ATTR_DISABLED));
2853 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2854 policy.doNotAskCredentialsOnBoot = true;
2855 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2856 policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID));
2857 } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) {
2858 policy.mLastSecurityLogRetrievalTime = Long.parseLong(
2859 parser.getAttributeValue(null, ATTR_VALUE));
2860 } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) {
2861 policy.mLastBugReportRequestTime = Long.parseLong(
2862 parser.getAttributeValue(null, ATTR_VALUE));
2863 } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) {
2864 policy.mLastNetworkLogsRetrievalTime = Long.parseLong(
2865 parser.getAttributeValue(null, ATTR_VALUE));
2866 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2867 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2868 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2869 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2870 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2871 } else if ("active-password".equals(tag)) {
2872 // Remove password metrics from saved settings, as we no longer wish to store
2874 needsRewrite = true;
2875 } else if (TAG_PASSWORD_VALIDITY.equals(tag)) {
2876 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2877 // This flag is only used for FDE devices
2878 policy.mPasswordValidAtLastCheckpoint = Boolean.parseBoolean(
2879 parser.getAttributeValue(null, ATTR_VALUE));
2881 } else if (TAG_PASSWORD_TOKEN_HANDLE.equals(tag)) {
2882 policy.mPasswordTokenHandle = Long.parseLong(
2883 parser.getAttributeValue(null, ATTR_VALUE));
2884 } else if (TAG_CURRENT_INPUT_METHOD_SET.equals(tag)) {
2885 policy.mCurrentInputMethodSet = true;
2886 } else if (TAG_OWNER_INSTALLED_CA_CERT.equals(tag)) {
2887 policy.mOwnerInstalledCaCerts.add(parser.getAttributeValue(null, ATTR_ALIAS));
2889 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2890 XmlUtils.skipCurrentTag(parser);
2893 } catch (FileNotFoundException e) {
2894 // Don't be noisy, this is normal if we haven't defined any policies.
2895 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2896 | IndexOutOfBoundsException e) {
2897 Slog.w(LOG_TAG, "failed parsing " + file, e);
2900 if (stream != null) {
2903 } catch (IOException e) {
2907 // Generate a list of admins from the admin map
2908 policy.mAdminList.addAll(policy.mAdminMap.values());
2910 // Might need to upgrade the file by rewriting it
2912 saveSettingsLocked(userHandle);
2915 validatePasswordOwnerLocked(policy);
2916 updateMaximumTimeToLockLocked(userHandle);
2917 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2918 if (policy.mStatusBarDisabled) {
2919 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2923 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2924 long ident = mInjector.binderClearCallingIdentity();
2926 mInjector.getIActivityManager()
2927 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2928 } catch (RemoteException e) {
2929 // Not gonna happen.
2931 mInjector.binderRestoreCallingIdentity(ident);
2935 private void updateDeviceOwnerLocked() {
2936 long ident = mInjector.binderClearCallingIdentity();
2938 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2939 // user id and also protect all other DAs too.
2940 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2941 if (deviceOwnerComponent != null) {
2942 mInjector.getIActivityManager()
2943 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2945 } catch (RemoteException e) {
2946 // Not gonna happen.
2948 mInjector.binderRestoreCallingIdentity(ident);
2952 static void validateQualityConstant(int quality) {
2954 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2955 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2956 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2957 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2958 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2959 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2960 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2961 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2962 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2965 throw new IllegalArgumentException("Invalid quality constant: 0x"
2966 + Integer.toHexString(quality));
2969 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2970 if (policy.mPasswordOwner >= 0) {
2971 boolean haveOwner = false;
2972 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2973 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2979 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2980 + " no longer active; disabling");
2981 policy.mPasswordOwner = -1;
2987 void systemReady(int phase) {
2992 case SystemService.PHASE_LOCK_SETTINGS_READY:
2993 onLockSettingsReady();
2995 case SystemService.PHASE_BOOT_COMPLETED:
2996 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
3001 private void onLockSettingsReady() {
3002 getUserData(UserHandle.USER_SYSTEM);
3005 maybeSetDefaultProfileOwnerUserRestrictions();
3006 handleStartUser(UserHandle.USER_SYSTEM);
3008 // Register an observer for watching for user setup complete and settings changes.
3009 mSetupContentObserver.register();
3010 // Initialize the user setup state, to handle the upgrade case.
3011 updateUserSetupCompleteAndPaired();
3013 List<String> packageList;
3014 synchronized (this) {
3015 packageList = getKeepUninstalledPackagesLocked();
3017 if (packageList != null) {
3018 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
3021 synchronized (this) {
3022 // push the force-ephemeral-users policy to the user manager.
3023 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
3024 if (deviceOwner != null) {
3025 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
3030 private void ensureDeviceOwnerUserStarted() {
3032 synchronized (this) {
3033 if (!mOwners.hasDeviceOwner()) {
3036 userId = mOwners.getDeviceOwnerUserId();
3039 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
3041 if (userId != UserHandle.USER_SYSTEM) {
3043 mInjector.getIActivityManager().startUserInBackground(userId);
3045 // STOPSHIP Prevent the DO user from being killed.
3047 } catch (RemoteException e) {
3048 Slog.w(LOG_TAG, "Exception starting user", e);
3053 void handleStartUser(int userId) {
3054 updateScreenCaptureDisabledInWindowManager(userId,
3055 getScreenCaptureDisabled(null, userId));
3056 pushUserRestrictions(userId);
3058 startOwnerService(userId, "start-user");
3061 void handleUnlockUser(int userId) {
3062 startOwnerService(userId, "unlock-user");
3065 void handleStopUser(int userId) {
3066 stopOwnerService(userId, "stop-user");
3069 private void startOwnerService(int userId, String actionForLog) {
3070 final ComponentName owner = getOwnerComponent(userId);
3071 if (owner != null) {
3072 mDeviceAdminServiceController.startServiceForOwner(
3073 owner.getPackageName(), userId, actionForLog);
3077 private void stopOwnerService(int userId, String actionForLog) {
3078 mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog);
3081 private void cleanUpOldUsers() {
3082 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
3084 Set<Integer> usersWithProfileOwners;
3085 Set<Integer> usersWithData;
3086 synchronized(this) {
3087 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
3088 usersWithData = new ArraySet<>();
3089 for (int i = 0; i < mUserData.size(); i++) {
3090 usersWithData.add(mUserData.keyAt(i));
3093 List<UserInfo> allUsers = mUserManager.getUsers();
3095 Set<Integer> deletedUsers = new ArraySet<>();
3096 deletedUsers.addAll(usersWithProfileOwners);
3097 deletedUsers.addAll(usersWithData);
3098 for (UserInfo userInfo : allUsers) {
3099 deletedUsers.remove(userInfo.id);
3101 for (Integer userId : deletedUsers) {
3102 removeUserData(userId);
3106 private void handlePasswordExpirationNotification(int userHandle) {
3107 final Bundle adminExtras = new Bundle();
3108 adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
3110 synchronized (this) {
3111 final long now = System.currentTimeMillis();
3113 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
3114 userHandle, /* parent */ false);
3115 final int N = admins.size();
3116 for (int i = 0; i < N; i++) {
3117 ActiveAdmin admin = admins.get(i);
3118 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
3119 && admin.passwordExpirationTimeout > 0L
3120 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
3121 && admin.passwordExpirationDate > 0L) {
3122 sendAdminCommandLocked(admin,
3123 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null);
3126 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
3131 * Clean up internal state when the set of installed trusted CA certificates changes.
3133 * @param userHandle user to check for. This must be a real user and not, for example,
3134 * {@link UserHandle#ALL}.
3135 * @param installedCertificates the full set of certificate authorities currently installed for
3136 * {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will
3137 * correspond to some subset of this.
3139 protected void onInstalledCertificatesChanged(final UserHandle userHandle,
3140 final @NonNull Collection<String> installedCertificates) {
3144 enforceManageUsers();
3146 synchronized (this) {
3147 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3149 boolean changed = false;
3150 changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates);
3151 changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates);
3153 saveSettingsLocked(userHandle.getIdentifier());
3159 * Internal method used by {@link CertificateMonitor}.
3161 protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) {
3163 return Collections.<String> emptySet();
3165 synchronized (this) {
3166 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3167 return policy.mAcceptedCaCertificates;
3172 * @param adminReceiver The admin to add
3173 * @param refreshing true = update an active admin, no error
3176 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
3180 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
3183 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
3184 Bundle onEnableData) {
3185 mContext.enforceCallingOrSelfPermission(
3186 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3187 enforceFullCrossUsersPermission(userHandle);
3189 DevicePolicyData policy = getUserData(userHandle);
3190 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
3191 /* throwForMissionPermission= */ true);
3193 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
3195 if (!info.getActivityInfo().applicationInfo.isInternal()) {
3196 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
3199 if (info.getActivityInfo().applicationInfo.isInstantApp()) {
3200 throw new IllegalArgumentException("Instant apps cannot be device admins: "
3203 synchronized (this) {
3204 long ident = mInjector.binderClearCallingIdentity();
3206 final ActiveAdmin existingAdmin
3207 = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3208 if (!refreshing && existingAdmin != null) {
3209 throw new IllegalArgumentException("Admin is already added");
3211 if (policy.mRemovingAdmins.contains(adminReceiver)) {
3212 throw new IllegalArgumentException(
3213 "Trying to set an admin which is being removed");
3215 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
3216 newAdmin.testOnlyAdmin =
3217 (existingAdmin != null) ? existingAdmin.testOnlyAdmin
3218 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
3219 policy.mAdminMap.put(adminReceiver, newAdmin);
3220 int replaceIndex = -1;
3221 final int N = policy.mAdminList.size();
3222 for (int i=0; i < N; i++) {
3223 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
3224 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
3229 if (replaceIndex == -1) {
3230 policy.mAdminList.add(newAdmin);
3231 enableIfNecessary(info.getPackageName(), userHandle);
3233 policy.mAdminList.set(replaceIndex, newAdmin);
3235 saveSettingsLocked(userHandle);
3236 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3237 onEnableData, null);
3239 mInjector.binderRestoreCallingIdentity(ident);
3245 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
3249 enforceFullCrossUsersPermission(userHandle);
3250 synchronized (this) {
3251 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
3256 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
3260 enforceFullCrossUsersPermission(userHandle);
3261 synchronized (this) {
3262 DevicePolicyData policyData = getUserData(userHandle);
3263 return policyData.mRemovingAdmins.contains(adminReceiver);
3268 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
3272 enforceFullCrossUsersPermission(userHandle);
3273 synchronized (this) {
3274 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3275 if (administrator == null) {
3276 throw new SecurityException("No active admin " + adminReceiver);
3278 return administrator.info.usesPolicy(policyId);
3283 @SuppressWarnings("unchecked")
3284 public List<ComponentName> getActiveAdmins(int userHandle) {
3286 return Collections.EMPTY_LIST;
3289 enforceFullCrossUsersPermission(userHandle);
3290 synchronized (this) {
3291 DevicePolicyData policy = getUserData(userHandle);
3292 final int N = policy.mAdminList.size();
3296 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3297 for (int i=0; i<N; i++) {
3298 res.add(policy.mAdminList.get(i).info.getComponent());
3305 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
3309 enforceFullCrossUsersPermission(userHandle);
3310 synchronized (this) {
3311 DevicePolicyData policy = getUserData(userHandle);
3312 final int N = policy.mAdminList.size();
3313 for (int i=0; i<N; i++) {
3314 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
3322 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
3326 Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
3327 enforceShell("forceRemoveActiveAdmin");
3328 long ident = mInjector.binderClearCallingIdentity();
3330 synchronized (this) {
3331 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
3332 throw new SecurityException("Attempt to remove non-test admin "
3333 + adminReceiver + " " + userHandle);
3336 // If admin is a device or profile owner tidy that up first.
3337 if (isDeviceOwner(adminReceiver, userHandle)) {
3338 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3340 if (isProfileOwner(adminReceiver, userHandle)) {
3341 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3342 userHandle, /* parent */ false);
3343 clearProfileOwnerLocked(admin, userHandle);
3346 // Remove the admin skipping sending the broadcast.
3347 removeAdminArtifacts(adminReceiver, userHandle);
3348 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3350 mInjector.binderRestoreCallingIdentity(ident);
3354 private void clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle) {
3355 // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state
3356 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
3357 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle);
3362 * Return if a given package has testOnly="true", in which case we'll relax certain rules
3365 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked}
3366 * to check wehter an active admin is test-only or not.
3368 * The system allows this flag to be changed when an app is updated, which is not good
3369 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3370 * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3372 private boolean isPackageTestOnly(String packageName, int userHandle) {
3373 final ApplicationInfo ai;
3375 ai = mIPackageManager.getApplicationInfo(packageName,
3376 (PackageManager.MATCH_DIRECT_BOOT_AWARE
3377 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3378 } catch (RemoteException e) {
3379 throw new IllegalStateException(e);
3382 throw new IllegalStateException("Couldn't find package: "
3383 + packageName + " on user " + userHandle);
3385 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3389 * See {@link #isPackageTestOnly}.
3391 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3392 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3393 return (admin != null) && admin.testOnlyAdmin;
3396 private void enforceShell(String method) {
3397 final int callingUid = Binder.getCallingUid();
3398 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3399 throw new SecurityException("Non-shell user attempted to call " + method);
3404 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3408 enforceFullCrossUsersPermission(userHandle);
3409 enforceUserUnlocked(userHandle);
3410 synchronized (this) {
3411 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3412 if (admin == null) {
3415 // Active device/profile owners must remain active admins.
3416 if (isDeviceOwner(adminReceiver, userHandle)
3417 || isProfileOwner(adminReceiver, userHandle)) {
3418 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3422 if (admin.getUid() != mInjector.binderGetCallingUid()) {
3423 mContext.enforceCallingOrSelfPermission(
3424 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3426 long ident = mInjector.binderClearCallingIdentity();
3428 removeActiveAdminLocked(adminReceiver, userHandle);
3430 mInjector.binderRestoreCallingIdentity(ident);
3436 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3437 ComponentName profileOwner = getProfileOwner(userHandle);
3438 // Profile challenge is supported on N or newer release.
3439 return profileOwner != null &&
3440 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3444 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3448 Preconditions.checkNotNull(who, "ComponentName is null");
3449 validateQualityConstant(quality);
3451 synchronized (this) {
3452 ActiveAdmin ap = getActiveAdminForCallerLocked(
3453 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3454 if (ap.minimumPasswordMetrics.quality != quality) {
3455 ap.minimumPasswordMetrics.quality = quality;
3456 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3457 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3463 * Updates flag in memory that tells us whether the user's password currently satisfies the
3464 * requirements set by all of the user's active admins. This should be called before
3465 * {@link #saveSettingsLocked} whenever the password or the admin policies have changed.
3467 @GuardedBy("DevicePolicyManagerService.this")
3468 private void updatePasswordValidityCheckpointLocked(int userHandle) {
3469 DevicePolicyData policy = getUserData(userHandle);
3470 policy.mPasswordValidAtLastCheckpoint = isActivePasswordSufficientForUserLocked(
3471 policy, policy.mUserHandle, false);
3475 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3477 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3479 enforceFullCrossUsersPermission(userHandle);
3480 synchronized (this) {
3481 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3484 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3485 return admin != null ? admin.minimumPasswordMetrics.quality : mode;
3488 // Return the strictest policy across all participating admins.
3489 List<ActiveAdmin> admins =
3490 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3491 final int N = admins.size();
3492 for (int i = 0; i < N; i++) {
3493 ActiveAdmin admin = admins.get(i);
3494 if (mode < admin.minimumPasswordMetrics.quality) {
3495 mode = admin.minimumPasswordMetrics.quality;
3502 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3503 int userHandle, boolean parent) {
3504 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3505 // If this user has a separate challenge, only return its restrictions.
3506 return getUserDataUnchecked(userHandle).mAdminList;
3508 // Return all admins for this user and the profiles that are visible from this
3509 // user that do not use a separate work challenge.
3510 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3511 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3512 DevicePolicyData policy = getUserData(userInfo.id);
3513 if (!userInfo.isManagedProfile()) {
3514 admins.addAll(policy.mAdminList);
3516 // For managed profiles, we always include the policies set on the parent
3517 // profile. Additionally, we include the ones set on the managed profile
3518 // if no separate challenge is in place.
3519 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3520 final int N = policy.mAdminList.size();
3521 for (int i = 0; i < N; i++) {
3522 ActiveAdmin admin = policy.mAdminList.get(i);
3523 if (admin.hasParentActiveAdmin()) {
3524 admins.add(admin.getParentActiveAdmin());
3526 if (!hasSeparateChallenge) {
3536 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3537 long ident = mInjector.binderClearCallingIdentity();
3539 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3541 mInjector.binderRestoreCallingIdentity(ident);
3546 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3550 Preconditions.checkNotNull(who, "ComponentName is null");
3551 synchronized (this) {
3552 ActiveAdmin ap = getActiveAdminForCallerLocked(
3553 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3554 if (ap.minimumPasswordMetrics.length != length) {
3555 ap.minimumPasswordMetrics.length = length;
3556 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3557 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3563 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3567 enforceFullCrossUsersPermission(userHandle);
3568 synchronized (this) {
3572 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3573 return admin != null ? admin.minimumPasswordMetrics.length : length;
3576 // Return the strictest policy across all participating admins.
3577 List<ActiveAdmin> admins =
3578 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3579 final int N = admins.size();
3580 for (int i = 0; i < N; i++) {
3581 ActiveAdmin admin = admins.get(i);
3582 if (length < admin.minimumPasswordMetrics.length) {
3583 length = admin.minimumPasswordMetrics.length;
3591 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3595 Preconditions.checkNotNull(who, "ComponentName is null");
3596 synchronized (this) {
3597 ActiveAdmin ap = getActiveAdminForCallerLocked(
3598 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3599 if (ap.passwordHistoryLength != length) {
3600 ap.passwordHistoryLength = length;
3601 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3602 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3608 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3612 enforceFullCrossUsersPermission(userHandle);
3613 synchronized (this) {
3617 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3618 return admin != null ? admin.passwordHistoryLength : length;
3621 // Return the strictest policy across all participating admins.
3622 List<ActiveAdmin> admins =
3623 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3624 final int N = admins.size();
3625 for (int i = 0; i < N; i++) {
3626 ActiveAdmin admin = admins.get(i);
3627 if (length < admin.passwordHistoryLength) {
3628 length = admin.passwordHistoryLength;
3637 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3641 Preconditions.checkNotNull(who, "ComponentName is null");
3642 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3643 final int userHandle = mInjector.userHandleGetCallingUserId();
3644 synchronized (this) {
3645 ActiveAdmin ap = getActiveAdminForCallerLocked(
3646 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3647 // Calling this API automatically bumps the expiration date
3648 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3649 ap.passwordExpirationDate = expiration;
3650 ap.passwordExpirationTimeout = timeout;
3652 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3653 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3654 .format(new Date(expiration)));
3656 saveSettingsLocked(userHandle);
3658 // in case this is the first one, set the alarm on the appropriate user.
3659 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3664 * Return a single admin's expiration cycle time, or the min of all cycle times.
3665 * Returns 0 if not configured.
3668 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3672 enforceFullCrossUsersPermission(userHandle);
3673 synchronized (this) {
3677 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3678 return admin != null ? admin.passwordExpirationTimeout : timeout;
3681 // Return the strictest policy across all participating admins.
3682 List<ActiveAdmin> admins =
3683 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3684 final int N = admins.size();
3685 for (int i = 0; i < N; i++) {
3686 ActiveAdmin admin = admins.get(i);
3687 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3688 && timeout > admin.passwordExpirationTimeout)) {
3689 timeout = admin.passwordExpirationTimeout;
3697 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3698 final int userId = UserHandle.getCallingUserId();
3699 List<String> changedProviders = null;
3701 synchronized (this) {
3702 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3703 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3704 if (activeAdmin.crossProfileWidgetProviders == null) {
3705 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3707 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3708 if (!providers.contains(packageName)) {
3709 providers.add(packageName);
3710 changedProviders = new ArrayList<>(providers);
3711 saveSettingsLocked(userId);
3715 if (changedProviders != null) {
3716 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3724 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3725 final int userId = UserHandle.getCallingUserId();
3726 List<String> changedProviders = null;
3728 synchronized (this) {
3729 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3730 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3731 if (activeAdmin.crossProfileWidgetProviders == null
3732 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3735 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3736 if (providers.remove(packageName)) {
3737 changedProviders = new ArrayList<>(providers);
3738 saveSettingsLocked(userId);
3742 if (changedProviders != null) {
3743 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3751 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3752 synchronized (this) {
3753 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3754 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3755 if (activeAdmin.crossProfileWidgetProviders == null
3756 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3759 if (mInjector.binderIsCallingUidMyUid()) {
3760 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3762 return activeAdmin.crossProfileWidgetProviders;
3768 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3769 * Returns 0 if not configured.
3771 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3775 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3776 return admin != null ? admin.passwordExpirationDate : timeout;
3779 // Return the strictest policy across all participating admins.
3780 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3781 final int N = admins.size();
3782 for (int i = 0; i < N; i++) {
3783 ActiveAdmin admin = admins.get(i);
3784 if (timeout == 0L || (admin.passwordExpirationDate != 0
3785 && timeout > admin.passwordExpirationDate)) {
3786 timeout = admin.passwordExpirationDate;
3793 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3797 enforceFullCrossUsersPermission(userHandle);
3798 synchronized (this) {
3799 return getPasswordExpirationLocked(who, userHandle, parent);
3804 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3808 Preconditions.checkNotNull(who, "ComponentName is null");
3809 synchronized (this) {
3810 ActiveAdmin ap = getActiveAdminForCallerLocked(
3811 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3812 if (ap.minimumPasswordMetrics.upperCase != length) {
3813 ap.minimumPasswordMetrics.upperCase = length;
3814 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3815 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3821 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3825 enforceFullCrossUsersPermission(userHandle);
3826 synchronized (this) {
3830 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3831 return admin != null ? admin.minimumPasswordMetrics.upperCase : length;
3834 // Return the strictest policy across all participating admins.
3835 List<ActiveAdmin> admins =
3836 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3837 final int N = admins.size();
3838 for (int i = 0; i < N; i++) {
3839 ActiveAdmin admin = admins.get(i);
3840 if (length < admin.minimumPasswordMetrics.upperCase) {
3841 length = admin.minimumPasswordMetrics.upperCase;
3849 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3850 Preconditions.checkNotNull(who, "ComponentName is null");
3851 synchronized (this) {
3852 ActiveAdmin ap = getActiveAdminForCallerLocked(
3853 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3854 if (ap.minimumPasswordMetrics.lowerCase != length) {
3855 ap.minimumPasswordMetrics.lowerCase = length;
3856 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3857 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3863 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3867 enforceFullCrossUsersPermission(userHandle);
3868 synchronized (this) {
3872 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3873 return admin != null ? admin.minimumPasswordMetrics.lowerCase : length;
3876 // Return the strictest policy across all participating admins.
3877 List<ActiveAdmin> admins =
3878 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3879 final int N = admins.size();
3880 for (int i = 0; i < N; i++) {
3881 ActiveAdmin admin = admins.get(i);
3882 if (length < admin.minimumPasswordMetrics.lowerCase) {
3883 length = admin.minimumPasswordMetrics.lowerCase;
3891 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3895 Preconditions.checkNotNull(who, "ComponentName is null");
3896 synchronized (this) {
3897 ActiveAdmin ap = getActiveAdminForCallerLocked(
3898 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3899 if (ap.minimumPasswordMetrics.letters != length) {
3900 ap.minimumPasswordMetrics.letters = length;
3901 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3902 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3908 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3912 enforceFullCrossUsersPermission(userHandle);
3913 synchronized (this) {
3917 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3918 return admin != null ? admin.minimumPasswordMetrics.letters : length;
3921 // Return the strictest policy across all participating admins.
3922 List<ActiveAdmin> admins =
3923 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3924 final int N = admins.size();
3925 for (int i = 0; i < N; i++) {
3926 ActiveAdmin admin = admins.get(i);
3927 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3930 if (length < admin.minimumPasswordMetrics.letters) {
3931 length = admin.minimumPasswordMetrics.letters;
3939 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3943 Preconditions.checkNotNull(who, "ComponentName is null");
3944 synchronized (this) {
3945 ActiveAdmin ap = getActiveAdminForCallerLocked(
3946 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3947 if (ap.minimumPasswordMetrics.numeric != length) {
3948 ap.minimumPasswordMetrics.numeric = length;
3949 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3950 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3956 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3960 enforceFullCrossUsersPermission(userHandle);
3961 synchronized (this) {
3965 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3966 return admin != null ? admin.minimumPasswordMetrics.numeric : length;
3969 // Return the strictest policy across all participating admins.
3970 List<ActiveAdmin> admins =
3971 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3972 final int N = admins.size();
3973 for (int i = 0; i < N; i++) {
3974 ActiveAdmin admin = admins.get(i);
3975 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3978 if (length < admin.minimumPasswordMetrics.numeric) {
3979 length = admin.minimumPasswordMetrics.numeric;
3987 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3991 Preconditions.checkNotNull(who, "ComponentName is null");
3992 synchronized (this) {
3993 ActiveAdmin ap = getActiveAdminForCallerLocked(
3994 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3995 if (ap.minimumPasswordMetrics.symbols != length) {
3996 ap.minimumPasswordMetrics.symbols = length;
3997 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3998 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4004 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
4008 enforceFullCrossUsersPermission(userHandle);
4009 synchronized (this) {
4013 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4014 return admin != null ? admin.minimumPasswordMetrics.symbols : length;
4017 // Return the strictest policy across all participating admins.
4018 List<ActiveAdmin> admins =
4019 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4020 final int N = admins.size();
4021 for (int i = 0; i < N; i++) {
4022 ActiveAdmin admin = admins.get(i);
4023 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
4026 if (length < admin.minimumPasswordMetrics.symbols) {
4027 length = admin.minimumPasswordMetrics.symbols;
4035 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
4039 Preconditions.checkNotNull(who, "ComponentName is null");
4040 synchronized (this) {
4041 ActiveAdmin ap = getActiveAdminForCallerLocked(
4042 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4043 if (ap.minimumPasswordMetrics.nonLetter != length) {
4044 ap.minimumPasswordMetrics.nonLetter = length;
4045 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
4046 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4052 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
4056 enforceFullCrossUsersPermission(userHandle);
4057 synchronized (this) {
4061 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4062 return admin != null ? admin.minimumPasswordMetrics.nonLetter : length;
4065 // Return the strictest policy across all participating admins.
4066 List<ActiveAdmin> admins =
4067 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4068 final int N = admins.size();
4069 for (int i = 0; i < N; i++) {
4070 ActiveAdmin admin = admins.get(i);
4071 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
4074 if (length < admin.minimumPasswordMetrics.nonLetter) {
4075 length = admin.minimumPasswordMetrics.nonLetter;
4083 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
4087 enforceFullCrossUsersPermission(userHandle);
4089 synchronized (this) {
4090 // This API can only be called by an active device admin,
4091 // so try to retrieve it to check that the caller is one.
4092 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4093 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4094 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
4099 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
4103 enforceFullCrossUsersPermission(userHandle);
4104 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
4106 synchronized (this) {
4107 int targetUser = getProfileParentId(userHandle);
4108 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
4109 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
4113 private boolean isActivePasswordSufficientForUserLocked(
4114 DevicePolicyData policy, int userHandle, boolean parent) {
4115 enforceUserUnlocked(userHandle, parent);
4117 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
4118 && !policy.mPasswordStateHasBeenSetSinceBoot) {
4119 // Before user enters their password for the first time after a reboot, return the
4120 // value of this flag, which tells us whether the password was valid the last time
4121 // settings were saved. If DPC changes password requirements on boot so that the
4122 // current password no longer meets the requirements, this value will be stale until
4123 // the next time the password is entered.
4124 return policy.mPasswordValidAtLastCheckpoint;
4127 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
4128 if (policy.mActivePasswordMetrics.quality < requiredPasswordQuality) {
4131 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
4132 && policy.mActivePasswordMetrics.length < getPasswordMinimumLength(
4133 null, userHandle, parent)) {
4136 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4139 return policy.mActivePasswordMetrics.upperCase >= getPasswordMinimumUpperCase(
4140 null, userHandle, parent)
4141 && policy.mActivePasswordMetrics.lowerCase >= getPasswordMinimumLowerCase(
4142 null, userHandle, parent)
4143 && policy.mActivePasswordMetrics.letters >= getPasswordMinimumLetters(
4144 null, userHandle, parent)
4145 && policy.mActivePasswordMetrics.numeric >= getPasswordMinimumNumeric(
4146 null, userHandle, parent)
4147 && policy.mActivePasswordMetrics.symbols >= getPasswordMinimumSymbols(
4148 null, userHandle, parent)
4149 && policy.mActivePasswordMetrics.nonLetter >= getPasswordMinimumNonLetter(
4150 null, userHandle, parent);
4154 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
4155 enforceFullCrossUsersPermission(userHandle);
4156 synchronized (this) {
4157 if (!isCallerWithSystemUid()) {
4158 // This API can only be called by an active device admin,
4159 // so try to retrieve it to check that the caller is one.
4160 getActiveAdminForCallerLocked(
4161 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4164 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4166 return policy.mFailedPasswordAttempts;
4171 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
4175 Preconditions.checkNotNull(who, "ComponentName is null");
4176 synchronized (this) {
4177 // This API can only be called by an active device admin,
4178 // so try to retrieve it to check that the caller is one.
4179 getActiveAdminForCallerLocked(
4180 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
4181 ActiveAdmin ap = getActiveAdminForCallerLocked(
4182 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4183 if (ap.maximumFailedPasswordsForWipe != num) {
4184 ap.maximumFailedPasswordsForWipe = num;
4185 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4191 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
4195 enforceFullCrossUsersPermission(userHandle);
4196 synchronized (this) {
4197 ActiveAdmin admin = (who != null)
4198 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
4199 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
4200 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
4205 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
4207 return UserHandle.USER_NULL;
4209 enforceFullCrossUsersPermission(userHandle);
4210 synchronized (this) {
4211 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4212 userHandle, parent);
4213 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
4218 * Returns the admin with the strictest policy on maximum failed passwords for:
4220 * <li>this user if it has a separate profile challenge, or
4221 * <li>this user and all profiles that don't have their own challenge otherwise.
4223 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
4224 * the primary profile.
4225 * Returns {@code null} if no participating admin has that policy set.
4227 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
4228 int userHandle, boolean parent) {
4230 ActiveAdmin strictestAdmin = null;
4232 // Return the strictest policy across all participating admins.
4233 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4234 final int N = admins.size();
4235 for (int i = 0; i < N; i++) {
4236 ActiveAdmin admin = admins.get(i);
4237 if (admin.maximumFailedPasswordsForWipe ==
4238 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
4239 continue; // No max number of failed passwords policy set for this profile.
4242 // We always favor the primary profile if several profiles have the same value set.
4243 int userId = admin.getUserHandle().getIdentifier();
4245 count > admin.maximumFailedPasswordsForWipe ||
4246 (count == admin.maximumFailedPasswordsForWipe &&
4247 getUserInfo(userId).isPrimary())) {
4248 count = admin.maximumFailedPasswordsForWipe;
4249 strictestAdmin = admin;
4252 return strictestAdmin;
4255 private UserInfo getUserInfo(@UserIdInt int userId) {
4256 final long token = mInjector.binderClearCallingIdentity();
4258 return mUserManager.getUserInfo(userId);
4260 mInjector.binderRestoreCallingIdentity(token);
4265 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
4266 final int callingUid = mInjector.binderGetCallingUid();
4267 final int userHandle = mInjector.userHandleGetCallingUserId();
4269 String password = passwordOrNull != null ? passwordOrNull : "";
4271 // Password resetting to empty/null is not allowed for managed profiles.
4272 if (TextUtils.isEmpty(password)) {
4273 enforceNotManagedProfile(userHandle, "clear the active password");
4276 synchronized (this) {
4277 // If caller has PO (or DO) it can change the password, so see if that's the case first.
4278 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
4279 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
4281 if (admin != null) {
4282 final int targetSdk = getTargetSdk(admin.info.getPackageName(), userHandle);
4283 if (targetSdk >= Build.VERSION_CODES.O) {
4284 throw new SecurityException("resetPassword() is deprecated for DPC targeting O"
4287 preN = targetSdk <= android.os.Build.VERSION_CODES.M;
4289 // Otherwise, make sure the caller has any active admin with the right policy.
4290 admin = getActiveAdminForCallerLocked(null,
4291 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
4292 preN = getTargetSdk(admin.info.getPackageName(),
4293 userHandle) <= android.os.Build.VERSION_CODES.M;
4295 // As of N, password resetting to empty/null is not allowed anymore.
4296 // TODO Should we allow DO/PO to set an empty password?
4297 if (TextUtils.isEmpty(password)) {
4299 throw new SecurityException("Cannot call with null password");
4301 Slog.e(LOG_TAG, "Cannot call with null password");
4305 // As of N, password cannot be changed by the admin if it is already set.
4306 if (isLockScreenSecureUnchecked(userHandle)) {
4308 throw new SecurityException("Admin cannot change current password");
4310 Slog.e(LOG_TAG, "Admin cannot change current password");
4315 // Do not allow to reset password when current user has a managed profile
4316 if (!isManagedProfile(userHandle)) {
4317 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4318 if (userInfo.isManagedProfile()) {
4320 throw new IllegalStateException(
4321 "Cannot reset password on user has managed profile");
4323 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
4329 // Do not allow to reset password when user is locked
4330 if (!mUserManager.isUserUnlocked(userHandle)) {
4332 throw new IllegalStateException("Cannot reset password when user is locked");
4334 Slog.e(LOG_TAG, "Cannot reset password when user is locked");
4340 return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle);
4343 private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token,
4344 int flags, int callingUid, int userHandle) {
4346 synchronized (this) {
4347 quality = getPasswordQuality(null, userHandle, /* parent */ false);
4348 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
4349 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4351 final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password);
4352 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
4353 final int realQuality = metrics.quality;
4354 if (realQuality < quality
4355 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4356 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
4357 + Integer.toHexString(realQuality)
4358 + " does not meet required quality 0x"
4359 + Integer.toHexString(quality));
4362 quality = Math.max(realQuality, quality);
4364 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
4365 if (password.length() < length) {
4366 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
4367 + " does not meet required length " + length);
4370 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4371 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4372 if(metrics.letters < neededLetters) {
4373 Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters
4374 + " does not meet required number of letters " + neededLetters);
4377 int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4378 if (metrics.numeric < neededNumeric) {
4379 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric
4380 + " does not meet required number of numerical digits "
4384 int neededLowerCase = getPasswordMinimumLowerCase(
4385 null, userHandle, /* parent */ false);
4386 if (metrics.lowerCase < neededLowerCase) {
4387 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters "
4389 + " does not meet required number of lowercase letters "
4393 int neededUpperCase = getPasswordMinimumUpperCase(
4394 null, userHandle, /* parent */ false);
4395 if (metrics.upperCase < neededUpperCase) {
4396 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters "
4398 + " does not meet required number of uppercase letters "
4402 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4403 if (metrics.symbols < neededSymbols) {
4404 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols
4405 + " does not meet required number of special symbols " + neededSymbols);
4408 int neededNonLetter = getPasswordMinimumNonLetter(
4409 null, userHandle, /* parent */ false);
4410 if (metrics.nonLetter < neededNonLetter) {
4411 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters "
4413 + " does not meet required number of non-letter characters "
4420 DevicePolicyData policy = getUserData(userHandle);
4421 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4422 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4426 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4427 boolean doNotAskCredentialsOnBoot =
4428 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4429 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4430 setDoNotAskCredentialsOnBoot();
4433 // Don't do this with the lock held, because it is going to call
4434 // back in to the service.
4435 final long ident = mInjector.binderClearCallingIdentity();
4436 final boolean result;
4438 if (token == null) {
4439 if (!TextUtils.isEmpty(password)) {
4440 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4442 mLockPatternUtils.clearLock(null, userHandle);
4446 result = mLockPatternUtils.setLockCredentialWithToken(password,
4447 TextUtils.isEmpty(password) ? LockPatternUtils.CREDENTIAL_TYPE_NONE
4448 : LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
4449 tokenHandle, token, userHandle);
4451 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4453 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4454 UserHandle.USER_ALL);
4456 synchronized (this) {
4457 int newOwner = requireEntry ? callingUid : -1;
4458 if (policy.mPasswordOwner != newOwner) {
4459 policy.mPasswordOwner = newOwner;
4460 saveSettingsLocked(userHandle);
4464 mInjector.binderRestoreCallingIdentity(ident);
4469 private boolean isLockScreenSecureUnchecked(int userId) {
4470 long ident = mInjector.binderClearCallingIdentity();
4472 return mLockPatternUtils.isSecure(userId);
4474 mInjector.binderRestoreCallingIdentity(ident);
4478 private void setDoNotAskCredentialsOnBoot() {
4479 synchronized (this) {
4480 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4481 if (!policyData.doNotAskCredentialsOnBoot) {
4482 policyData.doNotAskCredentialsOnBoot = true;
4483 saveSettingsLocked(UserHandle.USER_SYSTEM);
4489 public boolean getDoNotAskCredentialsOnBoot() {
4490 mContext.enforceCallingOrSelfPermission(
4491 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4492 synchronized (this) {
4493 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4494 return policyData.doNotAskCredentialsOnBoot;
4499 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4503 Preconditions.checkNotNull(who, "ComponentName is null");
4504 final int userHandle = mInjector.userHandleGetCallingUserId();
4505 synchronized (this) {
4506 ActiveAdmin ap = getActiveAdminForCallerLocked(
4507 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4508 if (ap.maximumTimeToUnlock != timeMs) {
4509 ap.maximumTimeToUnlock = timeMs;
4510 saveSettingsLocked(userHandle);
4511 updateMaximumTimeToLockLocked(userHandle);
4516 void updateMaximumTimeToLockLocked(int userHandle) {
4517 // Calculate the min timeout for all profiles - including the ones with a separate
4518 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4519 // challenge only and keep the screen on. However there is no easy way of doing that at the
4520 // moment so we set the screen off timeout regardless of whether it affects the parent user
4521 // or the profile challenge only.
4522 long timeMs = Long.MAX_VALUE;
4523 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4524 for (int profileId : profileIds) {
4525 DevicePolicyData policy = getUserDataUnchecked(profileId);
4526 final int N = policy.mAdminList.size();
4527 for (int i = 0; i < N; i++) {
4528 ActiveAdmin admin = policy.mAdminList.get(i);
4529 if (admin.maximumTimeToUnlock > 0
4530 && timeMs > admin.maximumTimeToUnlock) {
4531 timeMs = admin.maximumTimeToUnlock;
4533 // If userInfo.id is a managed profile, we also need to look at
4534 // the policies set on the parent.
4535 if (admin.hasParentActiveAdmin()) {
4536 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4537 if (parentAdmin.maximumTimeToUnlock > 0
4538 && timeMs > parentAdmin.maximumTimeToUnlock) {
4539 timeMs = parentAdmin.maximumTimeToUnlock;
4545 // We only store the last maximum time to lock on the parent profile. So if calling from a
4546 // managed profile, retrieve the policy for the parent.
4547 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4548 if (policy.mLastMaximumTimeToLock == timeMs) {
4551 policy.mLastMaximumTimeToLock = timeMs;
4553 final long ident = mInjector.binderClearCallingIdentity();
4555 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4556 // Make sure KEEP_SCREEN_ON is disabled, since that
4557 // would allow bypassing of the maximum time to lock.
4558 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4561 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4562 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4564 mInjector.binderRestoreCallingIdentity(ident);
4569 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4573 enforceFullCrossUsersPermission(userHandle);
4574 synchronized (this) {
4576 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4577 return admin != null ? admin.maximumTimeToUnlock : 0;
4579 // Return the strictest policy across all participating admins.
4580 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4581 userHandle, parent);
4582 return getMaximumTimeToLockPolicyFromAdmins(admins);
4587 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4591 enforceFullCrossUsersPermission(userHandle);
4592 synchronized (this) {
4593 // All admins for this user.
4594 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4595 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4596 DevicePolicyData policy = getUserData(userInfo.id);
4597 admins.addAll(policy.mAdminList);
4598 // If it is a managed profile, it may have parent active admins
4599 if (userInfo.isManagedProfile()) {
4600 for (ActiveAdmin admin : policy.mAdminList) {
4601 if (admin.hasParentActiveAdmin()) {
4602 admins.add(admin.getParentActiveAdmin());
4607 return getMaximumTimeToLockPolicyFromAdmins(admins);
4611 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4613 final int N = admins.size();
4614 for (int i = 0; i < N; i++) {
4615 ActiveAdmin admin = admins.get(i);
4617 time = admin.maximumTimeToUnlock;
4618 } else if (admin.maximumTimeToUnlock != 0
4619 && time > admin.maximumTimeToUnlock) {
4620 time = admin.maximumTimeToUnlock;
4627 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
4632 Preconditions.checkNotNull(who, "ComponentName is null");
4633 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
4634 // timeoutMs with value 0 means that the admin doesn't participate
4635 // timeoutMs is clamped to the interval in case the internal constants change in the future
4636 final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
4637 if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
4638 timeoutMs = minimumStrongAuthTimeout;
4640 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
4641 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4644 final int userHandle = mInjector.userHandleGetCallingUserId();
4645 synchronized (this) {
4646 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4647 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4648 if (ap.strongAuthUnlockTimeout != timeoutMs) {
4649 ap.strongAuthUnlockTimeout = timeoutMs;
4650 saveSettingsLocked(userHandle);
4656 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
4657 * admins if who is null.
4658 * Returns 0 if not configured for the provided admin.
4661 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
4663 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4665 enforceFullCrossUsersPermission(userId);
4666 synchronized (this) {
4668 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
4669 return admin != null ? admin.strongAuthUnlockTimeout : 0;
4672 // Return the strictest policy across all participating admins.
4673 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
4675 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4676 for (int i = 0; i < admins.size(); i++) {
4677 final long timeout = admins.get(i).strongAuthUnlockTimeout;
4678 if (timeout != 0) { // take only participating admins into account
4679 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
4682 return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
4686 private long getMinimumStrongAuthTimeoutMs() {
4687 if (!mInjector.isBuildDebuggable()) {
4688 return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
4690 // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
4691 // name cannot be longer than 31 characters
4692 return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
4693 MINIMUM_STRONG_AUTH_TIMEOUT_MS),
4694 MINIMUM_STRONG_AUTH_TIMEOUT_MS);
4698 public void lockNow(int flags, boolean parent) {
4703 final int callingUserId = mInjector.userHandleGetCallingUserId();
4704 synchronized (this) {
4705 // This API can only be called by an active device admin,
4706 // so try to retrieve it to check that the caller is one.
4707 final ActiveAdmin admin = getActiveAdminForCallerLocked(
4708 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4710 final long ident = mInjector.binderClearCallingIdentity();
4713 if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
4714 enforceManagedProfile(
4715 callingUserId, "set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
4716 if (!isProfileOwner(admin.info.getComponent(), callingUserId)) {
4717 throw new SecurityException("Only profile owner admins can set "
4718 + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
4721 throw new IllegalArgumentException(
4722 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent");
4724 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
4725 throw new UnsupportedOperationException(
4726 "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices");
4728 mUserManager.evictCredentialEncryptionKey(callingUserId);
4731 // Lock all users unless this is a managed profile with a separate challenge
4732 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
4733 ? UserHandle.USER_ALL : callingUserId);
4734 mLockPatternUtils.requireStrongAuth(
4735 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4737 // Require authentication for the device or profile
4738 if (userToLock == UserHandle.USER_ALL) {
4739 // Power off the display
4740 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4741 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4742 mInjector.getIWindowManager().lockNow(null);
4744 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4746 } catch (RemoteException e) {
4748 mInjector.binderRestoreCallingIdentity(ident);
4754 public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
4756 if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) {
4757 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4760 enforceProfileOrDeviceOwner(who);
4764 private void enforceProfileOrDeviceOwner(ComponentName who) {
4765 synchronized (this) {
4766 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4771 public boolean approveCaCert(String alias, int userId, boolean approval) {
4772 enforceManageUsers();
4773 synchronized (this) {
4774 Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4775 boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4779 saveSettingsLocked(userId);
4781 mCertificateMonitor.onCertificateApprovalsChanged(userId);
4786 public boolean isCaCertApproved(String alias, int userId) {
4787 enforceManageUsers();
4788 synchronized (this) {
4789 return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4793 private void removeCaApprovalsIfNeeded(int userId) {
4794 for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4795 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4796 if (userInfo.isManagedProfile()){
4797 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4800 synchronized (this) {
4801 getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4802 saveSettingsLocked(userInfo.id);
4804 mCertificateMonitor.onCertificateApprovalsChanged(userId);
4810 public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)
4811 throws RemoteException {
4815 enforceCanManageCaCerts(admin, callerPackage);
4819 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
4820 final long id = mInjector.binderClearCallingIdentity();
4822 alias = mCertificateMonitor.installCaCert(userHandle, certBuffer);
4823 if (alias == null) {
4824 Log.w(LOG_TAG, "Problem installing cert");
4828 mInjector.binderRestoreCallingIdentity(id);
4831 synchronized (this) {
4832 getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias);
4833 saveSettingsLocked(userHandle.getIdentifier());
4839 public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
4843 enforceCanManageCaCerts(admin, callerPackage);
4845 final int userId = mInjector.userHandleGetCallingUserId();
4846 final long id = mInjector.binderClearCallingIdentity();
4848 mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases);
4850 mInjector.binderRestoreCallingIdentity(id);
4853 synchronized (this) {
4854 if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) {
4855 saveSettingsLocked(userId);
4861 public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
4862 byte[] cert, byte[] chain, String alias, boolean requestAccess) {
4863 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
4864 DELEGATION_CERT_INSTALL);
4867 final int callingUid = mInjector.binderGetCallingUid();
4868 final long id = mInjector.binderClearCallingIdentity();
4870 final KeyChainConnection keyChainConnection =
4871 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4873 IKeyChainService keyChain = keyChainConnection.getService();
4874 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4877 if (requestAccess) {
4878 keyChain.setGrant(callingUid, alias, true);
4881 } catch (RemoteException e) {
4882 Log.e(LOG_TAG, "Installing certificate", e);
4884 keyChainConnection.close();
4886 } catch (InterruptedException e) {
4887 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4888 Thread.currentThread().interrupt();
4890 mInjector.binderRestoreCallingIdentity(id);
4896 public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
4897 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
4898 DELEGATION_CERT_INSTALL);
4900 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4901 final long id = Binder.clearCallingIdentity();
4903 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4905 IKeyChainService keyChain = keyChainConnection.getService();
4906 return keyChain.removeKeyPair(alias);
4907 } catch (RemoteException e) {
4908 Log.e(LOG_TAG, "Removing keypair", e);
4910 keyChainConnection.close();
4912 } catch (InterruptedException e) {
4913 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4914 Thread.currentThread().interrupt();
4916 Binder.restoreCallingIdentity(id);
4922 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4923 final IBinder response) {
4924 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4925 if (!isCallerWithSystemUid()) {
4929 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4930 // If there is a profile owner, redirect to that; otherwise query the device owner.
4931 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4932 if (aliasChooser == null && caller.isSystem()) {
4933 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4934 if (deviceOwnerAdmin != null) {
4935 aliasChooser = deviceOwnerAdmin.info.getComponent();
4938 if (aliasChooser == null) {
4939 sendPrivateKeyAliasResponse(null, response);
4943 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4944 intent.setComponent(aliasChooser);
4945 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4946 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4947 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4948 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4949 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4951 final long id = mInjector.binderClearCallingIdentity();
4953 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4955 public void onReceive(Context context, Intent intent) {
4956 final String chosenAlias = getResultData();
4957 sendPrivateKeyAliasResponse(chosenAlias, response);
4959 }, null, Activity.RESULT_OK, null, null);
4961 mInjector.binderRestoreCallingIdentity(id);
4965 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4966 final IKeyChainAliasCallback keyChainAliasResponse =
4967 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4968 // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback
4969 // is oneway, which means it won't block if the recipient lives in another process.
4971 keyChainAliasResponse.alias(alias);
4972 } catch (Exception e) {
4973 // Caller could throw RuntimeException or RemoteException back across processes. Catch
4974 // everything just to be sure.
4975 Log.e(LOG_TAG, "error while responding to callback", e);
4980 * Determine whether DPMS should check if a delegate package is already installed before
4981 * granting it new delegations via {@link #setDelegatedScopes}.
4983 private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage,
4984 int targetSdk, List<String> scopes) {
4985 // 1) Never skip is installed check from N.
4986 if (targetSdk >= Build.VERSION_CODES.N) {
4989 // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given.
4990 if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) {
4993 // 3) Skip if all previously granted scopes are being cleared.
4994 if (scopes.isEmpty()) {
4997 // Otherwise it should check that delegatePackage is installed.
5002 * Set the scopes of a device owner or profile owner delegate.
5004 * @param who the device owner or profile owner.
5005 * @param delegatePackage the name of the delegate package.
5006 * @param scopes the list of delegation scopes to be given to the delegate package.
5009 public void setDelegatedScopes(ComponentName who, String delegatePackage,
5010 List<String> scopes) throws SecurityException {
5011 Preconditions.checkNotNull(who, "ComponentName is null");
5012 Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
5013 Preconditions.checkCollectionElementsNotNull(scopes, "Scopes");
5014 // Remove possible duplicates.
5015 scopes = new ArrayList(new ArraySet(scopes));
5016 // Ensure given scopes are valid.
5017 if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
5018 throw new IllegalArgumentException("Unexpected delegation scopes");
5021 // Retrieve the user ID of the calling process.
5022 final int userId = mInjector.userHandleGetCallingUserId();
5023 synchronized (this) {
5024 // Ensure calling process is device/profile owner.
5025 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5026 // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
5027 if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage,
5028 getTargetSdk(who.getPackageName(), userId), scopes)) {
5029 // Throw when the delegate package is not installed.
5030 if (!isPackageInstalledForUser(delegatePackage, userId)) {
5031 throw new IllegalArgumentException("Package " + delegatePackage
5032 + " is not installed on the current user");
5036 // Set the new delegate in user policies.
5037 final DevicePolicyData policy = getUserData(userId);
5038 if (!scopes.isEmpty()) {
5039 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
5041 // Remove any delegation info if the given scopes list is empty.
5042 policy.mDelegationMap.remove(delegatePackage);
5045 // Notify delegate package of updates.
5046 final Intent intent = new Intent(
5047 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
5048 // Only call receivers registered with Context#registerReceiver (don’t wake delegate).
5049 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
5050 // Limit components this intent resolves to to the delegate package.
5051 intent.setPackage(delegatePackage);
5052 // Include the list of delegated scopes as an extra.
5053 intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES,
5054 (ArrayList<String>) scopes);
5055 // Send the broadcast.
5056 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
5059 saveSettingsLocked(userId);
5064 * Get the delegation scopes given to a delegate package by a device owner or profile owner.
5066 * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
5067 * passing in {@code null} as the {@code who} parameter and its own name as the
5068 * {@code delegatepackage}.
5070 * @param who the device owner or profile owner, or {@code null} if the caller is
5071 * {@code delegatePackage}.
5072 * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
5073 * @return a list of the delegation scopes currently given to {@code delegatePackage}.
5077 public List<String> getDelegatedScopes(ComponentName who,
5078 String delegatePackage) throws SecurityException {
5079 Preconditions.checkNotNull(delegatePackage, "Delegate package is null");
5081 // Retrieve the user ID of the calling process.
5082 final int callingUid = mInjector.binderGetCallingUid();
5083 final int userId = UserHandle.getUserId(callingUid);
5084 synchronized (this) {
5085 // Ensure calling process is device/profile owner.
5087 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5088 // Or ensure calling process is delegatePackage itself.
5092 uid = mInjector.getPackageManager()
5093 .getPackageUidAsUser(delegatePackage, userId);
5094 } catch(NameNotFoundException e) {
5096 if (uid != callingUid) {
5097 throw new SecurityException("Caller with uid " + callingUid + " is not "
5101 final DevicePolicyData policy = getUserData(userId);
5102 // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
5103 final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5104 return scopes == null ? Collections.EMPTY_LIST : scopes;
5109 * Get a list of packages that were given a specific delegation scopes by a device owner or
5112 * @param who the device owner or profile owner.
5113 * @param scope the scope whose delegates are to be retrieved.
5114 * @return a list of the delegate packages currently given the {@code scope} delegation.
5117 public List<String> getDelegatePackages(ComponentName who, String scope)
5118 throws SecurityException {
5119 Preconditions.checkNotNull(who, "ComponentName is null");
5120 Preconditions.checkNotNull(scope, "Scope is null");
5121 if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5122 throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5125 // Retrieve the user ID of the calling process.
5126 final int userId = mInjector.userHandleGetCallingUserId();
5127 synchronized (this) {
5128 // Ensure calling process is device/profile owner.
5129 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5130 final DevicePolicyData policy = getUserData(userId);
5132 // Create a list to hold the resulting delegate packages.
5133 final List<String> delegatePackagesWithScope = new ArrayList<>();
5134 // Add all delegations containing scope to the result list.
5135 for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5136 if (policy.mDelegationMap.valueAt(i).contains(scope)) {
5137 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
5140 return delegatePackagesWithScope;
5145 * Check whether a caller application has been delegated a given scope via
5146 * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
5149 * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
5150 * then comparing the calling UID with the UID of {@code callerPackage} as reported by
5151 * {@link PackageManager#getPackageUidAsUser}.
5153 * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
5154 * @param scope the delegation scope to be checked.
5155 * @return {@code true} if the calling process is a delegate of {@code scope}.
5157 private boolean isCallerDelegate(String callerPackage, String scope) {
5158 Preconditions.checkNotNull(callerPackage, "callerPackage is null");
5159 if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5160 throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5163 // Retrieve the UID and user ID of the calling process.
5164 final int callingUid = mInjector.binderGetCallingUid();
5165 final int userId = UserHandle.getUserId(callingUid);
5166 synchronized (this) {
5167 // Retrieve user policy data.
5168 final DevicePolicyData policy = getUserData(userId);
5169 // Retrieve the list of delegation scopes granted to callerPackage.
5170 final List<String> scopes = policy.mDelegationMap.get(callerPackage);
5171 // Check callingUid only if callerPackage has the required scope delegation.
5172 if (scopes != null && scopes.contains(scope)) {
5174 // Retrieve the expected UID for callerPackage.
5175 final int uid = mInjector.getPackageManager()
5176 .getPackageUidAsUser(callerPackage, userId);
5177 // Return true if the caller is actually callerPackage.
5178 return uid == callingUid;
5179 } catch (NameNotFoundException e) {
5188 * Throw a security exception if a ComponentName is given and it is not a device/profile owner
5189 * or if the calling process is not a delegate of the given scope.
5191 * @param who the device owner of profile owner, or null if {@code callerPackage} is a
5192 * {@code scope} delegate.
5193 * @param callerPackage the name of the calling package. Required if {@code who} is
5195 * @param reqPolicy the policy used in the API whose access permission is being checked.
5196 * @param scope the delegation scope corresponding to the API being checked.
5197 * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy};
5198 * or when {@code who} is {@code null} and {@code callerPackage} is not a delegate
5201 private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy,
5203 // If a ComponentName is given ensure it is a device or profile owner according to policy.
5205 synchronized (this) {
5206 getActiveAdminForCallerLocked(who, reqPolicy);
5208 // If no ComponentName is given ensure calling process has scope delegation.
5209 } else if (!isCallerDelegate(callerPackage, scope)) {
5210 throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid()
5211 + " is not a delegate of scope " + scope + ".");
5216 * Helper function to preserve delegation behavior pre-O when using the deprecated functions
5217 * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
5219 private void setDelegatedScopePreO(ComponentName who,
5220 String delegatePackage, String scope) {
5221 Preconditions.checkNotNull(who, "ComponentName is null");
5223 final int userId = mInjector.userHandleGetCallingUserId();
5224 synchronized(this) {
5225 // Ensure calling process is device/profile owner.
5226 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5227 final DevicePolicyData policy = getUserData(userId);
5229 if (delegatePackage != null) {
5230 // Set package as a delegate for scope if it is not already one.
5231 List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5232 if (scopes == null) {
5233 scopes = new ArrayList<>();
5235 if (!scopes.contains(scope)) {
5237 setDelegatedScopes(who, delegatePackage, scopes);
5241 // Clear any existing scope delegates.
5242 for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5243 final String currentPackage = policy.mDelegationMap.keyAt(i);
5244 final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
5246 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) {
5247 final List<String> newScopes = new ArrayList(currentScopes);
5248 newScopes.remove(scope);
5249 setDelegatedScopes(who, currentPackage, newScopes);
5256 public void setCertInstallerPackage(ComponentName who, String installerPackage)
5257 throws SecurityException {
5258 setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
5262 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
5263 final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
5264 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
5268 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
5269 * not installed and therefore not available.
5271 * @throws SecurityException if the caller is not a profile or device owner.
5272 * @throws UnsupportedOperationException if the package does not support being set as always-on.
5275 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
5276 throws SecurityException {
5277 enforceProfileOrDeviceOwner(admin);
5279 final int userId = mInjector.userHandleGetCallingUserId();
5280 final long token = mInjector.binderClearCallingIdentity();
5282 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
5285 ConnectivityManager connectivityManager = (ConnectivityManager)
5286 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5287 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
5288 throw new UnsupportedOperationException();
5291 mInjector.binderRestoreCallingIdentity(token);
5297 public String getAlwaysOnVpnPackage(ComponentName admin)
5298 throws SecurityException {
5299 enforceProfileOrDeviceOwner(admin);
5301 final int userId = mInjector.userHandleGetCallingUserId();
5302 final long token = mInjector.binderClearCallingIdentity();
5304 ConnectivityManager connectivityManager = (ConnectivityManager)
5305 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5306 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
5308 mInjector.binderRestoreCallingIdentity(token);
5312 private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc) {
5315 if (wipeExtRequested) {
5316 StorageManager sm = (StorageManager) mContext.getSystemService(
5317 Context.STORAGE_SERVICE);
5318 sm.wipeAdoptableDisks();
5321 mInjector.recoverySystemRebootWipeUserData(
5322 /*shutdown=*/ false, reason, /*force=*/ true, /*wipeEuicc=*/ wipeEuicc);
5323 } catch (IOException | SecurityException e) {
5324 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
5328 private void forceWipeUser(int userId) {
5330 IActivityManager am = mInjector.getIActivityManager();
5331 if (am.getCurrentUser().id == userId) {
5332 am.switchUser(UserHandle.USER_SYSTEM);
5335 boolean userRemoved = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
5337 Slog.w(LOG_TAG, "Couldn't remove user " + userId);
5338 } else if (isManagedProfile(userId)) {
5339 sendWipeProfileNotification();
5341 } catch (RemoteException re) {
5347 public void wipeData(int flags) {
5351 enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId());
5353 final ActiveAdmin admin;
5354 synchronized (this) {
5355 admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA);
5357 String reason = "DevicePolicyManager.wipeData() from "
5358 + admin.info.getComponent().flattenToShortString();
5360 admin.info.getComponent(), flags, reason, admin.getUserHandle().getIdentifier());
5363 private void wipeDataNoLock(ComponentName admin, int flags, String reason, int userId) {
5366 long ident = mInjector.binderClearCallingIdentity();
5368 // First check whether the admin is allowed to wipe the device/user/profile.
5369 final String restriction;
5370 if (userId == UserHandle.USER_SYSTEM) {
5371 restriction = UserManager.DISALLOW_FACTORY_RESET;
5372 } else if (isManagedProfile(userId)) {
5373 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
5375 restriction = UserManager.DISALLOW_REMOVE_USER;
5377 if (isAdminAffectedByRestriction(admin, restriction, userId)) {
5378 throw new SecurityException("Cannot wipe data. " + restriction
5379 + " restriction is set for user " + userId);
5382 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
5383 if (!isDeviceOwner(admin, userId)) {
5384 throw new SecurityException(
5385 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
5387 PersistentDataBlockManager manager = (PersistentDataBlockManager)
5388 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
5389 if (manager != null) {
5394 // TODO If split user is enabled and the device owner is set in the primary user
5395 // (rather than system), we should probably trigger factory reset. Current code just
5396 // removes that user (but still clears FRP...)
5397 if (userId == UserHandle.USER_SYSTEM) {
5398 forceWipeDeviceNoLock(/*wipeExtRequested=*/ (flags & WIPE_EXTERNAL_STORAGE) != 0,
5399 reason, /*wipeEuicc=*/ (flags & WIPE_EUICC) != 0);
5401 forceWipeUser(userId);
5404 mInjector.binderRestoreCallingIdentity(ident);
5408 private void sendWipeProfileNotification() {
5409 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
5410 Notification notification =
5411 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
5412 .setSmallIcon(android.R.drawable.stat_sys_warning)
5413 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
5414 .setContentText(contentText)
5415 .setColor(mContext.getColor(R.color.system_notification_accent_color))
5416 .setStyle(new Notification.BigTextStyle().bigText(contentText))
5418 mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification);
5421 private void clearWipeProfileNotification() {
5422 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED);
5426 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
5430 enforceFullCrossUsersPermission(userHandle);
5431 mContext.enforceCallingOrSelfPermission(
5432 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5434 synchronized (this) {
5435 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
5436 if (admin == null) {
5437 result.sendResult(null);
5440 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
5441 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
5442 intent.setComponent(admin.info.getComponent());
5443 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
5444 null, new BroadcastReceiver() {
5446 public void onReceive(Context context, Intent intent) {
5447 result.sendResult(getResultExtras(false));
5449 }, null, Activity.RESULT_OK, null, null);
5454 public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
5458 enforceFullCrossUsersPermission(userHandle);
5459 mContext.enforceCallingOrSelfPermission(
5460 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5462 // If the managed profile doesn't have a separate password, set the metrics to default
5463 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
5464 metrics = new PasswordMetrics();
5467 validateQualityConstant(metrics.quality);
5468 DevicePolicyData policy = getUserData(userHandle);
5469 synchronized (this) {
5470 policy.mActivePasswordMetrics = metrics;
5471 policy.mPasswordStateHasBeenSetSinceBoot = true;
5476 public void reportPasswordChanged(@UserIdInt int userId) {
5480 enforceFullCrossUsersPermission(userId);
5482 // Managed Profile password can only be changed when it has a separate challenge.
5483 if (!isSeparateProfileChallengeEnabled(userId)) {
5484 enforceNotManagedProfile(userId, "set the active password");
5487 mContext.enforceCallingOrSelfPermission(
5488 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5490 DevicePolicyData policy = getUserData(userId);
5492 long ident = mInjector.binderClearCallingIdentity();
5494 synchronized (this) {
5495 policy.mFailedPasswordAttempts = 0;
5496 updatePasswordValidityCheckpointLocked(userId);
5497 saveSettingsLocked(userId);
5498 updatePasswordExpirationsLocked(userId);
5499 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
5501 // Send a broadcast to each profile using this password as its primary unlock.
5502 sendAdminCommandForLockscreenPoliciesLocked(
5503 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
5504 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
5506 removeCaApprovalsIfNeeded(userId);
5508 mInjector.binderRestoreCallingIdentity(ident);
5513 * Called any time the device password is updated. Resets all password expiration clocks.
5515 private void updatePasswordExpirationsLocked(int userHandle) {
5516 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
5517 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5518 userHandle, /* parent */ false);
5519 final int N = admins.size();
5520 for (int i = 0; i < N; i++) {
5521 ActiveAdmin admin = admins.get(i);
5522 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
5523 affectedUserIds.add(admin.getUserHandle().getIdentifier());
5524 long timeout = admin.passwordExpirationTimeout;
5525 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
5526 admin.passwordExpirationDate = expiration;
5529 for (int affectedUserId : affectedUserIds) {
5530 saveSettingsLocked(affectedUserId);
5535 public void reportFailedPasswordAttempt(int userHandle) {
5536 enforceFullCrossUsersPermission(userHandle);
5537 if (!isSeparateProfileChallengeEnabled(userHandle)) {
5538 enforceNotManagedProfile(userHandle,
5539 "report failed password attempt if separate profile challenge is not in place");
5541 mContext.enforceCallingOrSelfPermission(
5542 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5544 boolean wipeData = false;
5545 ActiveAdmin strictestAdmin = null;
5546 final long ident = mInjector.binderClearCallingIdentity();
5548 synchronized (this) {
5549 DevicePolicyData policy = getUserData(userHandle);
5550 policy.mFailedPasswordAttempts++;
5551 saveSettingsLocked(userHandle);
5553 strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
5554 userHandle, /* parent */ false);
5555 int max = strictestAdmin != null
5556 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
5557 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
5561 sendAdminCommandForLockscreenPoliciesLocked(
5562 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
5563 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5567 mInjector.binderRestoreCallingIdentity(ident);
5570 if (wipeData && strictestAdmin != null) {
5571 final int userId = strictestAdmin.getUserHandle().getIdentifier();
5572 Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
5573 + strictestAdmin.info.getComponent().flattenToShortString()
5574 + ". Calling wipeData for user " + userId);
5576 // Attempt to wipe the device/user/profile associated with the admin, as if the
5577 // admin had called wipeData(). That way we can check whether the admin is actually
5578 // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
5579 // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
5581 // IMPORTANT: Call without holding the lock to prevent deadlock.
5583 wipeDataNoLock(strictestAdmin.info.getComponent(),
5585 /*reason=*/ "reportFailedPasswordAttempt()",
5587 } catch (SecurityException e) {
5588 Slog.w(LOG_TAG, "Failed to wipe user " + userId
5589 + " after max failed password attempts reached.", e);
5593 if (mInjector.securityLogIsLoggingEnabled()) {
5594 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5595 /*method strength*/ 1);
5600 public void reportSuccessfulPasswordAttempt(int userHandle) {
5601 enforceFullCrossUsersPermission(userHandle);
5602 mContext.enforceCallingOrSelfPermission(
5603 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5605 synchronized (this) {
5606 DevicePolicyData policy = getUserData(userHandle);
5607 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
5608 long ident = mInjector.binderClearCallingIdentity();
5610 policy.mFailedPasswordAttempts = 0;
5611 policy.mPasswordOwner = -1;
5612 saveSettingsLocked(userHandle);
5614 sendAdminCommandForLockscreenPoliciesLocked(
5615 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
5616 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5619 mInjector.binderRestoreCallingIdentity(ident);
5624 if (mInjector.securityLogIsLoggingEnabled()) {
5625 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5626 /*method strength*/ 1);
5631 public void reportFailedFingerprintAttempt(int userHandle) {
5632 enforceFullCrossUsersPermission(userHandle);
5633 mContext.enforceCallingOrSelfPermission(
5634 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5635 if (mInjector.securityLogIsLoggingEnabled()) {
5636 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5637 /*method strength*/ 0);
5642 public void reportSuccessfulFingerprintAttempt(int userHandle) {
5643 enforceFullCrossUsersPermission(userHandle);
5644 mContext.enforceCallingOrSelfPermission(
5645 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5646 if (mInjector.securityLogIsLoggingEnabled()) {
5647 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5648 /*method strength*/ 0);
5653 public void reportKeyguardDismissed(int userHandle) {
5654 enforceFullCrossUsersPermission(userHandle);
5655 mContext.enforceCallingOrSelfPermission(
5656 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5658 if (mInjector.securityLogIsLoggingEnabled()) {
5659 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
5664 public void reportKeyguardSecured(int userHandle) {
5665 enforceFullCrossUsersPermission(userHandle);
5666 mContext.enforceCallingOrSelfPermission(
5667 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5669 if (mInjector.securityLogIsLoggingEnabled()) {
5670 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
5675 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
5676 String exclusionList) {
5680 synchronized(this) {
5681 Preconditions.checkNotNull(who, "ComponentName is null");
5683 // Only check if system user has set global proxy. We don't allow other users to set it.
5684 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5685 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5686 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
5688 // Scan through active admins and find if anyone has already
5689 // set the global proxy.
5690 Set<ComponentName> compSet = policy.mAdminMap.keySet();
5691 for (ComponentName component : compSet) {
5692 ActiveAdmin ap = policy.mAdminMap.get(component);
5693 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
5694 // Another admin already sets the global proxy
5695 // Return it to the caller.
5700 // If the user is not system, don't set the global proxy. Fail silently.
5701 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
5702 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
5703 + UserHandle.getCallingUserId() + " is not permitted.");
5706 if (proxySpec == null) {
5707 admin.specifiesGlobalProxy = false;
5708 admin.globalProxySpec = null;
5709 admin.globalProxyExclusionList = null;
5712 admin.specifiesGlobalProxy = true;
5713 admin.globalProxySpec = proxySpec;
5714 admin.globalProxyExclusionList = exclusionList;
5717 // Reset the global proxy accordingly
5718 // Do this using system permissions, as apps cannot write to secure settings
5719 long origId = mInjector.binderClearCallingIdentity();
5721 resetGlobalProxyLocked(policy);
5723 mInjector.binderRestoreCallingIdentity(origId);
5730 public ComponentName getGlobalProxyAdmin(int userHandle) {
5734 enforceFullCrossUsersPermission(userHandle);
5735 synchronized(this) {
5736 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5737 // Scan through active admins and find if anyone has already
5738 // set the global proxy.
5739 final int N = policy.mAdminList.size();
5740 for (int i = 0; i < N; i++) {
5741 ActiveAdmin ap = policy.mAdminList.get(i);
5742 if (ap.specifiesGlobalProxy) {
5743 // Device admin sets the global proxy
5744 // Return it to the caller.
5745 return ap.info.getComponent();
5749 // No device admin sets the global proxy.
5754 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5755 synchronized (this) {
5756 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5758 long token = mInjector.binderClearCallingIdentity();
5760 ConnectivityManager connectivityManager = (ConnectivityManager)
5761 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5762 connectivityManager.setGlobalProxy(proxyInfo);
5764 mInjector.binderRestoreCallingIdentity(token);
5768 private void resetGlobalProxyLocked(DevicePolicyData policy) {
5769 final int N = policy.mAdminList.size();
5770 for (int i = 0; i < N; i++) {
5771 ActiveAdmin ap = policy.mAdminList.get(i);
5772 if (ap.specifiesGlobalProxy) {
5773 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5777 // No device admins defining global proxies - reset global proxy settings to none
5778 saveGlobalProxyLocked(null, null);
5781 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5782 if (exclusionList == null) {
5785 if (proxySpec == null) {
5788 // Remove white spaces
5789 proxySpec = proxySpec.trim();
5790 String data[] = proxySpec.split(":");
5791 int proxyPort = 8080;
5792 if (data.length > 1) {
5794 proxyPort = Integer.parseInt(data[1]);
5795 } catch (NumberFormatException e) {}
5797 exclusionList = exclusionList.trim();
5799 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5800 if (!proxyProperties.isValid()) {
5801 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5804 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5805 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5806 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5811 * Set the storage encryption request for a single admin. Returns the new total request
5812 * status (for all admins).
5815 public int setStorageEncryption(ComponentName who, boolean encrypt) {
5817 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5819 Preconditions.checkNotNull(who, "ComponentName is null");
5820 final int userHandle = UserHandle.getCallingUserId();
5821 synchronized (this) {
5822 // Check for permissions
5823 // Only system user can set storage encryption
5824 if (userHandle != UserHandle.USER_SYSTEM) {
5825 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5826 + UserHandle.getCallingUserId() + " is not permitted.");
5830 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5831 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5833 // Quick exit: If the filesystem does not support encryption, we can exit early.
5834 if (!isEncryptionSupported()) {
5835 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5838 // (1) Record the value for the admin so it's sticky
5839 if (ap.encryptionRequested != encrypt) {
5840 ap.encryptionRequested = encrypt;
5841 saveSettingsLocked(userHandle);
5844 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5845 // (2) Compute "max" for all admins
5846 boolean newRequested = false;
5847 final int N = policy.mAdminList.size();
5848 for (int i = 0; i < N; i++) {
5849 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5852 // Notify OS of new request
5853 setEncryptionRequested(newRequested);
5855 // Return the new global request status
5857 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5858 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5863 * Get the current storage encryption request status for a given admin, or aggregate of all
5867 public boolean getStorageEncryption(ComponentName who, int userHandle) {
5871 enforceFullCrossUsersPermission(userHandle);
5872 synchronized (this) {
5873 // Check for permissions if a particular caller is specified
5875 // When checking for a single caller, status is based on caller's request
5876 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5877 return ap != null ? ap.encryptionRequested : false;
5880 // If no particular caller is specified, return the aggregate set of requests.
5881 // This is short circuited by returning true on the first hit.
5882 DevicePolicyData policy = getUserData(userHandle);
5883 final int N = policy.mAdminList.size();
5884 for (int i = 0; i < N; i++) {
5885 if (policy.mAdminList.get(i).encryptionRequested) {
5894 * Get the current encryption status of the device.
5897 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5899 // Ok to return current status.
5901 enforceFullCrossUsersPermission(userHandle);
5903 // It's not critical here, but let's make sure the package name is correct, in case
5904 // we start using it for different purposes.
5905 ensureCallerPackage(callerPackage);
5907 final ApplicationInfo ai;
5909 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5910 } catch (RemoteException e) {
5911 throw new SecurityException(e);
5914 boolean legacyApp = false;
5915 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5919 final int rawStatus = getEncryptionStatus();
5920 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5921 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5927 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
5929 private boolean isEncryptionSupported() {
5930 // Note, this can be implemented as
5931 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5932 // But is provided as a separate internal method if there's a faster way to do a
5933 // simple check for supported-or-not.
5934 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5938 * Hook to low-levels: Reporting the current status of encryption.
5939 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5940 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5941 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5942 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5943 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5945 private int getEncryptionStatus() {
5946 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5947 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5948 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5949 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5950 } else if (mInjector.storageManagerIsEncrypted()) {
5951 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5952 } else if (mInjector.storageManagerIsEncryptable()) {
5953 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5955 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5960 * Hook to low-levels: If needed, record the new admin setting for encryption.
5962 private void setEncryptionRequested(boolean encrypt) {
5966 * Set whether the screen capture is disabled for the user managed by the specified admin.
5969 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5973 Preconditions.checkNotNull(who, "ComponentName is null");
5974 final int userHandle = UserHandle.getCallingUserId();
5975 synchronized (this) {
5976 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5977 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5978 if (ap.disableScreenCapture != disabled) {
5979 ap.disableScreenCapture = disabled;
5980 saveSettingsLocked(userHandle);
5981 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5987 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5988 * active admin (if given admin is null).
5991 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5995 synchronized (this) {
5997 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5998 return (admin != null) ? admin.disableScreenCapture : false;
6001 DevicePolicyData policy = getUserData(userHandle);
6002 final int N = policy.mAdminList.size();
6003 for (int i = 0; i < N; i++) {
6004 ActiveAdmin admin = policy.mAdminList.get(i);
6005 if (admin.disableScreenCapture) {
6013 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
6014 final boolean disabled) {
6015 mHandler.post(new Runnable() {
6019 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
6020 } catch (RemoteException e) {
6021 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
6028 * Set whether auto time is required by the specified admin (must be device or profile owner).
6031 public void setAutoTimeRequired(ComponentName who, boolean required) {
6035 Preconditions.checkNotNull(who, "ComponentName is null");
6036 final int userHandle = UserHandle.getCallingUserId();
6037 synchronized (this) {
6038 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6039 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6040 if (admin.requireAutoTime != required) {
6041 admin.requireAutoTime = required;
6042 saveSettingsLocked(userHandle);
6046 // Turn AUTO_TIME on in settings if it is required
6048 long ident = mInjector.binderClearCallingIdentity();
6050 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
6052 mInjector.binderRestoreCallingIdentity(ident);
6058 * Returns whether or not auto time is required by the device owner or any profile owner.
6061 public boolean getAutoTimeRequired() {
6065 synchronized (this) {
6066 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6067 if (deviceOwner != null && deviceOwner.requireAutoTime) {
6068 // If the device owner enforces auto time, we don't need to check the PO's
6072 // Now check to see if any profile owner on any user enforces auto time
6073 for (Integer userId : mOwners.getProfileOwnerKeys()) {
6074 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
6075 if (profileOwner != null && profileOwner.requireAutoTime) {
6085 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
6089 Preconditions.checkNotNull(who, "ComponentName is null");
6090 // Allow setting this policy to true only if there is a split system user.
6091 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
6092 throw new UnsupportedOperationException(
6093 "Cannot force ephemeral users on systems without split system user.");
6095 boolean removeAllUsers = false;
6096 synchronized (this) {
6097 final ActiveAdmin deviceOwner =
6098 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6099 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
6100 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
6101 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
6102 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
6103 removeAllUsers = forceEphemeralUsers;
6106 if (removeAllUsers) {
6107 long identitity = mInjector.binderClearCallingIdentity();
6109 mUserManagerInternal.removeAllUsers();
6111 mInjector.binderRestoreCallingIdentity(identitity);
6117 public boolean getForceEphemeralUsers(ComponentName who) {
6121 Preconditions.checkNotNull(who, "ComponentName is null");
6122 synchronized (this) {
6123 final ActiveAdmin deviceOwner =
6124 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6125 return deviceOwner.forceEphemeralUsers;
6129 private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) throws SecurityException {
6130 synchronized (this) {
6131 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6132 if (!areAllUsersAffiliatedWithDeviceLocked()) {
6133 throw new SecurityException("Not all users are affiliated.");
6139 public boolean requestBugreport(ComponentName who) {
6143 Preconditions.checkNotNull(who, "ComponentName is null");
6145 // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
6146 // which could still contain data related to that user. Should we disallow that, e.g. until
6147 // next boot? Might not be needed given that this still requires user consent.
6148 ensureDeviceOwnerAndAllUsersAffiliated(who);
6150 if (mRemoteBugreportServiceIsActive.get()
6151 || (getDeviceOwnerRemoteBugreportUri() != null)) {
6152 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
6156 final long currentTime = System.currentTimeMillis();
6157 synchronized (this) {
6158 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
6159 if (currentTime > policyData.mLastBugReportRequestTime) {
6160 policyData.mLastBugReportRequestTime = currentTime;
6161 saveSettingsLocked(UserHandle.USER_SYSTEM);
6165 final long callingIdentity = mInjector.binderClearCallingIdentity();
6167 mInjector.getIActivityManager().requestBugReport(
6168 ActivityManager.BUGREPORT_OPTION_REMOTE);
6170 mRemoteBugreportServiceIsActive.set(true);
6171 mRemoteBugreportSharingAccepted.set(false);
6172 registerRemoteBugreportReceivers();
6173 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
6174 RemoteBugreportUtils.NOTIFICATION_ID,
6175 RemoteBugreportUtils.buildNotification(mContext,
6176 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
6177 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
6178 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
6180 } catch (RemoteException re) {
6181 // should never happen
6182 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
6185 mInjector.binderRestoreCallingIdentity(callingIdentity);
6189 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
6190 Intent intent = new Intent(action);
6191 intent.setComponent(mOwners.getDeviceOwnerComponent());
6192 if (extras != null) {
6193 intent.putExtras(extras);
6195 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
6198 private synchronized String getDeviceOwnerRemoteBugreportUri() {
6199 return mOwners.getDeviceOwnerRemoteBugreportUri();
6202 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
6203 String bugreportHash) {
6204 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
6207 private void registerRemoteBugreportReceivers() {
6209 IntentFilter filterFinished = new IntentFilter(
6210 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
6211 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6212 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
6213 } catch (IntentFilter.MalformedMimeTypeException e) {
6214 // should never happen, as setting a constant
6215 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
6217 IntentFilter filterConsent = new IntentFilter();
6218 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
6219 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
6220 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
6223 private void onBugreportFinished(Intent intent) {
6224 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6225 mRemoteBugreportServiceIsActive.set(false);
6226 Uri bugreportUri = intent.getData();
6227 String bugreportUriString = null;
6228 if (bugreportUri != null) {
6229 bugreportUriString = bugreportUri.toString();
6231 String bugreportHash = intent.getStringExtra(
6232 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
6233 if (mRemoteBugreportSharingAccepted.get()) {
6234 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6235 mInjector.getNotificationManager().cancel(LOG_TAG,
6236 RemoteBugreportUtils.NOTIFICATION_ID);
6238 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
6239 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6240 RemoteBugreportUtils.buildNotification(mContext,
6241 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
6244 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6247 private void onBugreportFailed() {
6248 mRemoteBugreportServiceIsActive.set(false);
6249 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6250 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6251 mRemoteBugreportSharingAccepted.set(false);
6252 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6253 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
6254 Bundle extras = new Bundle();
6255 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6256 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
6257 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6258 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
6259 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6262 private void onBugreportSharingAccepted() {
6263 mRemoteBugreportSharingAccepted.set(true);
6264 String bugreportUriString = null;
6265 String bugreportHash = null;
6266 synchronized (this) {
6267 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
6268 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
6270 if (bugreportUriString != null) {
6271 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6272 } else if (mRemoteBugreportServiceIsActive.get()) {
6273 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6274 RemoteBugreportUtils.buildNotification(mContext,
6275 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
6280 private void onBugreportSharingDeclined() {
6281 if (mRemoteBugreportServiceIsActive.get()) {
6282 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6283 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6284 mRemoteBugreportServiceIsActive.set(false);
6285 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6286 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6288 mRemoteBugreportSharingAccepted.set(false);
6289 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6290 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
6293 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
6294 String bugreportHash) {
6295 ParcelFileDescriptor pfd = null;
6297 if (bugreportUriString == null) {
6298 throw new FileNotFoundException();
6300 Uri bugreportUri = Uri.parse(bugreportUriString);
6301 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
6303 synchronized (this) {
6304 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
6305 intent.setComponent(mOwners.getDeviceOwnerComponent());
6306 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6307 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
6308 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
6310 LocalServices.getService(ActivityManagerInternal.class)
6311 .grantUriPermissionFromIntent(Process.SHELL_UID,
6312 mOwners.getDeviceOwnerComponent().getPackageName(),
6313 intent, mOwners.getDeviceOwnerUserId());
6314 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
6316 } catch (FileNotFoundException e) {
6317 Bundle extras = new Bundle();
6318 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6319 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
6320 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6326 } catch (IOException ex) {
6329 mRemoteBugreportSharingAccepted.set(false);
6330 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6335 * Disables all device cameras according to the specified admin.
6338 public void setCameraDisabled(ComponentName who, boolean disabled) {
6342 Preconditions.checkNotNull(who, "ComponentName is null");
6343 final int userHandle = mInjector.userHandleGetCallingUserId();
6344 synchronized (this) {
6345 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6346 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
6347 if (ap.disableCamera != disabled) {
6348 ap.disableCamera = disabled;
6349 saveSettingsLocked(userHandle);
6352 // Tell the user manager that the restrictions have changed.
6353 pushUserRestrictions(userHandle);
6357 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
6361 public boolean getCameraDisabled(ComponentName who, int userHandle) {
6362 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
6365 private boolean getCameraDisabled(ComponentName who, int userHandle,
6366 boolean mergeDeviceOwnerRestriction) {
6370 synchronized (this) {
6372 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6373 return (admin != null) ? admin.disableCamera : false;
6375 // First, see if DO has set it. If so, it's device-wide.
6376 if (mergeDeviceOwnerRestriction) {
6377 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6378 if (deviceOwner != null && deviceOwner.disableCamera) {
6383 // Then check each device admin on the user.
6384 DevicePolicyData policy = getUserData(userHandle);
6385 // Determine whether or not the device camera is disabled for any active admins.
6386 final int N = policy.mAdminList.size();
6387 for (int i = 0; i < N; i++) {
6388 ActiveAdmin admin = policy.mAdminList.get(i);
6389 if (admin.disableCamera) {
6398 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
6402 Preconditions.checkNotNull(who, "ComponentName is null");
6403 final int userHandle = mInjector.userHandleGetCallingUserId();
6404 if (isManagedProfile(userHandle)) {
6406 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
6408 which = which & PROFILE_KEYGUARD_FEATURES;
6411 synchronized (this) {
6412 ActiveAdmin ap = getActiveAdminForCallerLocked(
6413 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6414 if (ap.disabledKeyguardFeatures != which) {
6415 ap.disabledKeyguardFeatures = which;
6416 saveSettingsLocked(userHandle);
6422 * Gets the disabled state for features in keyguard for the given admin,
6423 * or the aggregate of all active admins if who is null.
6426 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
6430 enforceFullCrossUsersPermission(userHandle);
6431 final long ident = mInjector.binderClearCallingIdentity();
6433 synchronized (this) {
6435 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
6436 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
6439 final List<ActiveAdmin> admins;
6440 if (!parent && isManagedProfile(userHandle)) {
6441 // If we are being asked about a managed profile, just return keyguard features
6442 // disabled by admins in the profile.
6443 admins = getUserDataUnchecked(userHandle).mAdminList;
6445 // Otherwise return those set by admins in the user and its profiles.
6446 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6449 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
6450 final int N = admins.size();
6451 for (int i = 0; i < N; i++) {
6452 ActiveAdmin admin = admins.get(i);
6453 int userId = admin.getUserHandle().getIdentifier();
6454 boolean isRequestedUser = !parent && (userId == userHandle);
6455 if (isRequestedUser || !isManagedProfile(userId)) {
6456 // If we are being asked explicitly about this user
6457 // return all disabled features even if its a managed profile.
6458 which |= admin.disabledKeyguardFeatures;
6460 // Otherwise a managed profile is only allowed to disable
6461 // some features on the parent user.
6462 which |= (admin.disabledKeyguardFeatures
6463 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
6469 mInjector.binderRestoreCallingIdentity(ident);
6474 public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
6475 List<String> packageList) {
6479 Preconditions.checkNotNull(packageList, "packageList is null");
6480 final int userHandle = UserHandle.getCallingUserId();
6481 synchronized (this) {
6482 // Ensure the caller is a DO or a keep uninstalled packages delegate.
6483 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6484 DELEGATION_KEEP_UNINSTALLED_PACKAGES);
6485 // Get the device owner
6486 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6487 // Set list of packages to be kept even if uninstalled.
6488 deviceOwner.keepUninstalledPackages = packageList;
6490 saveSettingsLocked(userHandle);
6491 // Notify package manager.
6492 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
6497 public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
6501 // TODO In split system user mode, allow apps on user 0 to query the list
6502 synchronized (this) {
6503 // Ensure the caller is a DO or a keep uninstalled packages delegate.
6504 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6505 DELEGATION_KEEP_UNINSTALLED_PACKAGES);
6506 return getKeepUninstalledPackagesLocked();
6510 private List<String> getKeepUninstalledPackagesLocked() {
6511 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6512 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
6516 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
6521 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
6522 throw new IllegalArgumentException("Invalid component " + admin
6523 + " for device owner");
6525 final boolean hasIncompatibleAccountsOrNonAdb =
6526 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin);
6527 synchronized (this) {
6528 enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb);
6529 final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
6530 if (activeAdmin == null
6531 || getUserData(userId).mRemovingAdmins.contains(admin)) {
6532 throw new IllegalArgumentException("Not active admin: " + admin);
6535 // Shutting down backup manager service permanently.
6536 long ident = mInjector.binderClearCallingIdentity();
6538 if (mInjector.getIBackupManager() != null) {
6539 mInjector.getIBackupManager()
6540 .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
6542 } catch (RemoteException e) {
6543 throw new IllegalStateException("Failed deactivating backup service.", e);
6545 mInjector.binderRestoreCallingIdentity(ident);
6549 // Log device owner provisioning was started using adb.
6550 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
6553 mOwners.setDeviceOwner(admin, ownerName, userId);
6554 mOwners.writeDeviceOwner();
6555 updateDeviceOwnerLocked();
6556 setDeviceOwnerSystemPropertyLocked();
6558 final Set<String> restrictions =
6559 UserRestrictionsUtils.getDefaultEnabledForDeviceOwner();
6560 if (!restrictions.isEmpty()) {
6561 for (String restriction : restrictions) {
6562 activeAdmin.ensureUserRestrictions().putBoolean(restriction, true);
6564 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions);
6565 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions);
6567 saveUserRestrictionsLocked(userId);
6570 ident = mInjector.binderClearCallingIdentity();
6572 // TODO Send to system too?
6573 mContext.sendBroadcastAsUser(
6574 new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED)
6575 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND),
6576 UserHandle.of(userId));
6578 mInjector.binderRestoreCallingIdentity(ident);
6580 mDeviceAdminServiceController.startServiceForOwner(
6581 admin.getPackageName(), userId, "set-device-owner");
6583 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
6589 public boolean hasDeviceOwner() {
6590 enforceDeviceOwnerOrManageUsers();
6591 return mOwners.hasDeviceOwner();
6594 boolean isDeviceOwner(ActiveAdmin admin) {
6595 return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
6598 public boolean isDeviceOwner(ComponentName who, int userId) {
6599 synchronized (this) {
6600 return mOwners.hasDeviceOwner()
6601 && mOwners.getDeviceOwnerUserId() == userId
6602 && mOwners.getDeviceOwnerComponent().equals(who);
6606 private boolean isDeviceOwnerPackage(String packageName, int userId) {
6607 synchronized (this) {
6608 return mOwners.hasDeviceOwner()
6609 && mOwners.getDeviceOwnerUserId() == userId
6610 && mOwners.getDeviceOwnerPackageName().equals(packageName);
6614 private boolean isProfileOwnerPackage(String packageName, int userId) {
6615 synchronized (this) {
6616 return mOwners.hasProfileOwner(userId)
6617 && mOwners.getProfileOwnerPackage(userId).equals(packageName);
6621 public boolean isProfileOwner(ComponentName who, int userId) {
6622 final ComponentName profileOwner = getProfileOwner(userId);
6623 return who != null && who.equals(profileOwner);
6627 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
6631 if (!callingUserOnly) {
6632 enforceManageUsers();
6634 synchronized (this) {
6635 if (!mOwners.hasDeviceOwner()) {
6638 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
6639 mOwners.getDeviceOwnerUserId()) {
6642 return mOwners.getDeviceOwnerComponent();
6647 public int getDeviceOwnerUserId() {
6649 return UserHandle.USER_NULL;
6651 enforceManageUsers();
6652 synchronized (this) {
6653 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
6658 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
6662 public String getDeviceOwnerName() {
6666 enforceManageUsers();
6667 synchronized (this) {
6668 if (!mOwners.hasDeviceOwner()) {
6671 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
6672 // Should setDeviceOwner/ProfileOwner still take a name?
6673 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
6674 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
6678 /** Returns the active device owner or {@code null} if there is no device owner. */
6680 ActiveAdmin getDeviceOwnerAdminLocked() {
6681 ComponentName component = mOwners.getDeviceOwnerComponent();
6682 if (component == null) {
6686 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
6687 final int n = policy.mAdminList.size();
6688 for (int i = 0; i < n; i++) {
6689 ActiveAdmin admin = policy.mAdminList.get(i);
6690 if (component.equals(admin.info.getComponent())) {
6694 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
6699 public void clearDeviceOwner(String packageName) {
6700 Preconditions.checkNotNull(packageName, "packageName is null");
6701 final int callingUid = mInjector.binderGetCallingUid();
6703 int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName,
6704 UserHandle.getUserId(callingUid));
6705 if (uid != callingUid) {
6706 throw new SecurityException("Invalid packageName");
6708 } catch (NameNotFoundException e) {
6709 throw new SecurityException(e);
6711 synchronized (this) {
6712 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6713 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6714 if (!mOwners.hasDeviceOwner()
6715 || !deviceOwnerComponent.getPackageName().equals(packageName)
6716 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
6717 throw new SecurityException(
6718 "clearDeviceOwner can only be called by the device owner");
6720 enforceUserUnlocked(deviceOwnerUserId);
6722 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
6723 long ident = mInjector.binderClearCallingIdentity();
6725 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
6726 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
6727 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
6728 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
6729 mContext.sendBroadcastAsUser(intent, UserHandle.of(deviceOwnerUserId));
6731 mInjector.binderRestoreCallingIdentity(ident);
6733 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
6737 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
6738 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner");
6740 if (admin != null) {
6741 admin.disableCamera = false;
6742 admin.userRestrictions = null;
6743 admin.defaultEnabledRestrictionsAlreadySet.clear();
6744 admin.forceEphemeralUsers = false;
6745 admin.isNetworkLoggingEnabled = false;
6746 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
6748 final DevicePolicyData policyData = getUserData(userId);
6749 policyData.mCurrentInputMethodSet = false;
6750 saveSettingsLocked(userId);
6751 final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM);
6752 systemPolicyData.mLastSecurityLogRetrievalTime = -1;
6753 systemPolicyData.mLastBugReportRequestTime = -1;
6754 systemPolicyData.mLastNetworkLogsRetrievalTime = -1;
6755 saveSettingsLocked(UserHandle.USER_SYSTEM);
6756 clearUserPoliciesLocked(userId);
6758 mOwners.clearDeviceOwner();
6759 mOwners.writeDeviceOwner();
6760 updateDeviceOwnerLocked();
6762 clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId));
6763 mInjector.securityLogSetLoggingEnabledProperty(false);
6764 mSecurityLogMonitor.stop();
6765 setNetworkLoggingActiveInternal(false);
6768 if (mInjector.getIBackupManager() != null) {
6769 // Reactivate backup service.
6770 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6772 } catch (RemoteException e) {
6773 throw new IllegalStateException("Failed reactivating backup service.", e);
6778 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6783 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6784 throw new IllegalArgumentException("Component " + who
6785 + " not installed for userId:" + userHandle);
6787 final boolean hasIncompatibleAccountsOrNonAdb =
6788 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who);
6789 synchronized (this) {
6790 enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb);
6792 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6793 if (admin == null || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6794 throw new IllegalArgumentException("Not active admin: " + who);
6798 // Log profile owner provisioning was started using adb.
6799 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
6802 mOwners.setProfileOwner(who, ownerName, userHandle);
6803 mOwners.writeProfileOwner(userHandle);
6804 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6806 final long id = mInjector.binderClearCallingIdentity();
6808 if (mUserManager.isManagedProfile(userHandle)) {
6809 maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin,
6810 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
6811 ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin,
6812 true /* newOwner */);
6815 mInjector.binderRestoreCallingIdentity(id);
6817 mDeviceAdminServiceController.startServiceForOwner(
6818 who.getPackageName(), userHandle, "set-profile-owner");
6824 public void clearProfileOwner(ComponentName who) {
6828 Preconditions.checkNotNull(who, "ComponentName is null");
6830 final int userId = mInjector.userHandleGetCallingUserId();
6831 enforceNotManagedProfile(userId, "clear profile owner");
6832 enforceUserUnlocked(userId);
6833 synchronized (this) {
6834 // Check if this is the profile owner who is calling
6835 final ActiveAdmin admin =
6836 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6838 final long ident = mInjector.binderClearCallingIdentity();
6840 clearProfileOwnerLocked(admin, userId);
6841 removeActiveAdminLocked(who, userId);
6843 mInjector.binderRestoreCallingIdentity(ident);
6845 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6849 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6850 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner");
6852 if (admin != null) {
6853 admin.disableCamera = false;
6854 admin.userRestrictions = null;
6855 admin.defaultEnabledRestrictionsAlreadySet.clear();
6857 final DevicePolicyData policyData = getUserData(userId);
6858 policyData.mCurrentInputMethodSet = false;
6859 policyData.mOwnerInstalledCaCerts.clear();
6860 saveSettingsLocked(userId);
6861 clearUserPoliciesLocked(userId);
6862 mOwners.removeProfileOwner(userId);
6863 mOwners.writeProfileOwner(userId);
6867 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6868 Preconditions.checkNotNull(who, "ComponentName is null");
6873 synchronized (this) {
6874 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6875 long token = mInjector.binderClearCallingIdentity();
6877 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6879 mInjector.binderRestoreCallingIdentity(token);
6885 public CharSequence getDeviceOwnerLockScreenInfo() {
6886 return mLockPatternUtils.getDeviceOwnerInfo();
6889 private void clearUserPoliciesLocked(int userId) {
6890 // Reset some of the user-specific policies.
6891 final DevicePolicyData policy = getUserData(userId);
6892 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6893 // Clear delegations.
6894 policy.mDelegationMap.clear();
6895 policy.mStatusBarDisabled = false;
6896 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6897 policy.mAffiliationIds.clear();
6898 policy.mLockTaskPackages.clear();
6899 saveSettingsLocked(userId);
6902 mIPackageManager.updatePermissionFlagsForAllApps(
6903 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6904 0 /* flagValues */, userId);
6905 pushUserRestrictions(userId);
6906 } catch (RemoteException re) {
6907 // Shouldn't happen.
6912 public boolean hasUserSetupCompleted() {
6913 return hasUserSetupCompleted(UserHandle.getCallingUserId());
6916 // This checks only if the Setup Wizard has run. Since Wear devices pair before
6917 // completing Setup Wizard, and pairing involves transferring user data, calling
6918 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
6919 private boolean hasUserSetupCompleted(int userHandle) {
6923 return getUserData(userHandle).mUserSetupComplete;
6926 private boolean hasPaired(int userHandle) {
6930 return getUserData(userHandle).mPaired;
6934 public int getUserProvisioningState() {
6936 return DevicePolicyManager.STATE_USER_UNMANAGED;
6938 int userHandle = mInjector.userHandleGetCallingUserId();
6939 return getUserProvisioningState(userHandle);
6942 private int getUserProvisioningState(int userHandle) {
6943 return getUserData(userHandle).mUserProvisioningState;
6947 public void setUserProvisioningState(int newState, int userHandle) {
6952 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6953 && getManagedUserId(userHandle) == -1) {
6954 // No managed device, user or profile, so setting provisioning state makes no sense.
6955 throw new IllegalStateException("Not allowed to change provisioning state unless a "
6956 + "device or profile owner is set.");
6959 synchronized (this) {
6960 boolean transitionCheckNeeded = true;
6962 // Calling identity/permission checks.
6964 // ADB shell can only move directly from un-managed to finalized as part of directly
6965 // setting profile-owner or device-owner.
6966 if (getUserProvisioningState(userHandle) !=
6967 DevicePolicyManager.STATE_USER_UNMANAGED
6968 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6969 throw new IllegalStateException("Not allowed to change provisioning state "
6970 + "unless current provisioning state is unmanaged, and new state is "
6973 transitionCheckNeeded = false;
6975 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6976 enforceCanManageProfileAndDeviceOwners();
6979 final DevicePolicyData policyData = getUserData(userHandle);
6980 if (transitionCheckNeeded) {
6981 // Optional state transition check for non-ADB case.
6982 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6984 policyData.mUserProvisioningState = newState;
6985 saveSettingsLocked(userHandle);
6989 private void checkUserProvisioningStateTransition(int currentState, int newState) {
6990 // Valid transitions for normal use-cases.
6991 switch (currentState) {
6992 case DevicePolicyManager.STATE_USER_UNMANAGED:
6993 // Can move to any state from unmanaged (except itself as an edge case)..
6994 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6998 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6999 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
7000 // Can only move to finalized from these states.
7001 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
7005 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
7006 // Current user has a managed-profile, but current user is not managed, so
7007 // rather than moving to finalized state, go back to unmanaged once
7008 // profile provisioning is complete.
7009 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
7013 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
7014 // Cannot transition out of finalized.
7018 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
7019 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
7020 + "from state [" + currentState + "]");
7024 public void setProfileEnabled(ComponentName who) {
7028 Preconditions.checkNotNull(who, "ComponentName is null");
7029 synchronized (this) {
7030 // Check if this is the profile owner who is calling
7031 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7032 final int userId = UserHandle.getCallingUserId();
7033 enforceManagedProfile(userId, "enable the profile");
7034 // Check if the profile is already enabled.
7035 UserInfo managedProfile = getUserInfo(userId);
7036 if (managedProfile.isEnabled()) {
7038 "setProfileEnabled is called when the profile is already enabled");
7041 long id = mInjector.binderClearCallingIdentity();
7043 mUserManager.setUserEnabled(userId);
7044 UserInfo parent = mUserManager.getProfileParent(userId);
7045 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
7046 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
7047 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
7048 Intent.FLAG_RECEIVER_FOREGROUND);
7049 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
7051 mInjector.binderRestoreCallingIdentity(id);
7057 public void setProfileName(ComponentName who, String profileName) {
7058 Preconditions.checkNotNull(who, "ComponentName is null");
7059 int userId = UserHandle.getCallingUserId();
7060 // Check if this is the profile owner (includes device owner).
7061 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7063 long id = mInjector.binderClearCallingIdentity();
7065 mUserManager.setUserName(userId, profileName);
7067 mInjector.binderRestoreCallingIdentity(id);
7072 public ComponentName getProfileOwner(int userHandle) {
7077 synchronized (this) {
7078 return mOwners.getProfileOwnerComponent(userHandle);
7082 // Returns the active profile owner for this user or null if the current user has no
7085 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
7086 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
7087 if (profileOwner == null) {
7090 DevicePolicyData policy = getUserData(userHandle);
7091 final int n = policy.mAdminList.size();
7092 for (int i = 0; i < n; i++) {
7093 ActiveAdmin admin = policy.mAdminList.get(i);
7094 if (profileOwner.equals(admin.info.getComponent())) {
7102 public String getProfileOwnerName(int userHandle) {
7106 enforceManageUsers();
7107 ComponentName profileOwner = getProfileOwner(userHandle);
7108 if (profileOwner == null) {
7111 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
7115 * Canonical name for a given package.
7117 private String getApplicationLabel(String packageName, int userHandle) {
7118 long token = mInjector.binderClearCallingIdentity();
7120 final Context userContext;
7122 UserHandle handle = new UserHandle(userHandle);
7123 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
7124 } catch (PackageManager.NameNotFoundException nnfe) {
7125 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
7128 ApplicationInfo appInfo = userContext.getApplicationInfo();
7129 CharSequence result = null;
7130 if (appInfo != null) {
7131 PackageManager pm = userContext.getPackageManager();
7132 result = pm.getApplicationLabel(appInfo);
7134 return result != null ? result.toString() : null;
7136 mInjector.binderRestoreCallingIdentity(token);
7141 * Calls wtfStack() if called with the DPMS lock held.
7143 private void wtfIfInLock() {
7144 if (Thread.holdsLock(this)) {
7145 Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
7150 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7152 * The profile owner can only be set before the user setup phase has completed,
7155 * - adb unless hasIncompatibleAccountsOrNonAdb is true.
7157 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle,
7158 boolean hasIncompatibleAccountsOrNonAdb) {
7159 UserInfo info = getUserInfo(userHandle);
7161 // User doesn't exist.
7162 throw new IllegalArgumentException(
7163 "Attempted to set profile owner for invalid userId: " + userHandle);
7165 if (info.isGuest()) {
7166 throw new IllegalStateException("Cannot set a profile owner on a guest");
7168 if (mOwners.hasProfileOwner(userHandle)) {
7169 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
7170 + "is already set.");
7172 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
7173 throw new IllegalStateException("Trying to set the profile owner, but the user "
7174 + "already has a device owner.");
7177 if ((mIsWatch || hasUserSetupCompleted(userHandle))
7178 && hasIncompatibleAccountsOrNonAdb) {
7179 throw new IllegalStateException("Not allowed to set the profile owner because "
7180 + "there are already some accounts on the profile");
7184 enforceCanManageProfileAndDeviceOwners();
7185 if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
7186 throw new IllegalStateException("Cannot set the profile owner on a user which is "
7187 + "already set-up");
7192 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7195 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId,
7196 boolean hasIncompatibleAccountsOrNonAdb) {
7198 enforceCanManageProfileAndDeviceOwners();
7201 final int code = checkDeviceOwnerProvisioningPreConditionLocked(
7202 owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb);
7206 case CODE_HAS_DEVICE_OWNER:
7207 throw new IllegalStateException(
7208 "Trying to set the device owner, but device owner is already set.");
7209 case CODE_USER_HAS_PROFILE_OWNER:
7210 throw new IllegalStateException("Trying to set the device owner, but the user "
7211 + "already has a profile owner.");
7212 case CODE_USER_NOT_RUNNING:
7213 throw new IllegalStateException("User not running: " + userId);
7214 case CODE_NOT_SYSTEM_USER:
7215 throw new IllegalStateException("User is not system user");
7216 case CODE_USER_SETUP_COMPLETED:
7217 throw new IllegalStateException(
7218 "Cannot set the device owner if the device is already set-up");
7219 case CODE_NONSYSTEM_USER_EXISTS:
7220 throw new IllegalStateException("Not allowed to set the device owner because there "
7221 + "are already several users on the device");
7222 case CODE_ACCOUNTS_NOT_EMPTY:
7223 throw new IllegalStateException("Not allowed to set the device owner because there "
7224 + "are already some accounts on the device");
7225 case CODE_HAS_PAIRED:
7226 throw new IllegalStateException("Not allowed to set the device owner because this "
7227 + "device has already paired");
7229 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code);
7233 private void enforceUserUnlocked(int userId) {
7234 // Since we're doing this operation on behalf of an app, we only
7235 // want to use the actual "unlocked" state.
7236 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
7237 "User must be running and unlocked");
7240 private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
7242 enforceUserUnlocked(getProfileParentId(userId));
7244 enforceUserUnlocked(userId);
7248 private void enforceManageUsers() {
7249 final int callingUid = mInjector.binderGetCallingUid();
7250 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
7251 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7255 private void enforceFullCrossUsersPermission(int userHandle) {
7256 enforceSystemUserOrPermissionIfCrossUser(userHandle,
7257 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
7260 private void enforceCrossUsersPermission(int userHandle) {
7261 enforceSystemUserOrPermissionIfCrossUser(userHandle,
7262 android.Manifest.permission.INTERACT_ACROSS_USERS);
7265 private void enforceSystemUserOrPermission(String permission) {
7266 if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) {
7267 mContext.enforceCallingOrSelfPermission(permission,
7268 "Must be system or have " + permission + " permission");
7272 private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) {
7273 if (userHandle < 0) {
7274 throw new IllegalArgumentException("Invalid userId " + userHandle);
7276 if (userHandle == mInjector.userHandleGetCallingUserId()) {
7279 enforceSystemUserOrPermission(permission);
7282 private void enforceManagedProfile(int userHandle, String message) {
7283 if(!isManagedProfile(userHandle)) {
7284 throw new SecurityException("You can not " + message + " outside a managed profile.");
7288 private void enforceNotManagedProfile(int userHandle, String message) {
7289 if(isManagedProfile(userHandle)) {
7290 throw new SecurityException("You can not " + message + " for a managed profile.");
7294 private void enforceDeviceOwnerOrManageUsers() {
7295 synchronized (this) {
7296 if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7297 mInjector.binderGetCallingUid()) != null) {
7301 enforceManageUsers();
7304 private void enforceProfileOwnerOrSystemUser() {
7305 synchronized (this) {
7306 if (getActiveAdminWithPolicyForUidLocked(null,
7307 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7312 Preconditions.checkState(isCallerWithSystemUid(),
7313 "Only profile owner, device owner and system may call this method.");
7316 private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) {
7317 if (userId == mInjector.userHandleGetCallingUserId()) {
7318 synchronized (this) {
7319 if (getActiveAdminWithPolicyForUidLocked(null,
7320 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7322 // Device Owner/Profile Owner may access the user it runs on.
7327 // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required.
7328 enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
7331 private void ensureCallerPackage(@Nullable String packageName) {
7332 if (packageName == null) {
7333 Preconditions.checkState(isCallerWithSystemUid(),
7334 "Only caller can omit package name");
7336 final int callingUid = mInjector.binderGetCallingUid();
7337 final int userId = mInjector.userHandleGetCallingUserId();
7339 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
7340 packageName, 0, userId);
7341 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
7342 } catch (RemoteException e) {
7348 private boolean isCallerWithSystemUid() {
7349 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
7352 protected int getProfileParentId(int userHandle) {
7353 final long ident = mInjector.binderClearCallingIdentity();
7355 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
7356 return parentUser != null ? parentUser.id : userHandle;
7358 mInjector.binderRestoreCallingIdentity(ident);
7362 private int getCredentialOwner(int userHandle, boolean parent) {
7363 final long ident = mInjector.binderClearCallingIdentity();
7366 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
7367 if (parentProfile != null) {
7368 userHandle = parentProfile.id;
7371 return mUserManager.getCredentialOwnerProfile(userHandle);
7373 mInjector.binderRestoreCallingIdentity(ident);
7377 private boolean isManagedProfile(int userHandle) {
7378 final UserInfo user = getUserInfo(userHandle);
7379 return user != null && user.isManagedProfile();
7382 private void enableIfNecessary(String packageName, int userId) {
7384 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
7385 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId);
7386 if (ai.enabledSetting
7387 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
7388 mIPackageManager.setApplicationEnabledSetting(packageName,
7389 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
7390 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
7392 } catch (RemoteException e) {
7397 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7398 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
7400 synchronized (this) {
7401 pw.println("Current Device Policy Manager state:");
7403 mOwners.dump(" ", pw);
7404 mDeviceAdminServiceController.dump(" ", pw);
7405 int userCount = mUserData.size();
7406 for (int u = 0; u < userCount; u++) {
7407 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
7409 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
7410 + ", provisioningState: " + policy.mUserProvisioningState + "):");
7411 final int N = policy.mAdminList.size();
7412 for (int i=0; i<N; i++) {
7413 ActiveAdmin ap = policy.mAdminList.get(i);
7415 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
7420 if (!policy.mRemovingAdmins.isEmpty()) {
7421 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
7422 + policy.mRemovingAdmins);
7426 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
7429 mConstants.dump(" ", pw);
7431 pw.println(" Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
7435 private String getEncryptionStatusName(int encryptionStatus) {
7436 switch (encryptionStatus) {
7437 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
7439 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
7440 return "block default key";
7441 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
7443 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
7445 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
7446 return "unsupported";
7447 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
7448 return "activating";
7455 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
7456 ComponentName activity) {
7457 Preconditions.checkNotNull(who, "ComponentName is null");
7458 final int userHandle = UserHandle.getCallingUserId();
7459 synchronized (this) {
7460 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7462 long id = mInjector.binderClearCallingIdentity();
7464 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
7465 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
7466 } catch (RemoteException re) {
7469 mInjector.binderRestoreCallingIdentity(id);
7475 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
7476 Preconditions.checkNotNull(who, "ComponentName is null");
7477 final int userHandle = UserHandle.getCallingUserId();
7478 synchronized (this) {
7479 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7481 long id = mInjector.binderClearCallingIdentity();
7483 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
7484 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
7485 } catch (RemoteException re) {
7488 mInjector.binderRestoreCallingIdentity(id);
7494 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
7495 String packageName) {
7497 setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
7498 } catch (IllegalArgumentException e) {
7505 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
7506 final List<String> delegatePackages = getDelegatePackages(admin,
7507 DELEGATION_APP_RESTRICTIONS);
7508 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
7512 public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
7513 return isCallerDelegate(callerPackage, DELEGATION_APP_RESTRICTIONS);
7517 public void setApplicationRestrictions(ComponentName who, String callerPackage,
7518 String packageName, Bundle settings) {
7519 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
7520 DELEGATION_APP_RESTRICTIONS);
7522 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7523 final long id = mInjector.binderClearCallingIdentity();
7525 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
7527 mInjector.binderRestoreCallingIdentity(id);
7532 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
7533 PersistableBundle args, boolean parent) {
7537 Preconditions.checkNotNull(admin, "admin is null");
7538 Preconditions.checkNotNull(agent, "agent is null");
7539 final int userHandle = UserHandle.getCallingUserId();
7540 synchronized (this) {
7541 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
7542 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
7543 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
7544 saveSettingsLocked(userHandle);
7549 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
7550 ComponentName agent, int userHandle, boolean parent) {
7554 Preconditions.checkNotNull(agent, "agent null");
7555 enforceFullCrossUsersPermission(userHandle);
7557 synchronized (this) {
7558 final String componentName = agent.flattenToString();
7559 if (admin != null) {
7560 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
7561 if (ap == null) return null;
7562 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
7563 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
7564 List<PersistableBundle> result = new ArrayList<>();
7565 result.add(trustAgentInfo.options);
7569 // Return strictest policy for this user and profiles that are visible from this user.
7570 List<PersistableBundle> result = null;
7571 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
7572 // of the options. If any admin doesn't have options, discard options for the rest
7574 List<ActiveAdmin> admins =
7575 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
7576 boolean allAdminsHaveOptions = true;
7577 final int N = admins.size();
7578 for (int i = 0; i < N; i++) {
7579 final ActiveAdmin active = admins.get(i);
7581 final boolean disablesTrust = (active.disabledKeyguardFeatures
7582 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
7583 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
7584 if (info != null && info.options != null && !info.options.isEmpty()) {
7585 if (disablesTrust) {
7586 if (result == null) {
7587 result = new ArrayList<>();
7589 result.add(info.options);
7591 Log.w(LOG_TAG, "Ignoring admin " + active.info
7592 + " because it has trust options but doesn't declare "
7593 + "KEYGUARD_DISABLE_TRUST_AGENTS");
7595 } else if (disablesTrust) {
7596 allAdminsHaveOptions = false;
7600 return allAdminsHaveOptions ? result : null;
7605 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
7606 Preconditions.checkNotNull(who, "ComponentName is null");
7607 synchronized (this) {
7608 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7610 int userHandle = UserHandle.getCallingUserId();
7611 DevicePolicyData userData = getUserData(userHandle);
7612 userData.mRestrictionsProvider = permissionProvider;
7613 saveSettingsLocked(userHandle);
7618 public ComponentName getRestrictionsProvider(int userHandle) {
7619 synchronized (this) {
7620 if (!isCallerWithSystemUid()) {
7621 throw new SecurityException("Only the system can query the permission provider");
7623 DevicePolicyData userData = getUserData(userHandle);
7624 return userData != null ? userData.mRestrictionsProvider : null;
7629 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
7630 Preconditions.checkNotNull(who, "ComponentName is null");
7631 int callingUserId = UserHandle.getCallingUserId();
7632 synchronized (this) {
7633 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7635 long id = mInjector.binderClearCallingIdentity();
7637 UserInfo parent = mUserManager.getProfileParent(callingUserId);
7638 if (parent == null) {
7639 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
7643 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
7644 mIPackageManager.addCrossProfileIntentFilter(
7645 filter, who.getPackageName(), callingUserId, parent.id, 0);
7647 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
7648 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
7649 parent.id, callingUserId, 0);
7651 } catch (RemoteException re) {
7654 mInjector.binderRestoreCallingIdentity(id);
7660 public void clearCrossProfileIntentFilters(ComponentName who) {
7661 Preconditions.checkNotNull(who, "ComponentName is null");
7662 int callingUserId = UserHandle.getCallingUserId();
7663 synchronized (this) {
7664 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7665 long id = mInjector.binderClearCallingIdentity();
7667 UserInfo parent = mUserManager.getProfileParent(callingUserId);
7668 if (parent == null) {
7669 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
7673 // Removing those that go from the managed profile to the parent.
7674 mIPackageManager.clearCrossProfileIntentFilters(
7675 callingUserId, who.getPackageName());
7676 // And those that go from the parent to the managed profile.
7677 // If we want to support multiple managed profiles, we will have to only remove
7678 // those that have callingUserId as their target.
7679 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
7680 } catch (RemoteException re) {
7683 mInjector.binderRestoreCallingIdentity(id);
7689 * @return true if all packages in enabledPackages are either in the list
7690 * permittedList or are a system app.
7692 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
7693 List<String> permittedList, int userIdToCheck) {
7694 long id = mInjector.binderClearCallingIdentity();
7696 // If we have an enabled packages list for a managed profile the packages
7697 // we should check are installed for the parent user.
7698 UserInfo user = getUserInfo(userIdToCheck);
7699 if (user.isManagedProfile()) {
7700 userIdToCheck = user.profileGroupId;
7703 for (String enabledPackage : enabledPackages) {
7704 boolean systemService = false;
7706 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
7707 enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
7709 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7710 } catch (RemoteException e) {
7711 Log.i(LOG_TAG, "Can't talk to package managed", e);
7713 if (!systemService && !permittedList.contains(enabledPackage)) {
7718 mInjector.binderRestoreCallingIdentity(id);
7723 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
7724 // Not using AccessibilityManager.getInstance because that guesses
7725 // at the user you require based on callingUid and caches for a given
7727 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
7728 IAccessibilityManager service = iBinder == null
7729 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
7730 return new AccessibilityManager(mContext, service, userId);
7734 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
7738 Preconditions.checkNotNull(who, "ComponentName is null");
7740 if (packageList != null) {
7741 int userId = UserHandle.getCallingUserId();
7742 List<AccessibilityServiceInfo> enabledServices = null;
7743 long id = mInjector.binderClearCallingIdentity();
7745 UserInfo user = getUserInfo(userId);
7746 if (user.isManagedProfile()) {
7747 userId = user.profileGroupId;
7749 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
7750 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
7751 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
7753 mInjector.binderRestoreCallingIdentity(id);
7756 if (enabledServices != null) {
7757 List<String> enabledPackages = new ArrayList<String>();
7758 for (AccessibilityServiceInfo service : enabledServices) {
7759 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
7761 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7763 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
7764 + "because it contains already enabled accesibility services.");
7770 synchronized (this) {
7771 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7772 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7773 admin.permittedAccessiblityServices = packageList;
7774 saveSettingsLocked(UserHandle.getCallingUserId());
7780 public List getPermittedAccessibilityServices(ComponentName who) {
7784 Preconditions.checkNotNull(who, "ComponentName is null");
7786 synchronized (this) {
7787 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7788 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7789 return admin.permittedAccessiblityServices;
7794 public List getPermittedAccessibilityServicesForUser(int userId) {
7798 synchronized (this) {
7799 List<String> result = null;
7800 // If we have multiple profiles we return the intersection of the
7801 // permitted lists. This can happen in cases where we have a device
7802 // and profile owner.
7803 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7804 for (int profileId : profileIds) {
7805 // Just loop though all admins, only device or profiles
7806 // owners can have permitted lists set.
7807 DevicePolicyData policy = getUserDataUnchecked(profileId);
7808 final int N = policy.mAdminList.size();
7809 for (int j = 0; j < N; j++) {
7810 ActiveAdmin admin = policy.mAdminList.get(j);
7811 List<String> fromAdmin = admin.permittedAccessiblityServices;
7812 if (fromAdmin != null) {
7813 if (result == null) {
7814 result = new ArrayList<>(fromAdmin);
7816 result.retainAll(fromAdmin);
7822 // If we have a permitted list add all system accessibility services.
7823 if (result != null) {
7824 long id = mInjector.binderClearCallingIdentity();
7826 UserInfo user = getUserInfo(userId);
7827 if (user.isManagedProfile()) {
7828 userId = user.profileGroupId;
7830 AccessibilityManager accessibilityManager =
7831 getAccessibilityManagerForUser(userId);
7832 List<AccessibilityServiceInfo> installedServices =
7833 accessibilityManager.getInstalledAccessibilityServiceList();
7835 if (installedServices != null) {
7836 for (AccessibilityServiceInfo service : installedServices) {
7837 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7838 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7839 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7840 result.add(serviceInfo.packageName);
7845 mInjector.binderRestoreCallingIdentity(id);
7854 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7859 Preconditions.checkNotNull(who, "ComponentName is null");
7860 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7861 if (!isCallerWithSystemUid()){
7862 throw new SecurityException(
7863 "Only the system can query if an accessibility service is disabled by admin");
7865 synchronized (this) {
7866 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7867 if (admin == null) {
7870 if (admin.permittedAccessiblityServices == null) {
7873 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
7874 admin.permittedAccessiblityServices, userHandle);
7878 private boolean checkCallerIsCurrentUserOrProfile() {
7879 final int callingUserId = UserHandle.getCallingUserId();
7880 final long token = mInjector.binderClearCallingIdentity();
7882 UserInfo currentUser;
7883 UserInfo callingUser = getUserInfo(callingUserId);
7885 currentUser = mInjector.getIActivityManager().getCurrentUser();
7886 } catch (RemoteException e) {
7887 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7891 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7892 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7893 + "of a user that isn't the foreground user.");
7896 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7897 Slog.e(LOG_TAG, "Cannot set permitted input methods "
7898 + "of a user that isn't the foreground user.");
7902 mInjector.binderRestoreCallingIdentity(token);
7908 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7912 Preconditions.checkNotNull(who, "ComponentName is null");
7914 // TODO When InputMethodManager supports per user calls remove
7915 // this restriction.
7916 if (!checkCallerIsCurrentUserOrProfile()) {
7920 final int callingUserId = mInjector.userHandleGetCallingUserId();
7921 if (packageList != null) {
7922 // InputMethodManager fetches input methods for current user.
7923 // So this can only be set when calling user is the current user
7924 // or parent is current user in case of managed profiles.
7925 InputMethodManager inputMethodManager =
7926 mContext.getSystemService(InputMethodManager.class);
7927 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7929 if (enabledImes != null) {
7930 List<String> enabledPackages = new ArrayList<String>();
7931 for (InputMethodInfo ime : enabledImes) {
7932 enabledPackages.add(ime.getPackageName());
7934 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7936 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7937 + "because it contains already enabled input method.");
7943 synchronized (this) {
7944 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7945 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7946 admin.permittedInputMethods = packageList;
7947 saveSettingsLocked(callingUserId);
7953 public List getPermittedInputMethods(ComponentName who) {
7957 Preconditions.checkNotNull(who, "ComponentName is null");
7959 synchronized (this) {
7960 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7961 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7962 return admin.permittedInputMethods;
7967 public List getPermittedInputMethodsForCurrentUser() {
7968 UserInfo currentUser;
7970 currentUser = mInjector.getIActivityManager().getCurrentUser();
7971 } catch (RemoteException e) {
7972 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7973 // Activity managed is dead, just allow all IMEs
7977 int userId = currentUser.id;
7978 synchronized (this) {
7979 List<String> result = null;
7980 // If we have multiple profiles we return the intersection of the
7981 // permitted lists. This can happen in cases where we have a device
7982 // and profile owner.
7983 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7984 for (int profileId : profileIds) {
7985 // Just loop though all admins, only device or profiles
7986 // owners can have permitted lists set.
7987 DevicePolicyData policy = getUserDataUnchecked(profileId);
7988 final int N = policy.mAdminList.size();
7989 for (int j = 0; j < N; j++) {
7990 ActiveAdmin admin = policy.mAdminList.get(j);
7991 List<String> fromAdmin = admin.permittedInputMethods;
7992 if (fromAdmin != null) {
7993 if (result == null) {
7994 result = new ArrayList<String>(fromAdmin);
7996 result.retainAll(fromAdmin);
8002 // If we have a permitted list add all system input methods.
8003 if (result != null) {
8004 InputMethodManager inputMethodManager =
8005 mContext.getSystemService(InputMethodManager.class);
8006 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
8007 long id = mInjector.binderClearCallingIdentity();
8010 for (InputMethodInfo ime : imes) {
8011 ServiceInfo serviceInfo = ime.getServiceInfo();
8012 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
8013 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8014 result.add(serviceInfo.packageName);
8019 mInjector.binderRestoreCallingIdentity(id);
8027 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
8032 Preconditions.checkNotNull(who, "ComponentName is null");
8033 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
8034 if (!isCallerWithSystemUid()) {
8035 throw new SecurityException(
8036 "Only the system can query if an input method is disabled by admin");
8038 synchronized (this) {
8039 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8040 if (admin == null) {
8043 if (admin.permittedInputMethods == null) {
8046 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8047 admin.permittedInputMethods, userHandle);
8052 public boolean setPermittedCrossProfileNotificationListeners(
8053 ComponentName who, List<String> packageList) {
8057 Preconditions.checkNotNull(who, "ComponentName is null");
8059 final int callingUserId = mInjector.userHandleGetCallingUserId();
8060 if (!isManagedProfile(callingUserId)) {
8064 synchronized (this) {
8065 ActiveAdmin admin = getActiveAdminForCallerLocked(
8066 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8067 admin.permittedNotificationListeners = packageList;
8068 saveSettingsLocked(callingUserId);
8074 public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) {
8078 Preconditions.checkNotNull(who, "ComponentName is null");
8080 synchronized (this) {
8081 ActiveAdmin admin = getActiveAdminForCallerLocked(
8082 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8083 return admin.permittedNotificationListeners;
8088 public boolean isNotificationListenerServicePermitted(String packageName, int userId) {
8093 Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty");
8094 if (!isCallerWithSystemUid()) {
8095 throw new SecurityException(
8096 "Only the system can query if a notification listener service is permitted");
8098 synchronized (this) {
8099 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
8100 if (profileOwner == null || profileOwner.permittedNotificationListeners == null) {
8103 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8104 profileOwner.permittedNotificationListeners, userId);
8110 private void sendAdminEnabledBroadcastLocked(int userHandle) {
8111 DevicePolicyData policyData = getUserData(userHandle);
8112 if (policyData.mAdminBroadcastPending) {
8113 // Send the initialization data to profile owner and delete the data
8114 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
8115 if (admin != null) {
8116 PersistableBundle initBundle = policyData.mInitBundle;
8117 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
8118 initBundle == null ? null : new Bundle(initBundle), null);
8120 policyData.mInitBundle = null;
8121 policyData.mAdminBroadcastPending = false;
8122 saveSettingsLocked(userHandle);
8127 public UserHandle createAndManageUser(ComponentName admin, String name,
8128 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
8129 Preconditions.checkNotNull(admin, "admin is null");
8130 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
8131 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
8132 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
8133 + admin + " are not in the same package");
8135 // Only allow the system user to use this method
8136 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
8137 throw new SecurityException("createAndManageUser was called from non-system user");
8139 final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0;
8140 final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0
8141 && UserManager.isDeviceInDemoMode(mContext);
8142 if (ephemeral && !mInjector.userManagerIsSplitSystemUser() && !demo) {
8143 throw new IllegalArgumentException(
8144 "Ephemeral users are only supported on systems with a split system user.");
8147 UserHandle user = null;
8148 synchronized (this) {
8149 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8151 final long id = mInjector.binderClearCallingIdentity();
8153 int userInfoFlags = 0;
8155 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
8158 userInfoFlags |= UserInfo.FLAG_DEMO;
8160 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
8162 if (userInfo != null) {
8163 user = userInfo.getUserHandle();
8166 mInjector.binderRestoreCallingIdentity(id);
8173 final long id = mInjector.binderClearCallingIdentity();
8175 final String adminPkg = admin.getPackageName();
8177 final int userHandle = user.getIdentifier();
8179 // Install the profile owner if not present.
8180 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
8181 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle,
8182 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8184 } catch (RemoteException e) {
8185 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
8186 + "removing created user", e);
8187 mUserManager.removeUser(user.getIdentifier());
8191 setActiveAdmin(profileOwner, true, userHandle);
8192 // User is not started yet, the broadcast by setActiveAdmin will not be received.
8193 // So we store adminExtras for broadcasting when the user starts for first time.
8194 synchronized(this) {
8195 DevicePolicyData policyData = getUserData(userHandle);
8196 policyData.mInitBundle = adminExtras;
8197 policyData.mAdminBroadcastPending = true;
8198 saveSettingsLocked(userHandle);
8200 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
8201 setProfileOwner(profileOwner, ownerName, userHandle);
8203 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
8204 Settings.Secure.putIntForUser(mContext.getContentResolver(),
8205 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
8210 mInjector.binderRestoreCallingIdentity(id);
8215 public boolean removeUser(ComponentName who, UserHandle userHandle) {
8216 Preconditions.checkNotNull(who, "ComponentName is null");
8217 synchronized (this) {
8218 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8221 final int callingUserId = mInjector.userHandleGetCallingUserId();
8222 final long id = mInjector.binderClearCallingIdentity();
8224 String restriction = isManagedProfile(userHandle.getIdentifier())
8225 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
8226 : UserManager.DISALLOW_REMOVE_USER;
8227 if (isAdminAffectedByRestriction(who, restriction, callingUserId)) {
8228 Log.w(LOG_TAG, "The device owner cannot remove a user because "
8229 + restriction + " is enabled, and was not set by the device owner");
8232 return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
8234 mInjector.binderRestoreCallingIdentity(id);
8238 private boolean isAdminAffectedByRestriction(
8239 ComponentName admin, String userRestriction, int userId) {
8240 switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
8241 case UserManager.RESTRICTION_NOT_SET:
8243 case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
8244 return !isDeviceOwner(admin, userId);
8245 case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
8246 return !isProfileOwner(admin, userId);
8253 public boolean switchUser(ComponentName who, UserHandle userHandle) {
8254 Preconditions.checkNotNull(who, "ComponentName is null");
8255 synchronized (this) {
8256 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8258 long id = mInjector.binderClearCallingIdentity();
8260 int userId = UserHandle.USER_SYSTEM;
8261 if (userHandle != null) {
8262 userId = userHandle.getIdentifier();
8264 return mInjector.getIActivityManager().switchUser(userId);
8265 } catch (RemoteException e) {
8266 Log.e(LOG_TAG, "Couldn't switch user", e);
8269 mInjector.binderRestoreCallingIdentity(id);
8275 public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
8276 String packageName) {
8277 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8278 DELEGATION_APP_RESTRICTIONS);
8280 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
8281 final long id = mInjector.binderClearCallingIdentity();
8283 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
8284 // if no restrictions were saved, mUserManager.getApplicationRestrictions
8285 // returns null, but DPM method should return an empty Bundle as per JavaDoc
8286 return bundle != null ? bundle : Bundle.EMPTY;
8288 mInjector.binderRestoreCallingIdentity(id);
8293 public String[] setPackagesSuspended(ComponentName who, String callerPackage,
8294 String[] packageNames, boolean suspended) {
8295 int callingUserId = UserHandle.getCallingUserId();
8296 synchronized (this) {
8297 // Ensure the caller is a DO/PO or a package access delegate.
8298 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8299 DELEGATION_PACKAGE_ACCESS);
8301 long id = mInjector.binderClearCallingIdentity();
8303 return mIPackageManager.setPackagesSuspendedAsUser(
8304 packageNames, suspended, callingUserId);
8305 } catch (RemoteException re) {
8306 // Shouldn't happen.
8307 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
8309 mInjector.binderRestoreCallingIdentity(id);
8311 return packageNames;
8316 public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
8317 int callingUserId = UserHandle.getCallingUserId();
8318 synchronized (this) {
8319 // Ensure the caller is a DO/PO or a package access delegate.
8320 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8321 DELEGATION_PACKAGE_ACCESS);
8323 long id = mInjector.binderClearCallingIdentity();
8325 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
8326 } catch (RemoteException re) {
8327 // Shouldn't happen.
8328 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
8330 mInjector.binderRestoreCallingIdentity(id);
8337 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
8338 Preconditions.checkNotNull(who, "ComponentName is null");
8339 if (!UserRestrictionsUtils.isValidRestriction(key)) {
8343 final int userHandle = mInjector.userHandleGetCallingUserId();
8344 synchronized (this) {
8345 final ActiveAdmin activeAdmin =
8346 getActiveAdminForCallerLocked(who,
8347 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8348 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
8349 if (isDeviceOwner) {
8350 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
8351 throw new SecurityException("Device owner cannot set user restriction " + key);
8353 } else { // profile owner
8354 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
8355 throw new SecurityException("Profile owner cannot set user restriction " + key);
8359 // Save the restriction to ActiveAdmin.
8360 final Bundle restrictions = activeAdmin.ensureUserRestrictions();
8361 if (enabledFromThisOwner) {
8362 restrictions.putBoolean(key, true);
8364 restrictions.remove(key);
8366 saveUserRestrictionsLocked(userHandle);
8370 private void saveUserRestrictionsLocked(int userId) {
8371 saveSettingsLocked(userId);
8372 pushUserRestrictions(userId);
8373 sendChangedNotification(userId);
8376 private void pushUserRestrictions(int userId) {
8377 synchronized (this) {
8378 final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId);
8379 final Bundle userRestrictions;
8380 // Whether device owner enforces camera restriction.
8381 boolean disallowCameraGlobally = false;
8383 if (isDeviceOwner) {
8384 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
8385 if (deviceOwner == null) {
8386 return; // Shouldn't happen.
8388 userRestrictions = deviceOwner.userRestrictions;
8389 // DO can disable camera globally.
8390 disallowCameraGlobally = deviceOwner.disableCamera;
8392 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
8393 userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null;
8396 // Whether any admin enforces camera restriction.
8397 final int cameraRestrictionScope =
8398 getCameraRestrictionScopeLocked(userId, disallowCameraGlobally);
8400 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions,
8401 isDeviceOwner, cameraRestrictionScope);
8406 * Get the scope of camera restriction for a given user if any.
8408 private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) {
8409 if (disallowCameraGlobally) {
8410 return UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
8411 } else if (getCameraDisabled(
8412 /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) {
8413 return UserManagerInternal.CAMERA_DISABLED_LOCALLY;
8415 return UserManagerInternal.CAMERA_NOT_DISABLED;
8419 public Bundle getUserRestrictions(ComponentName who) {
8423 Preconditions.checkNotNull(who, "ComponentName is null");
8424 synchronized (this) {
8425 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
8426 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8427 return activeAdmin.userRestrictions;
8432 public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
8434 int callingUserId = UserHandle.getCallingUserId();
8435 synchronized (this) {
8436 // Ensure the caller is a DO/PO or a package access delegate.
8437 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8438 DELEGATION_PACKAGE_ACCESS);
8440 long id = mInjector.binderClearCallingIdentity();
8442 return mIPackageManager.setApplicationHiddenSettingAsUser(
8443 packageName, hidden, callingUserId);
8444 } catch (RemoteException re) {
8446 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
8448 mInjector.binderRestoreCallingIdentity(id);
8455 public boolean isApplicationHidden(ComponentName who, String callerPackage,
8456 String packageName) {
8457 int callingUserId = UserHandle.getCallingUserId();
8458 synchronized (this) {
8459 // Ensure the caller is a DO/PO or a package access delegate.
8460 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8461 DELEGATION_PACKAGE_ACCESS);
8463 long id = mInjector.binderClearCallingIdentity();
8465 return mIPackageManager.getApplicationHiddenSettingAsUser(
8466 packageName, callingUserId);
8467 } catch (RemoteException re) {
8469 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
8471 mInjector.binderRestoreCallingIdentity(id);
8478 public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
8479 synchronized (this) {
8480 // Ensure the caller is a DO/PO or an enable system app delegate.
8481 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8482 DELEGATION_ENABLE_SYSTEM_APP);
8484 final boolean isDemo = isCurrentUserDemo();
8486 int userId = UserHandle.getCallingUserId();
8487 long id = mInjector.binderClearCallingIdentity();
8491 Slog.v(LOG_TAG, "installing " + packageName + " for "
8495 int parentUserId = getProfileParentId(userId);
8496 if (!isDemo && !isSystemApp(mIPackageManager, packageName, parentUserId)) {
8497 throw new IllegalArgumentException("Only system apps can be enabled this way.");
8501 mIPackageManager.installExistingPackageAsUser(packageName, userId,
8502 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8504 // Ensure the app is also ENABLED for demo users.
8505 mIPackageManager.setApplicationEnabledSetting(packageName,
8506 PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
8507 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
8509 } catch (RemoteException re) {
8511 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
8513 mInjector.binderRestoreCallingIdentity(id);
8519 public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
8520 synchronized (this) {
8521 // Ensure the caller is a DO/PO or an enable system app delegate.
8522 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8523 DELEGATION_ENABLE_SYSTEM_APP);
8525 int userId = UserHandle.getCallingUserId();
8526 long id = mInjector.binderClearCallingIdentity();
8529 int parentUserId = getProfileParentId(userId);
8530 List<ResolveInfo> activitiesToEnable = mIPackageManager
8531 .queryIntentActivities(intent,
8532 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
8533 PackageManager.MATCH_DIRECT_BOOT_AWARE
8534 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
8539 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
8541 int numberOfAppsInstalled = 0;
8542 if (activitiesToEnable != null) {
8543 for (ResolveInfo info : activitiesToEnable) {
8544 if (info.activityInfo != null) {
8545 String packageName = info.activityInfo.packageName;
8546 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
8547 numberOfAppsInstalled++;
8548 mIPackageManager.installExistingPackageAsUser(packageName, userId,
8549 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8551 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
8557 return numberOfAppsInstalled;
8558 } catch (RemoteException e) {
8560 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
8563 mInjector.binderRestoreCallingIdentity(id);
8568 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
8569 throws RemoteException {
8570 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
8572 if (appInfo == null) {
8573 throw new IllegalArgumentException("The application " + packageName +
8574 " is not present on this device");
8576 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
8580 public void setAccountManagementDisabled(ComponentName who, String accountType,
8585 Preconditions.checkNotNull(who, "ComponentName is null");
8586 synchronized (this) {
8587 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
8588 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8590 ap.accountTypesWithManagementDisabled.add(accountType);
8592 ap.accountTypesWithManagementDisabled.remove(accountType);
8594 saveSettingsLocked(UserHandle.getCallingUserId());
8599 public String[] getAccountTypesWithManagementDisabled() {
8600 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
8604 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
8605 enforceFullCrossUsersPermission(userId);
8609 synchronized (this) {
8610 DevicePolicyData policy = getUserData(userId);
8611 final int N = policy.mAdminList.size();
8612 ArraySet<String> resultSet = new ArraySet<>();
8613 for (int i = 0; i < N; i++) {
8614 ActiveAdmin admin = policy.mAdminList.get(i);
8615 resultSet.addAll(admin.accountTypesWithManagementDisabled);
8617 return resultSet.toArray(new String[resultSet.size()]);
8622 public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
8623 boolean uninstallBlocked) {
8624 final int userId = UserHandle.getCallingUserId();
8625 synchronized (this) {
8626 // Ensure the caller is a DO/PO or a block uninstall delegate
8627 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8628 DELEGATION_BLOCK_UNINSTALL);
8630 long id = mInjector.binderClearCallingIdentity();
8632 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
8633 } catch (RemoteException re) {
8634 // Shouldn't happen.
8635 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
8637 mInjector.binderRestoreCallingIdentity(id);
8643 public boolean isUninstallBlocked(ComponentName who, String packageName) {
8644 // This function should return true if and only if the package is blocked by
8645 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
8646 // when the package is a system app, or when it is an active device admin.
8647 final int userId = UserHandle.getCallingUserId();
8649 synchronized (this) {
8651 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8654 long id = mInjector.binderClearCallingIdentity();
8656 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
8657 } catch (RemoteException re) {
8658 // Shouldn't happen.
8659 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
8661 mInjector.binderRestoreCallingIdentity(id);
8668 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
8672 Preconditions.checkNotNull(who, "ComponentName is null");
8673 synchronized (this) {
8674 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8675 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8676 if (admin.disableCallerId != disabled) {
8677 admin.disableCallerId = disabled;
8678 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
8684 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
8688 Preconditions.checkNotNull(who, "ComponentName is null");
8689 synchronized (this) {
8690 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8691 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8692 return admin.disableCallerId;
8697 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
8698 enforceCrossUsersPermission(userId);
8699 synchronized (this) {
8700 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8701 return (admin != null) ? admin.disableCallerId : false;
8706 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
8710 Preconditions.checkNotNull(who, "ComponentName is null");
8711 synchronized (this) {
8712 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8713 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8714 if (admin.disableContactsSearch != disabled) {
8715 admin.disableContactsSearch = disabled;
8716 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
8722 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
8726 Preconditions.checkNotNull(who, "ComponentName is null");
8727 synchronized (this) {
8728 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8729 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8730 return admin.disableContactsSearch;
8735 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
8736 enforceCrossUsersPermission(userId);
8737 synchronized (this) {
8738 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8739 return (admin != null) ? admin.disableContactsSearch : false;
8744 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
8745 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
8746 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
8747 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
8748 final int callingUserId = UserHandle.getCallingUserId();
8750 final long ident = mInjector.binderClearCallingIdentity();
8752 synchronized (this) {
8753 final int managedUserId = getManagedUserId(callingUserId);
8754 if (managedUserId < 0) {
8757 if (isCrossProfileQuickContactDisabled(managedUserId)) {
8760 "Cross-profile contacts access disabled for user " + managedUserId);
8764 ContactsInternal.startQuickContactWithErrorToastForUser(
8765 mContext, intent, new UserHandle(managedUserId));
8768 mInjector.binderRestoreCallingIdentity(ident);
8773 * @return true if cross-profile QuickContact is disabled
8775 private boolean isCrossProfileQuickContactDisabled(int userId) {
8776 return getCrossProfileCallerIdDisabledForUser(userId)
8777 && getCrossProfileContactsSearchDisabledForUser(userId);
8781 * @return the user ID of the managed user that is linked to the current user, if any.
8784 public int getManagedUserId(int callingUserId) {
8786 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
8789 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
8790 if (ui.id == callingUserId || !ui.isManagedProfile()) {
8791 continue; // Caller user self, or not a managed profile. Skip.
8794 Log.v(LOG_TAG, "Managed user=" + ui.id);
8799 Log.v(LOG_TAG, "Managed user not found.");
8805 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
8809 Preconditions.checkNotNull(who, "ComponentName is null");
8810 synchronized (this) {
8811 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8812 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8813 if (admin.disableBluetoothContactSharing != disabled) {
8814 admin.disableBluetoothContactSharing = disabled;
8815 saveSettingsLocked(UserHandle.getCallingUserId());
8821 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
8825 Preconditions.checkNotNull(who, "ComponentName is null");
8826 synchronized (this) {
8827 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8828 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8829 return admin.disableBluetoothContactSharing;
8834 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
8835 // TODO: Should there be a check to make sure this relationship is
8836 // within a profile group?
8837 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
8838 synchronized (this) {
8839 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8840 return (admin != null) ? admin.disableBluetoothContactSharing : false;
8845 public void setLockTaskPackages(ComponentName who, String[] packages)
8846 throws SecurityException {
8847 Preconditions.checkNotNull(who, "ComponentName is null");
8848 Preconditions.checkNotNull(packages, "packages is null");
8850 synchronized (this) {
8851 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8852 final int userHandle = mInjector.userHandleGetCallingUserId();
8853 if (isUserAffiliatedWithDeviceLocked(userHandle)) {
8854 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
8856 throw new SecurityException("Admin " + who +
8857 " is neither the device owner or affiliated user's profile owner.");
8862 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
8863 DevicePolicyData policy = getUserData(userHandle);
8864 policy.mLockTaskPackages = packages;
8866 // Store the settings persistently.
8867 saveSettingsLocked(userHandle);
8868 updateLockTaskPackagesLocked(packages, userHandle);
8871 private void maybeClearLockTaskPackagesLocked() {
8872 final long ident = mInjector.binderClearCallingIdentity();
8874 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
8875 for (int i = 0; i < userInfos.size(); i++) {
8876 int userId = userInfos.get(i).id;
8877 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
8878 if (!lockTaskPackages.isEmpty() &&
8879 !isUserAffiliatedWithDeviceLocked(userId)) {
8881 "User id " + userId + " not affiliated. Clearing lock task packages");
8882 setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
8886 mInjector.binderRestoreCallingIdentity(ident);
8891 public String[] getLockTaskPackages(ComponentName who) {
8892 Preconditions.checkNotNull(who, "ComponentName is null");
8894 final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
8895 synchronized (this) {
8896 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8897 if (!isUserAffiliatedWithDeviceLocked(userHandle)) {
8898 throw new SecurityException("Admin " + who +
8899 " is neither the device owner or affiliated user's profile owner.");
8902 final List<String> packages = getUserData(userHandle).mLockTaskPackages;
8903 return packages.toArray(new String[packages.size()]);
8908 public boolean isLockTaskPermitted(String pkg) {
8909 final int userHandle = mInjector.userHandleGetCallingUserId();
8910 synchronized (this) {
8911 return getUserData(userHandle).mLockTaskPackages.contains(pkg);
8916 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
8917 if (!isCallerWithSystemUid()) {
8918 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
8920 synchronized (this) {
8921 final DevicePolicyData policy = getUserData(userHandle);
8922 Bundle adminExtras = new Bundle();
8923 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
8924 for (ActiveAdmin admin : policy.mAdminList) {
8925 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
8926 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
8927 if (ownsDevice || ownsProfile) {
8929 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
8932 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
8940 public void setGlobalSetting(ComponentName who, String setting, String value) {
8941 Preconditions.checkNotNull(who, "ComponentName is null");
8943 synchronized (this) {
8944 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8946 // Some settings are no supported any more. However we do not want to throw a
8947 // SecurityException to avoid breaking apps.
8948 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
8949 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
8953 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)
8954 && !UserManager.isDeviceInDemoMode(mContext)) {
8955 throw new SecurityException(String.format(
8956 "Permission denial: device owners cannot update %1$s", setting));
8959 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
8960 // ignore if it contradicts an existing policy
8961 long timeMs = getMaximumTimeToLock(
8962 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
8963 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
8968 long id = mInjector.binderClearCallingIdentity();
8970 mInjector.settingsGlobalPutString(setting, value);
8972 mInjector.binderRestoreCallingIdentity(id);
8978 public void setSecureSetting(ComponentName who, String setting, String value) {
8979 Preconditions.checkNotNull(who, "ComponentName is null");
8980 int callingUserId = mInjector.userHandleGetCallingUserId();
8982 synchronized (this) {
8983 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8985 if (isDeviceOwner(who, callingUserId)) {
8986 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)
8987 && !isCurrentUserDemo()) {
8988 throw new SecurityException(String.format(
8989 "Permission denial: Device owners cannot update %1$s", setting));
8991 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) {
8992 throw new SecurityException(String.format(
8993 "Permission denial: Profile owners cannot update %1$s", setting));
8995 if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
8996 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
8997 throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
8998 + " is deprecated. Please use the user restriction "
8999 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " instead.");
9001 if (!mUserManager.isManagedProfile(callingUserId)) {
9002 Slog.e(LOG_TAG, "Ignoring setSecureSetting request for "
9003 + setting + ". User restriction "
9004 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES
9005 + " should be used instead.");
9008 setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
9009 (Integer.parseInt(value) == 0) ? true : false);
9010 } catch (NumberFormatException exc) {
9011 Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
9016 long id = mInjector.binderClearCallingIdentity();
9018 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
9019 final String currentValue = mInjector.settingsSecureGetStringForUser(
9020 Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
9021 if (!TextUtils.equals(currentValue, value)) {
9022 // Tell the content observer that the next change will be due to the owner
9023 // changing the value. There is a small race condition here that we cannot
9024 // avoid: Change notifications are sent asynchronously, so it is possible
9025 // that there are prior notifications queued up before the one we are about
9026 // to trigger. This is a corner case that will have no impact in practice.
9027 mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
9029 getUserData(callingUserId).mCurrentInputMethodSet = true;
9030 saveSettingsLocked(callingUserId);
9032 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
9034 mInjector.binderRestoreCallingIdentity(id);
9040 public void setMasterVolumeMuted(ComponentName who, boolean on) {
9041 Preconditions.checkNotNull(who, "ComponentName is null");
9042 synchronized (this) {
9043 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9044 setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on);
9049 public boolean isMasterVolumeMuted(ComponentName who) {
9050 Preconditions.checkNotNull(who, "ComponentName is null");
9051 synchronized (this) {
9052 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9054 AudioManager audioManager =
9055 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
9056 return audioManager.isMasterMute();
9061 public void setUserIcon(ComponentName who, Bitmap icon) {
9062 synchronized (this) {
9063 Preconditions.checkNotNull(who, "ComponentName is null");
9064 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9066 int userId = UserHandle.getCallingUserId();
9067 long id = mInjector.binderClearCallingIdentity();
9069 mUserManagerInternal.setUserIcon(userId, icon);
9071 mInjector.binderRestoreCallingIdentity(id);
9077 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
9078 Preconditions.checkNotNull(who, "ComponentName is null");
9079 synchronized (this) {
9080 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9082 final int userId = UserHandle.getCallingUserId();
9084 long ident = mInjector.binderClearCallingIdentity();
9086 // disallow disabling the keyguard if a password is currently set
9087 if (disabled && mLockPatternUtils.isSecure(userId)) {
9090 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
9092 mInjector.binderRestoreCallingIdentity(ident);
9098 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
9099 int userId = UserHandle.getCallingUserId();
9100 synchronized (this) {
9101 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9102 DevicePolicyData policy = getUserData(userId);
9103 if (policy.mStatusBarDisabled != disabled) {
9104 if (!setStatusBarDisabledInternal(disabled, userId)) {
9107 policy.mStatusBarDisabled = disabled;
9108 saveSettingsLocked(userId);
9114 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
9115 long ident = mInjector.binderClearCallingIdentity();
9117 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
9118 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
9119 if (statusBarService != null) {
9120 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
9121 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
9122 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
9123 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
9126 } catch (RemoteException e) {
9127 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
9129 mInjector.binderRestoreCallingIdentity(ident);
9135 * We need to update the internal state of whether a user has completed setup or a
9136 * device has paired once. After that, we ignore any changes that reset the
9137 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
9138 * as we don't trust any apps that might try to reset them.
9140 * Unfortunately, we don't know which user's setup state was changed, so we write all of
9143 void updateUserSetupCompleteAndPaired() {
9144 List<UserInfo> users = mUserManager.getUsers(true);
9145 final int N = users.size();
9146 for (int i = 0; i < N; i++) {
9147 int userHandle = users.get(i).id;
9148 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
9150 DevicePolicyData policy = getUserData(userHandle);
9151 if (!policy.mUserSetupComplete) {
9152 policy.mUserSetupComplete = true;
9153 synchronized (this) {
9154 saveSettingsLocked(userHandle);
9158 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
9160 DevicePolicyData policy = getUserData(userHandle);
9161 if (!policy.mPaired) {
9162 policy.mPaired = true;
9163 synchronized (this) {
9164 saveSettingsLocked(userHandle);
9171 private class SetupContentObserver extends ContentObserver {
9172 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
9173 Settings.Secure.USER_SETUP_COMPLETE);
9174 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
9175 Settings.Global.DEVICE_PROVISIONED);
9176 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
9177 private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
9178 Settings.Secure.DEFAULT_INPUT_METHOD);
9180 @GuardedBy("DevicePolicyManagerService.this")
9181 private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();
9183 public SetupContentObserver(Handler handler) {
9188 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
9189 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
9191 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
9193 mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
9196 private void addPendingChangeByOwnerLocked(int userId) {
9197 mUserIdsWithPendingChangesByOwner.add(userId);
9201 public void onChange(boolean selfChange, Uri uri, int userId) {
9202 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
9203 updateUserSetupCompleteAndPaired();
9204 } else if (mDeviceProvisioned.equals(uri)) {
9205 synchronized (DevicePolicyManagerService.this) {
9206 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
9207 // is delayed until device is marked as provisioned.
9208 setDeviceOwnerSystemPropertyLocked();
9210 } else if (mDefaultImeChanged.equals(uri)) {
9211 synchronized (DevicePolicyManagerService.this) {
9212 if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
9213 // This change notification was triggered by the owner changing the current
9215 mUserIdsWithPendingChangesByOwner.remove(userId);
9217 // This change notification was triggered by the user manually changing the
9219 getUserData(userId).mCurrentInputMethodSet = false;
9220 saveSettingsLocked(userId);
9228 final class LocalService extends DevicePolicyManagerInternal {
9229 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
9232 public List<String> getCrossProfileWidgetProviders(int profileId) {
9233 synchronized (DevicePolicyManagerService.this) {
9234 if (mOwners == null) {
9235 return Collections.emptyList();
9237 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
9238 if (ownerComponent == null) {
9239 return Collections.emptyList();
9242 DevicePolicyData policy = getUserDataUnchecked(profileId);
9243 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
9245 if (admin == null || admin.crossProfileWidgetProviders == null
9246 || admin.crossProfileWidgetProviders.isEmpty()) {
9247 return Collections.emptyList();
9250 return admin.crossProfileWidgetProviders;
9255 public void addOnCrossProfileWidgetProvidersChangeListener(
9256 OnCrossProfileWidgetProvidersChangeListener listener) {
9257 synchronized (DevicePolicyManagerService.this) {
9258 if (mWidgetProviderListeners == null) {
9259 mWidgetProviderListeners = new ArrayList<>();
9261 if (!mWidgetProviderListeners.contains(listener)) {
9262 mWidgetProviderListeners.add(listener);
9268 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
9269 synchronized(DevicePolicyManagerService.this) {
9270 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
9274 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
9275 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
9276 synchronized (DevicePolicyManagerService.this) {
9277 listeners = new ArrayList<>(mWidgetProviderListeners);
9279 final int listenerCount = listeners.size();
9280 for (int i = 0; i < listenerCount; i++) {
9281 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
9282 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
9287 public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
9288 // This method is called from AM with its lock held, so don't take the DPMS lock.
9291 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
9292 if (profileOwner != null) {
9293 return DevicePolicyManagerService.this
9294 .createShowAdminSupportIntent(profileOwner, userId);
9297 final Pair<Integer, ComponentName> deviceOwner =
9298 mOwners.getDeviceOwnerUserIdAndComponent();
9299 if (deviceOwner != null && deviceOwner.first == userId) {
9300 return DevicePolicyManagerService.this
9301 .createShowAdminSupportIntent(deviceOwner.second, userId);
9304 // We're not specifying the device admin because there isn't one.
9305 if (useDefaultIfNoAdmin) {
9306 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
9312 public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
9314 long ident = mInjector.binderClearCallingIdentity();
9316 source = mUserManager.getUserRestrictionSource(userRestriction,
9317 UserHandle.of(userId));
9319 mInjector.binderRestoreCallingIdentity(ident);
9321 if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) {
9323 * In this case, the user restriction is enforced by the system.
9324 * So we won't show an admin support intent, even if it is also
9325 * enforced by a profile/device owner.
9329 boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0;
9330 boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0;
9331 if (enforcedByDo && enforcedByPo) {
9332 // In this case, we'll show an admin support dialog that does not
9333 // specify the admin.
9334 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
9335 } else if (enforcedByPo) {
9336 final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
9337 if (profileOwner != null) {
9338 return DevicePolicyManagerService.this
9339 .createShowAdminSupportIntent(profileOwner, userId);
9341 // This could happen if another thread has changed the profile owner since we called
9342 // getUserRestrictionSource
9344 } else if (enforcedByDo) {
9345 final Pair<Integer, ComponentName> deviceOwner
9346 = mOwners.getDeviceOwnerUserIdAndComponent();
9347 if (deviceOwner != null) {
9348 return DevicePolicyManagerService.this
9349 .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first);
9351 // This could happen if another thread has changed the device owner since we called
9352 // getUserRestrictionSource
9359 private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
9360 // This method is called with AMS lock held, so don't take DPMS lock
9361 final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
9362 intent.putExtra(Intent.EXTRA_USER_ID, userId);
9363 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
9364 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9369 public Intent createAdminSupportIntent(String restriction) {
9370 Preconditions.checkNotNull(restriction);
9371 final int uid = mInjector.binderGetCallingUid();
9372 final int userId = UserHandle.getUserId(uid);
9373 Intent intent = null;
9374 if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) ||
9375 DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
9376 synchronized(this) {
9377 final DevicePolicyData policy = getUserData(userId);
9378 final int N = policy.mAdminList.size();
9379 for (int i = 0; i < N; i++) {
9380 final ActiveAdmin admin = policy.mAdminList.get(i);
9381 if ((admin.disableCamera &&
9382 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) ||
9383 (admin.disableScreenCapture && DevicePolicyManager
9384 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) {
9385 intent = createShowAdminSupportIntent(admin.info.getComponent(), userId);
9389 // For the camera, a device owner on a different user can disable it globally,
9390 // so we need an additional check.
9392 && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
9393 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
9394 if (admin != null && admin.disableCamera) {
9395 intent = createShowAdminSupportIntent(admin.info.getComponent(),
9396 mOwners.getDeviceOwnerUserId());
9401 // if valid, |restriction| can only be a user restriction
9402 intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction);
9404 if (intent != null) {
9405 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
9411 * Returns true if specified admin is allowed to limit passwords and has a
9412 * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
9414 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
9415 if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
9418 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
9422 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
9423 if (policy != null && !policy.isValid()) {
9424 throw new IllegalArgumentException("Invalid system update policy.");
9426 synchronized (this) {
9427 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9428 if (policy == null) {
9429 mOwners.clearSystemUpdatePolicy();
9431 mOwners.setSystemUpdatePolicy(policy);
9433 mOwners.writeDeviceOwner();
9435 mContext.sendBroadcastAsUser(
9436 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
9441 public SystemUpdatePolicy getSystemUpdatePolicy() {
9442 synchronized (this) {
9443 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
9444 if (policy != null && !policy.isValid()) {
9445 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
9453 * Checks if the caller of the method is the device owner app.
9455 * @param callerUid UID of the caller.
9456 * @return true if the caller is the device owner app
9459 boolean isCallerDeviceOwner(int callerUid) {
9460 synchronized (this) {
9461 if (!mOwners.hasDeviceOwner()) {
9464 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
9467 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
9470 String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid);
9471 for (String pkg : pkgs) {
9472 if (deviceOwnerPackageName.equals(pkg)) {
9476 } catch (RemoteException e) {
9485 public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
9486 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
9487 "Only the system update service can broadcast update information");
9489 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
9490 Slog.w(LOG_TAG, "Only the system update service in the system user " +
9491 "can broadcast update information.");
9495 if (!mOwners.saveSystemUpdateInfo(info)) {
9496 // Pending system update hasn't changed, don't send duplicate notification.
9500 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
9501 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
9502 info == null ? -1 : info.getReceivedTime());
9504 final long ident = mInjector.binderClearCallingIdentity();
9506 synchronized (this) {
9507 // Broadcast to device owner first if there is one.
9508 if (mOwners.hasDeviceOwner()) {
9509 final UserHandle deviceOwnerUser =
9510 UserHandle.of(mOwners.getDeviceOwnerUserId());
9511 intent.setComponent(mOwners.getDeviceOwnerComponent());
9512 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
9515 // Get running users.
9516 final int runningUserIds[];
9518 runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
9519 } catch (RemoteException e) {
9520 // Shouldn't happen.
9521 Log.e(LOG_TAG, "Could not retrieve the list of running users", e);
9524 // Send broadcasts to corresponding profile owners if any.
9525 for (final int userId : runningUserIds) {
9526 synchronized (this) {
9527 final ComponentName profileOwnerPackage =
9528 mOwners.getProfileOwnerComponent(userId);
9529 if (profileOwnerPackage != null) {
9530 intent.setComponent(profileOwnerPackage);
9531 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
9536 mInjector.binderRestoreCallingIdentity(ident);
9541 public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
9542 Preconditions.checkNotNull(admin, "ComponentName is null");
9543 enforceProfileOrDeviceOwner(admin);
9545 return mOwners.getSystemUpdateInfo();
9549 public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy)
9550 throws RemoteException {
9551 int userId = UserHandle.getCallingUserId();
9552 synchronized (this) {
9553 // Ensure the caller is a DO/PO or a permission grant state delegate.
9554 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9555 DELEGATION_PERMISSION_GRANT);
9556 DevicePolicyData userPolicy = getUserData(userId);
9557 if (userPolicy.mPermissionPolicy != policy) {
9558 userPolicy.mPermissionPolicy = policy;
9559 saveSettingsLocked(userId);
9565 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
9566 int userId = UserHandle.getCallingUserId();
9567 synchronized (this) {
9568 DevicePolicyData userPolicy = getUserData(userId);
9569 return userPolicy.mPermissionPolicy;
9574 public boolean setPermissionGrantState(ComponentName admin, String callerPackage,
9575 String packageName, String permission, int grantState) throws RemoteException {
9576 UserHandle user = mInjector.binderGetCallingUserHandle();
9577 synchronized (this) {
9578 // Ensure the caller is a DO/PO or a permission grant state delegate.
9579 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9580 DELEGATION_PERMISSION_GRANT);
9581 long ident = mInjector.binderClearCallingIdentity();
9583 if (getTargetSdk(packageName, user.getIdentifier())
9584 < android.os.Build.VERSION_CODES.M) {
9587 if (!isRuntimePermission(permission)) {
9588 EventLog.writeEvent(0x534e4554, "62623498", user.getIdentifier(), "");
9591 final PackageManager packageManager = mInjector.getPackageManager();
9592 switch (grantState) {
9593 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
9594 mInjector.getPackageManagerInternal().grantRuntimePermission(packageName,
9595 permission, user.getIdentifier(), true /* override policy */);
9596 packageManager.updatePermissionFlags(permission, packageName,
9597 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
9598 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
9601 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
9602 mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName,
9603 permission, user.getIdentifier(), true /* override policy */);
9604 packageManager.updatePermissionFlags(permission, packageName,
9605 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
9606 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
9609 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
9610 packageManager.updatePermissionFlags(permission, packageName,
9611 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
9615 } catch (SecurityException se) {
9617 } catch (NameNotFoundException e) {
9620 mInjector.binderRestoreCallingIdentity(ident);
9626 public int getPermissionGrantState(ComponentName admin, String callerPackage,
9627 String packageName, String permission) throws RemoteException {
9628 PackageManager packageManager = mInjector.getPackageManager();
9630 UserHandle user = mInjector.binderGetCallingUserHandle();
9631 if (!isCallerWithSystemUid()) {
9632 // Ensure the caller is a DO/PO or a permission grant state delegate.
9633 enforceCanManageScope(admin, callerPackage,
9634 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT);
9636 synchronized (this) {
9637 long ident = mInjector.binderClearCallingIdentity();
9639 int granted = mIPackageManager.checkPermission(permission,
9640 packageName, user.getIdentifier());
9641 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
9642 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
9643 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
9644 // Not controlled by policy
9645 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
9647 // Policy controlled so return result based on permission grant state
9648 return granted == PackageManager.PERMISSION_GRANTED
9649 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
9650 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
9653 mInjector.binderRestoreCallingIdentity(ident);
9658 boolean isPackageInstalledForUser(String packageName, int userHandle) {
9660 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
9662 return (pi != null) && (pi.applicationInfo.flags != 0);
9663 } catch (RemoteException re) {
9664 throw new RuntimeException("Package manager has died", re);
9668 public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
9669 final PackageManager packageManager = mInjector.getPackageManager();
9670 PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
9671 return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
9672 == PermissionInfo.PROTECTION_DANGEROUS;
9676 public boolean isProvisioningAllowed(String action, String packageName) {
9677 Preconditions.checkNotNull(packageName);
9679 final int callingUid = mInjector.binderGetCallingUid();
9680 final long ident = mInjector.binderClearCallingIdentity();
9682 final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser(
9683 packageName, UserHandle.getUserId(callingUid));
9684 Preconditions.checkArgument(callingUid == uidForPackage,
9685 "Caller uid doesn't match the one for the provided package.");
9686 } catch (NameNotFoundException e) {
9687 throw new IllegalArgumentException("Invalid package provided " + packageName, e);
9689 mInjector.binderRestoreCallingIdentity(ident);
9692 return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK;
9696 public int checkProvisioningPreCondition(String action, String packageName) {
9697 Preconditions.checkNotNull(packageName);
9698 enforceCanManageProfileAndDeviceOwners();
9699 return checkProvisioningPreConditionSkipPermission(action, packageName);
9702 private int checkProvisioningPreConditionSkipPermission(String action, String packageName) {
9704 return CODE_DEVICE_ADMIN_NOT_SUPPORTED;
9707 final int callingUserId = mInjector.userHandleGetCallingUserId();
9708 if (action != null) {
9710 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
9711 return checkManagedProfileProvisioningPreCondition(packageName, callingUserId);
9712 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
9713 return checkDeviceOwnerProvisioningPreCondition(callingUserId);
9714 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER:
9715 return checkManagedUserProvisioningPreCondition(callingUserId);
9716 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE:
9717 return checkManagedShareableDeviceProvisioningPreCondition(callingUserId);
9720 throw new IllegalArgumentException("Unknown provisioning action " + action);
9724 * The device owner can only be set before the setup phase of the primary user has completed,
9725 * except for adb command if no accounts or additional users are present on the device.
9727 private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
9728 int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) {
9729 if (mOwners.hasDeviceOwner()) {
9730 return CODE_HAS_DEVICE_OWNER;
9732 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
9733 return CODE_USER_HAS_PROFILE_OWNER;
9735 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
9736 return CODE_USER_NOT_RUNNING;
9738 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
9739 return CODE_HAS_PAIRED;
9742 // if shell command runs after user setup completed check device status. Otherwise, OK.
9743 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
9744 if (!mInjector.userManagerIsSplitSystemUser()) {
9745 if (mUserManager.getUserCount() > 1) {
9746 return CODE_NONSYSTEM_USER_EXISTS;
9748 if (hasIncompatibleAccountsOrNonAdb) {
9749 return CODE_ACCOUNTS_NOT_EMPTY;
9752 // STOPSHIP Do proper check in split user mode
9757 if (!mInjector.userManagerIsSplitSystemUser()) {
9758 // In non-split user mode, DO has to be user 0
9759 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
9760 return CODE_NOT_SYSTEM_USER;
9762 // In non-split user mode, only provision DO before setup wizard completes
9763 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
9764 return CODE_USER_SETUP_COMPLETED;
9767 // STOPSHIP Do proper check in split user mode
9773 private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) {
9774 synchronized (this) {
9775 // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
9776 return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
9777 deviceOwnerUserId, /* isAdb= */ false,
9778 /* hasIncompatibleAccountsOrNonAdb=*/ true);
9782 private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) {
9783 if (!hasFeatureManagedUsers()) {
9784 return CODE_MANAGED_USERS_NOT_SUPPORTED;
9786 if (callingUserId == UserHandle.USER_SYSTEM
9787 && mInjector.userManagerIsSplitSystemUser()) {
9788 // Managed-profiles cannot be setup on the system user.
9789 return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
9791 if (getProfileOwner(callingUserId) != null) {
9792 // Managed user cannot have a managed profile.
9793 return CODE_USER_HAS_PROFILE_OWNER;
9796 final long ident = mInjector.binderClearCallingIdentity();
9798 final UserHandle callingUserHandle = UserHandle.of(callingUserId);
9799 final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId);
9800 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
9801 callingUserHandle)) {
9802 // An admin can initiate provisioning if it has set the restriction.
9803 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
9804 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) {
9805 return CODE_ADD_MANAGED_PROFILE_DISALLOWED;
9808 boolean canRemoveProfile = true;
9809 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
9810 callingUserHandle)) {
9811 // We can remove a profile if the admin itself has set the restriction.
9812 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
9813 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
9815 canRemoveProfile = false;
9818 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) {
9819 return CODE_CANNOT_ADD_MANAGED_PROFILE;
9822 mInjector.binderRestoreCallingIdentity(ident);
9827 private ComponentName getOwnerComponent(String packageName, int userId) {
9828 if (isDeviceOwnerPackage(packageName, userId)) {
9829 return mOwners.getDeviceOwnerComponent();
9831 if (isProfileOwnerPackage(packageName, userId)) {
9832 return mOwners.getProfileOwnerComponent(userId);
9838 * Return device owner or profile owner set on a given user.
9840 private @Nullable ComponentName getOwnerComponent(int userId) {
9841 synchronized (this) {
9842 if (mOwners.getDeviceOwnerUserId() == userId) {
9843 return mOwners.getDeviceOwnerComponent();
9845 if (mOwners.hasProfileOwner(userId)) {
9846 return mOwners.getProfileOwnerComponent(userId);
9852 private int checkManagedUserProvisioningPreCondition(int callingUserId) {
9853 if (!hasFeatureManagedUsers()) {
9854 return CODE_MANAGED_USERS_NOT_SUPPORTED;
9856 if (!mInjector.userManagerIsSplitSystemUser()) {
9857 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
9858 return CODE_NOT_SYSTEM_USER_SPLIT;
9860 if (callingUserId == UserHandle.USER_SYSTEM) {
9861 // System user cannot be a managed user.
9862 return CODE_SYSTEM_USER;
9864 if (hasUserSetupCompleted(callingUserId)) {
9865 return CODE_USER_SETUP_COMPLETED;
9867 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
9868 return CODE_HAS_PAIRED;
9873 private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) {
9874 if (!mInjector.userManagerIsSplitSystemUser()) {
9875 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
9876 return CODE_NOT_SYSTEM_USER_SPLIT;
9878 return checkDeviceOwnerProvisioningPreCondition(callingUserId);
9881 private boolean hasFeatureManagedUsers() {
9883 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
9884 } catch (RemoteException e) {
9890 public String getWifiMacAddress(ComponentName admin) {
9891 // Make sure caller has DO.
9892 synchronized (this) {
9893 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9896 final long ident = mInjector.binderClearCallingIdentity();
9898 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
9899 if (wifiInfo == null) {
9902 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
9904 mInjector.binderRestoreCallingIdentity(ident);
9909 * Returns the target sdk version number that the given packageName was built for
9910 * in the given user.
9912 private int getTargetSdk(String packageName, int userId) {
9913 final ApplicationInfo ai;
9915 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
9916 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
9917 return targetSdkVersion;
9918 } catch (RemoteException e) {
9925 public boolean isManagedProfile(ComponentName admin) {
9926 enforceProfileOrDeviceOwner(admin);
9927 return isManagedProfile(mInjector.userHandleGetCallingUserId());
9931 public boolean isSystemOnlyUser(ComponentName admin) {
9932 synchronized (this) {
9933 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9935 final int callingUserId = mInjector.userHandleGetCallingUserId();
9936 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
9940 public void reboot(ComponentName admin) {
9941 Preconditions.checkNotNull(admin);
9942 // Make sure caller has DO.
9943 synchronized (this) {
9944 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9946 long ident = mInjector.binderClearCallingIdentity();
9948 // Make sure there are no ongoing calls on the device.
9949 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
9950 throw new IllegalStateException("Cannot be called with ongoing call on the device");
9952 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
9954 mInjector.binderRestoreCallingIdentity(ident);
9959 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
9963 Preconditions.checkNotNull(who, "ComponentName is null");
9964 final int userHandle = mInjector.userHandleGetCallingUserId();
9965 synchronized (this) {
9966 ActiveAdmin admin = getActiveAdminForUidLocked(who,
9967 mInjector.binderGetCallingUid());
9968 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
9969 admin.shortSupportMessage = message;
9970 saveSettingsLocked(userHandle);
9976 public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
9980 Preconditions.checkNotNull(who, "ComponentName is null");
9981 synchronized (this) {
9982 ActiveAdmin admin = getActiveAdminForUidLocked(who,
9983 mInjector.binderGetCallingUid());
9984 return admin.shortSupportMessage;
9989 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
9993 Preconditions.checkNotNull(who, "ComponentName is null");
9994 final int userHandle = mInjector.userHandleGetCallingUserId();
9995 synchronized (this) {
9996 ActiveAdmin admin = getActiveAdminForUidLocked(who,
9997 mInjector.binderGetCallingUid());
9998 if (!TextUtils.equals(admin.longSupportMessage, message)) {
9999 admin.longSupportMessage = message;
10000 saveSettingsLocked(userHandle);
10006 public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
10007 if (!mHasFeature) {
10010 Preconditions.checkNotNull(who, "ComponentName is null");
10011 synchronized (this) {
10012 ActiveAdmin admin = getActiveAdminForUidLocked(who,
10013 mInjector.binderGetCallingUid());
10014 return admin.longSupportMessage;
10019 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
10020 if (!mHasFeature) {
10023 Preconditions.checkNotNull(who, "ComponentName is null");
10024 if (!isCallerWithSystemUid()) {
10025 throw new SecurityException("Only the system can query support message for user");
10027 synchronized (this) {
10028 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
10029 if (admin != null) {
10030 return admin.shortSupportMessage;
10037 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
10038 if (!mHasFeature) {
10041 Preconditions.checkNotNull(who, "ComponentName is null");
10042 if (!isCallerWithSystemUid()) {
10043 throw new SecurityException("Only the system can query support message for user");
10045 synchronized (this) {
10046 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
10047 if (admin != null) {
10048 return admin.longSupportMessage;
10055 public void setOrganizationColor(@NonNull ComponentName who, int color) {
10056 if (!mHasFeature) {
10059 Preconditions.checkNotNull(who, "ComponentName is null");
10060 final int userHandle = mInjector.userHandleGetCallingUserId();
10061 enforceManagedProfile(userHandle, "set organization color");
10062 synchronized (this) {
10063 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10064 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10065 admin.organizationColor = color;
10066 saveSettingsLocked(userHandle);
10071 public void setOrganizationColorForUser(int color, int userId) {
10072 if (!mHasFeature) {
10075 enforceFullCrossUsersPermission(userId);
10076 enforceManageUsers();
10077 enforceManagedProfile(userId, "set organization color");
10078 synchronized (this) {
10079 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
10080 admin.organizationColor = color;
10081 saveSettingsLocked(userId);
10086 public int getOrganizationColor(@NonNull ComponentName who) {
10087 if (!mHasFeature) {
10088 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
10090 Preconditions.checkNotNull(who, "ComponentName is null");
10091 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
10092 synchronized (this) {
10093 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10094 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10095 return admin.organizationColor;
10100 public int getOrganizationColorForUser(int userHandle) {
10101 if (!mHasFeature) {
10102 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
10104 enforceFullCrossUsersPermission(userHandle);
10105 enforceManagedProfile(userHandle, "get organization color");
10106 synchronized (this) {
10107 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
10108 return (profileOwner != null)
10109 ? profileOwner.organizationColor
10110 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
10115 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
10116 if (!mHasFeature) {
10119 Preconditions.checkNotNull(who, "ComponentName is null");
10120 final int userHandle = mInjector.userHandleGetCallingUserId();
10122 synchronized (this) {
10123 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10124 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10125 if (!TextUtils.equals(admin.organizationName, text)) {
10126 admin.organizationName = (text == null || text.length() == 0)
10127 ? null : text.toString();
10128 saveSettingsLocked(userHandle);
10134 public CharSequence getOrganizationName(@NonNull ComponentName who) {
10135 if (!mHasFeature) {
10138 Preconditions.checkNotNull(who, "ComponentName is null");
10139 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
10140 synchronized(this) {
10141 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10142 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10143 return admin.organizationName;
10148 public CharSequence getDeviceOwnerOrganizationName() {
10149 if (!mHasFeature) {
10152 enforceDeviceOwnerOrManageUsers();
10153 synchronized(this) {
10154 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
10155 return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
10160 public CharSequence getOrganizationNameForUser(int userHandle) {
10161 if (!mHasFeature) {
10164 enforceFullCrossUsersPermission(userHandle);
10165 enforceManagedProfile(userHandle, "get organization name");
10166 synchronized (this) {
10167 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
10168 return (profileOwner != null)
10169 ? profileOwner.organizationName
10175 public void setAffiliationIds(ComponentName admin, List<String> ids) {
10176 if (!mHasFeature) {
10180 throw new IllegalArgumentException("ids must not be null");
10182 for (String id : ids) {
10183 if (TextUtils.isEmpty(id)) {
10184 throw new IllegalArgumentException("ids must not contain empty string");
10188 final Set<String> affiliationIds = new ArraySet<>(ids);
10189 final int callingUserId = mInjector.userHandleGetCallingUserId();
10190 synchronized (this) {
10191 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10192 getUserData(callingUserId).mAffiliationIds = affiliationIds;
10193 saveSettingsLocked(callingUserId);
10194 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
10195 // Affiliation ids specified by the device owner are additionally stored in
10196 // UserHandle.USER_SYSTEM's DevicePolicyData.
10197 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
10198 saveSettingsLocked(UserHandle.USER_SYSTEM);
10201 // Affiliation status for any user, not just the calling user, might have changed.
10202 // The device owner user will still be affiliated after changing its affiliation ids,
10203 // but as a result of that other users might become affiliated or un-affiliated.
10204 maybePauseDeviceWideLoggingLocked();
10205 maybeResumeDeviceWideLoggingLocked();
10206 maybeClearLockTaskPackagesLocked();
10211 public List<String> getAffiliationIds(ComponentName admin) {
10212 if (!mHasFeature) {
10213 return Collections.emptyList();
10216 Preconditions.checkNotNull(admin);
10217 synchronized (this) {
10218 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10219 return new ArrayList<String>(
10220 getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds);
10225 public boolean isAffiliatedUser() {
10226 if (!mHasFeature) {
10230 synchronized (this) {
10231 return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
10235 private boolean isUserAffiliatedWithDeviceLocked(int userId) {
10236 if (!mOwners.hasDeviceOwner()) {
10239 if (userId == mOwners.getDeviceOwnerUserId()) {
10240 // The user that the DO is installed on is always affiliated with the device.
10243 if (userId == UserHandle.USER_SYSTEM) {
10244 // The system user is always affiliated in a DO device, even if the DO is set on a
10245 // different user. This could be the case if the DO is set in the primary user
10246 // of a split user device.
10249 final ComponentName profileOwner = getProfileOwner(userId);
10250 if (profileOwner == null) {
10253 final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
10254 final Set<String> deviceAffiliationIds =
10255 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
10256 for (String id : userAffiliationIds) {
10257 if (deviceAffiliationIds.contains(id)) {
10264 private boolean areAllUsersAffiliatedWithDeviceLocked() {
10265 final long ident = mInjector.binderClearCallingIdentity();
10267 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
10268 for (int i = 0; i < userInfos.size(); i++) {
10269 int userId = userInfos.get(i).id;
10270 if (!isUserAffiliatedWithDeviceLocked(userId)) {
10271 Slog.d(LOG_TAG, "User id " + userId + " not affiliated.");
10276 mInjector.binderRestoreCallingIdentity(ident);
10283 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
10284 if (!mHasFeature) {
10287 Preconditions.checkNotNull(admin);
10289 synchronized (this) {
10290 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10291 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
10294 mInjector.securityLogSetLoggingEnabledProperty(enabled);
10296 mSecurityLogMonitor.start();
10297 maybePauseDeviceWideLoggingLocked();
10299 mSecurityLogMonitor.stop();
10305 public boolean isSecurityLoggingEnabled(ComponentName admin) {
10306 if (!mHasFeature) {
10310 synchronized (this) {
10311 if (!isCallerWithSystemUid()) {
10312 Preconditions.checkNotNull(admin);
10313 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10315 return mInjector.securityLogGetLoggingEnabledProperty();
10319 private synchronized void recordSecurityLogRetrievalTime() {
10320 final long currentTime = System.currentTimeMillis();
10321 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
10322 if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
10323 policyData.mLastSecurityLogRetrievalTime = currentTime;
10324 saveSettingsLocked(UserHandle.USER_SYSTEM);
10329 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
10330 if (!mHasFeature) {
10334 Preconditions.checkNotNull(admin);
10335 ensureDeviceOwnerAndAllUsersAffiliated(admin);
10337 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
10338 || !mInjector.securityLogGetLoggingEnabledProperty()) {
10342 recordSecurityLogRetrievalTime();
10344 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
10346 SecurityLog.readPreviousEvents(output);
10347 return new ParceledListSlice<SecurityEvent>(output);
10348 } catch (IOException e) {
10349 Slog.w(LOG_TAG, "Fail to read previous events" , e);
10350 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
10355 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
10356 if (!mHasFeature) {
10360 Preconditions.checkNotNull(admin);
10361 ensureDeviceOwnerAndAllUsersAffiliated(admin);
10363 if (!mInjector.securityLogGetLoggingEnabledProperty()) {
10367 recordSecurityLogRetrievalTime();
10369 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
10370 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
10373 private void enforceCanManageDeviceAdmin() {
10374 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
10378 private void enforceCanManageProfileAndDeviceOwners() {
10379 mContext.enforceCallingOrSelfPermission(
10380 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
10383 private void enforceCallerSystemUserHandle() {
10384 final int callingUid = mInjector.binderGetCallingUid();
10385 final int userId = UserHandle.getUserId(callingUid);
10386 if (userId != UserHandle.USER_SYSTEM) {
10387 throw new SecurityException("Caller has to be in user 0");
10392 public boolean isUninstallInQueue(final String packageName) {
10393 enforceCanManageDeviceAdmin();
10394 final int userId = mInjector.userHandleGetCallingUserId();
10395 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10396 synchronized (this) {
10397 return mPackagesToRemove.contains(packageUserPair);
10402 public void uninstallPackageWithActiveAdmins(final String packageName) {
10403 enforceCanManageDeviceAdmin();
10404 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
10406 final int userId = mInjector.userHandleGetCallingUserId();
10408 enforceUserUnlocked(userId);
10410 final ComponentName profileOwner = getProfileOwner(userId);
10411 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
10412 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
10415 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
10416 if (getDeviceOwnerUserId() == userId && deviceOwner != null
10417 && packageName.equals(deviceOwner.getPackageName())) {
10418 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
10421 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10422 synchronized (this) {
10423 mPackagesToRemove.add(packageUserPair);
10426 // All active admins on the user.
10427 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
10429 // Active admins in the target package.
10430 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
10431 if (allActiveAdmins != null) {
10432 for (ComponentName activeAdmin : allActiveAdmins) {
10433 if (packageName.equals(activeAdmin.getPackageName())) {
10434 packageActiveAdmins.add(activeAdmin);
10435 removeActiveAdmin(activeAdmin, userId);
10439 if (packageActiveAdmins.size() == 0) {
10440 startUninstallIntent(packageName, userId);
10442 mHandler.postDelayed(new Runnable() {
10444 public void run() {
10445 for (ComponentName activeAdmin : packageActiveAdmins) {
10446 removeAdminArtifacts(activeAdmin, userId);
10448 startUninstallIntent(packageName, userId);
10450 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
10455 public boolean isDeviceProvisioned() {
10456 synchronized (this) {
10457 return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
10461 private boolean isCurrentUserDemo() {
10462 if (UserManager.isDeviceInDemoMode(mContext)) {
10463 final int userId = mInjector.userHandleGetCallingUserId();
10464 final long callingIdentity = mInjector.binderClearCallingIdentity();
10466 return mUserManager.getUserInfo(userId).isDemo();
10468 mInjector.binderRestoreCallingIdentity(callingIdentity);
10474 private void removePackageIfRequired(final String packageName, final int userId) {
10475 if (!packageHasActiveAdmins(packageName, userId)) {
10476 // Will not do anything if uninstall was not requested or was already started.
10477 startUninstallIntent(packageName, userId);
10481 private void startUninstallIntent(final String packageName, final int userId) {
10482 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10483 synchronized (this) {
10484 if (!mPackagesToRemove.contains(packageUserPair)) {
10485 // Do nothing if uninstall was not requested or was already started.
10488 mPackagesToRemove.remove(packageUserPair);
10491 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
10492 // Package does not exist. Nothing to do.
10495 } catch (RemoteException re) {
10496 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
10499 try { // force stop the package before uninstalling
10500 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
10501 } catch (RemoteException re) {
10502 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
10504 final Uri packageURI = Uri.parse("package:" + packageName);
10505 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
10506 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
10507 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
10511 * Removes the admin from the policy. Ideally called after the admin's
10512 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
10514 * @param adminReceiver The admin to remove
10515 * @param userHandle The user for which this admin has to be removed.
10517 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
10518 synchronized (this) {
10519 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
10520 if (admin == null) {
10523 final DevicePolicyData policy = getUserData(userHandle);
10524 final boolean doProxyCleanup = admin.info.usesPolicy(
10525 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
10526 policy.mAdminList.remove(admin);
10527 policy.mAdminMap.remove(adminReceiver);
10528 validatePasswordOwnerLocked(policy);
10529 if (doProxyCleanup) {
10530 resetGlobalProxyLocked(policy);
10532 saveSettingsLocked(userHandle);
10533 updateMaximumTimeToLockLocked(userHandle);
10534 policy.mRemovingAdmins.remove(adminReceiver);
10536 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
10538 // The removed admin might have disabled camera, so update user
10540 pushUserRestrictions(userHandle);
10544 public void setDeviceProvisioningConfigApplied() {
10545 enforceManageUsers();
10546 synchronized (this) {
10547 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
10548 policy.mDeviceProvisioningConfigApplied = true;
10549 saveSettingsLocked(UserHandle.USER_SYSTEM);
10554 public boolean isDeviceProvisioningConfigApplied() {
10555 enforceManageUsers();
10556 synchronized (this) {
10557 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
10558 return policy.mDeviceProvisioningConfigApplied;
10563 * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
10565 * It's added for testing only. Please use this API carefully if it's used by other system app
10566 * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
10570 public void forceUpdateUserSetupComplete() {
10571 enforceCanManageProfileAndDeviceOwners();
10572 enforceCallerSystemUserHandle();
10573 // no effect if it's called from user build
10574 if (!mInjector.isBuildDebuggable()) {
10577 final int userId = UserHandle.USER_SYSTEM;
10578 boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
10579 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
10580 DevicePolicyData policy = getUserData(userId);
10581 policy.mUserSetupComplete = isUserCompleted;
10582 synchronized (this) {
10583 saveSettingsLocked(userId);
10587 // TODO(b/22388012): When backup is available for secondary users and profiles, consider
10588 // whether there are any privacy/security implications of enabling the backup service here
10589 // if there are other users or profiles unmanaged or managed by a different entity (i.e. not
10592 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
10593 if (!mHasFeature) {
10596 Preconditions.checkNotNull(admin);
10597 synchronized (this) {
10598 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10601 final long ident = mInjector.binderClearCallingIdentity();
10603 IBackupManager ibm = mInjector.getIBackupManager();
10605 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
10607 } catch (RemoteException e) {
10608 throw new IllegalStateException(
10609 "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
10611 mInjector.binderRestoreCallingIdentity(ident);
10616 public boolean isBackupServiceEnabled(ComponentName admin) {
10617 Preconditions.checkNotNull(admin);
10618 if (!mHasFeature) {
10621 synchronized (this) {
10623 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10624 IBackupManager ibm = mInjector.getIBackupManager();
10625 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
10626 } catch (RemoteException e) {
10627 throw new IllegalStateException("Failed requesting backup service state.", e);
10633 public boolean bindDeviceAdminServiceAsUser(
10634 @NonNull ComponentName admin, @NonNull IApplicationThread caller,
10635 @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
10636 @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
10637 if (!mHasFeature) {
10640 Preconditions.checkNotNull(admin);
10641 Preconditions.checkNotNull(caller);
10642 Preconditions.checkNotNull(serviceIntent);
10643 Preconditions.checkArgument(
10644 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
10645 "Service intent must be explicit (with a package name or component): "
10647 Preconditions.checkNotNull(connection);
10648 Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
10649 "target user id must be different from the calling user id");
10651 if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
10652 throw new SecurityException("Not allowed to bind to target user id");
10655 final String targetPackage;
10656 synchronized (this) {
10657 targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
10660 final long callingIdentity = mInjector.binderClearCallingIdentity();
10662 // Validate and sanitize the incoming service intent.
10663 final Intent sanitizedIntent =
10664 createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
10665 if (sanitizedIntent == null) {
10666 // Fail, cannot lookup the target service.
10669 // Ask ActivityManager to bind it. Notice that we are binding the service with the
10670 // caller app instead of DevicePolicyManagerService.
10671 return mInjector.getIActivityManager().bindService(
10672 caller, activtiyToken, serviceIntent,
10673 serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
10674 connection, flags, mContext.getOpPackageName(),
10675 targetUserId) != 0;
10676 } catch (RemoteException ex) {
10677 // Same process, should not happen.
10679 mInjector.binderRestoreCallingIdentity(callingIdentity);
10687 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
10688 if (!mHasFeature) {
10689 return Collections.emptyList();
10691 Preconditions.checkNotNull(admin);
10693 synchronized (this) {
10694 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10696 final int callingUserId = mInjector.userHandleGetCallingUserId();
10697 final long callingIdentity = mInjector.binderClearCallingIdentity();
10699 ArrayList<UserHandle> targetUsers = new ArrayList<>();
10700 if (!isDeviceOwner(admin, callingUserId)) {
10701 // Profile owners can only bind to the device owner.
10702 if (canUserBindToDeviceOwnerLocked(callingUserId)) {
10703 targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
10706 // Caller is the device owner: Look for profile owners that it can bind to.
10707 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
10708 for (int i = 0; i < userInfos.size(); i++) {
10709 final int userId = userInfos.get(i).id;
10710 if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
10711 targetUsers.add(UserHandle.of(userId));
10716 return targetUsers;
10718 mInjector.binderRestoreCallingIdentity(callingIdentity);
10723 private boolean canUserBindToDeviceOwnerLocked(int userId) {
10724 // There has to be a device owner, under another user id.
10725 if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
10729 // The user must have a profile owner that belongs to the same package as the device owner.
10730 if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
10731 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
10735 // The user must be affiliated.
10736 return isUserAffiliatedWithDeviceLocked(userId);
10740 * Return true if a given user has any accounts that'll prevent installing a device or profile
10741 * owner {@code owner}.
10742 * - If the user has no accounts, then return false.
10743 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
10744 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
10745 * ..._DISALLOWED, return true.
10746 * - Otherwise return false.
10748 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used
10749 * when the caller is not ADB.
10751 * DO NOT CALL IT WITH THE DPMS LOCK HELD.
10753 private boolean hasIncompatibleAccountsOrNonAdbNoLock(
10754 int userId, @Nullable ComponentName owner) {
10760 final long token = mInjector.binderClearCallingIdentity();
10762 final AccountManager am = AccountManager.get(mContext);
10763 final Account accounts[] = am.getAccountsAsUser(userId);
10764 if (accounts.length == 0) {
10767 synchronized (this) {
10768 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
10770 "Non test-only owner can't be installed with existing accounts.");
10775 final String[] feature_allow =
10776 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
10777 final String[] feature_disallow =
10778 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
10780 boolean compatible = true;
10781 for (Account account : accounts) {
10782 if (hasAccountFeatures(am, account, feature_disallow)) {
10783 Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
10784 compatible = false;
10787 if (!hasAccountFeatures(am, account, feature_allow)) {
10788 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
10789 compatible = false;
10794 Log.w(LOG_TAG, "All accounts are compatible");
10796 Log.e(LOG_TAG, "Found incompatible accounts");
10798 return !compatible;
10800 mInjector.binderRestoreCallingIdentity(token);
10804 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
10806 return am.hasFeatures(account, features, null, null).getResult();
10807 } catch (Exception e) {
10808 Log.w(LOG_TAG, "Failed to get account feature", e);
10813 private boolean isAdb() {
10814 final int callingUid = mInjector.binderGetCallingUid();
10815 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
10819 public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
10820 if (!mHasFeature) {
10823 Preconditions.checkNotNull(admin);
10824 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10826 if (enabled == isNetworkLoggingEnabledInternalLocked()) {
10827 // already in the requested state
10830 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
10831 deviceOwner.isNetworkLoggingEnabled = enabled;
10833 deviceOwner.numNetworkLoggingNotifications = 0;
10834 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
10836 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
10838 setNetworkLoggingActiveInternal(enabled);
10841 private synchronized void setNetworkLoggingActiveInternal(boolean active) {
10842 final long callingIdentity = mInjector.binderClearCallingIdentity();
10845 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
10846 if (!mNetworkLogger.startNetworkLogging()) {
10847 mNetworkLogger = null;
10848 Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
10849 + " service not being available yet.");
10851 maybePauseDeviceWideLoggingLocked();
10852 sendNetworkLoggingNotificationLocked();
10854 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
10855 Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
10856 + " service not being available yet.");
10858 mNetworkLogger = null;
10859 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING);
10862 mInjector.binderRestoreCallingIdentity(callingIdentity);
10866 /** Pauses security and network logging if there are unaffiliated users on the device */
10867 private void maybePauseDeviceWideLoggingLocked() {
10868 if (!areAllUsersAffiliatedWithDeviceLocked()) {
10869 Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be "
10870 + "paused if enabled.");
10871 mSecurityLogMonitor.pause();
10872 if (mNetworkLogger != null) {
10873 mNetworkLogger.pause();
10878 /** Resumes security and network logging (if they are enabled) if all users are affiliated */
10879 private void maybeResumeDeviceWideLoggingLocked() {
10880 if (areAllUsersAffiliatedWithDeviceLocked()) {
10881 final long ident = mInjector.binderClearCallingIdentity();
10883 mSecurityLogMonitor.resume();
10884 if (mNetworkLogger != null) {
10885 mNetworkLogger.resume();
10888 mInjector.binderRestoreCallingIdentity(ident);
10893 /** Deletes any security and network logs that might have been collected so far */
10894 private void discardDeviceWideLogsLocked() {
10895 mSecurityLogMonitor.discardLogs();
10896 if (mNetworkLogger != null) {
10897 mNetworkLogger.discardLogs();
10899 // TODO: We should discard pre-boot security logs here too, as otherwise those
10900 // logs (which might contain data from the user just removed) will be
10901 // available after next boot.
10905 public boolean isNetworkLoggingEnabled(ComponentName admin) {
10906 if (!mHasFeature) {
10909 synchronized (this) {
10910 enforceDeviceOwnerOrManageUsers();
10911 return isNetworkLoggingEnabledInternalLocked();
10915 private boolean isNetworkLoggingEnabledInternalLocked() {
10916 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
10917 return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
10921 * A maximum of 1200 events are returned, and the total marshalled size is in the order of
10922 * 100kB, so returning a List instead of ParceledListSlice is acceptable.
10923 * Ideally this would be done with ParceledList, however it only supports homogeneous types.
10925 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
10928 public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) {
10929 if (!mHasFeature) {
10932 Preconditions.checkNotNull(admin);
10933 ensureDeviceOwnerAndAllUsersAffiliated(admin);
10935 synchronized (this) {
10936 if (mNetworkLogger == null
10937 || !isNetworkLoggingEnabledInternalLocked()) {
10941 final long currentTime = System.currentTimeMillis();
10942 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
10943 if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
10944 policyData.mLastNetworkLogsRetrievalTime = currentTime;
10945 saveSettingsLocked(UserHandle.USER_SYSTEM);
10947 return mNetworkLogger.retrieveLogs(batchToken);
10951 private void sendNetworkLoggingNotificationLocked() {
10952 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
10953 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
10956 if (deviceOwner.numNetworkLoggingNotifications >=
10957 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
10960 final long now = System.currentTimeMillis();
10961 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
10964 deviceOwner.numNetworkLoggingNotifications++;
10965 if (deviceOwner.numNetworkLoggingNotifications
10966 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
10967 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
10969 deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
10971 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
10972 intent.setPackage("com.android.systemui");
10973 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
10974 UserHandle.CURRENT);
10975 Notification notification =
10976 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
10977 .setSmallIcon(R.drawable.ic_info_outline)
10978 .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
10979 .setContentText(mContext.getString(R.string.network_logging_notification_text))
10980 .setTicker(mContext.getString(R.string.network_logging_notification_title))
10982 .setContentIntent(pendingIntent)
10983 .setStyle(new Notification.BigTextStyle()
10984 .bigText(mContext.getString(R.string.network_logging_notification_text)))
10986 mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification);
10987 saveSettingsLocked(mOwners.getDeviceOwnerUserId());
10991 * Return the package name of owner in a given user.
10993 private String getOwnerPackageNameForUserLocked(int userId) {
10994 return mOwners.getDeviceOwnerUserId() == userId
10995 ? mOwners.getDeviceOwnerPackageName()
10996 : mOwners.getProfileOwnerPackage(userId);
11000 * @param rawIntent Original service intent specified by caller. It must be explicit.
11001 * @param expectedPackageName The expected package name of the resolved service.
11002 * @return Intent that have component explicitly set. {@code null} if no service is resolved
11003 * with the given intent.
11004 * @throws SecurityException if the intent is resolved to an invalid service.
11006 private Intent createCrossUserServiceIntent(
11007 @NonNull Intent rawIntent, @NonNull String expectedPackageName,
11008 @UserIdInt int targetUserId) throws RemoteException, SecurityException {
11009 ResolveInfo info = mIPackageManager.resolveService(
11011 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
11014 if (info == null || info.serviceInfo == null) {
11015 Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent
11016 + " or user " + targetUserId + " is not running");
11019 if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
11020 throw new SecurityException("Only allow to bind service in " + expectedPackageName);
11022 // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
11023 if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
11024 throw new SecurityException(
11025 "Service must be protected by BIND_DEVICE_ADMIN permission");
11027 // It is the system server to bind the service, it would be extremely dangerous if it
11028 // can be exploited to bind any service. Set the component explicitly to make sure we
11029 // do not bind anything accidentally.
11030 rawIntent.setComponent(info.serviceInfo.getComponentName());
11035 public long getLastSecurityLogRetrievalTime() {
11036 enforceDeviceOwnerOrManageUsers();
11037 return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
11041 public long getLastBugReportRequestTime() {
11042 enforceDeviceOwnerOrManageUsers();
11043 return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
11047 public long getLastNetworkLogRetrievalTime() {
11048 enforceDeviceOwnerOrManageUsers();
11049 return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime;
11053 public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
11054 if (!mHasFeature) {
11057 if (token == null || token.length < 32) {
11058 throw new IllegalArgumentException("token must be at least 32-byte long");
11060 synchronized (this) {
11061 final int userHandle = mInjector.userHandleGetCallingUserId();
11062 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11064 DevicePolicyData policy = getUserData(userHandle);
11065 long ident = mInjector.binderClearCallingIdentity();
11067 if (policy.mPasswordTokenHandle != 0) {
11068 mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle);
11071 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, userHandle);
11072 saveSettingsLocked(userHandle);
11073 return policy.mPasswordTokenHandle != 0;
11075 mInjector.binderRestoreCallingIdentity(ident);
11081 public boolean clearResetPasswordToken(ComponentName admin) {
11082 if (!mHasFeature) {
11085 synchronized (this) {
11086 final int userHandle = mInjector.userHandleGetCallingUserId();
11087 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11089 DevicePolicyData policy = getUserData(userHandle);
11090 if (policy.mPasswordTokenHandle != 0) {
11091 long ident = mInjector.binderClearCallingIdentity();
11093 boolean result = mLockPatternUtils.removeEscrowToken(
11094 policy.mPasswordTokenHandle, userHandle);
11095 policy.mPasswordTokenHandle = 0;
11096 saveSettingsLocked(userHandle);
11099 mInjector.binderRestoreCallingIdentity(ident);
11107 public boolean isResetPasswordTokenActive(ComponentName admin) {
11108 synchronized (this) {
11109 final int userHandle = mInjector.userHandleGetCallingUserId();
11110 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11112 DevicePolicyData policy = getUserData(userHandle);
11113 if (policy.mPasswordTokenHandle != 0) {
11114 long ident = mInjector.binderClearCallingIdentity();
11116 return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle,
11119 mInjector.binderRestoreCallingIdentity(ident);
11127 public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token,
11129 Preconditions.checkNotNull(token);
11130 synchronized (this) {
11131 final int userHandle = mInjector.userHandleGetCallingUserId();
11132 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11134 DevicePolicyData policy = getUserData(userHandle);
11135 if (policy.mPasswordTokenHandle != 0) {
11136 final String password = passwordOrNull != null ? passwordOrNull : "";
11137 return resetPasswordInternal(password, policy.mPasswordTokenHandle, token,
11138 flags, mInjector.binderGetCallingUid(), userHandle);
11140 Slog.w(LOG_TAG, "No saved token handle");
11147 public boolean isCurrentInputMethodSetByOwner() {
11148 enforceProfileOwnerOrSystemUser();
11149 return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet;
11153 public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
11154 final int userId = user.getIdentifier();
11155 enforceProfileOwnerOrFullCrossUsersPermission(userId);
11156 synchronized (this) {
11157 return new StringParceledListSlice(
11158 new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));