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.MANAGE_CA_CERTIFICATES;
20 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
21 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
22 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
23 import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
24 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
25 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
26 import static org.xmlpull.v1.XmlPullParser.END_TAG;
27 import static org.xmlpull.v1.XmlPullParser.TEXT;
29 import com.google.android.collect.Sets;
31 import android.Manifest.permission;
32 import android.accessibilityservice.AccessibilityServiceInfo;
33 import android.accounts.AccountManager;
34 import android.annotation.NonNull;
35 import android.annotation.Nullable;
36 import android.app.Activity;
37 import android.app.ActivityManager;
38 import android.app.ActivityManagerNative;
39 import android.app.AlarmManager;
40 import android.app.AppGlobals;
41 import android.app.IActivityManager;
42 import android.app.Notification;
43 import android.app.NotificationManager;
44 import android.app.PendingIntent;
45 import android.app.StatusBarManager;
46 import android.app.admin.DeviceAdminInfo;
47 import android.app.admin.DeviceAdminReceiver;
48 import android.app.admin.DevicePolicyManager;
49 import android.app.admin.DevicePolicyManagerInternal;
50 import android.app.admin.IDevicePolicyManager;
51 import android.app.admin.SystemUpdatePolicy;
52 import android.app.backup.IBackupManager;
53 import android.auditing.SecurityLog;
54 import android.auditing.SecurityLog.SecurityEvent;
55 import android.content.BroadcastReceiver;
56 import android.content.ComponentName;
57 import android.content.ContentResolver;
58 import android.content.Context;
59 import android.content.Intent;
60 import android.content.IntentFilter;
61 import android.content.pm.ActivityInfo;
62 import android.content.pm.ApplicationInfo;
63 import android.content.pm.IPackageManager;
64 import android.content.pm.PackageInfo;
65 import android.content.pm.PackageManager;
66 import android.content.pm.PackageManager.NameNotFoundException;
67 import android.content.pm.PackageManagerInternal;
68 import android.content.pm.ParceledListSlice;
69 import android.content.pm.ResolveInfo;
70 import android.content.pm.ServiceInfo;
71 import android.content.pm.UserInfo;
72 import android.database.ContentObserver;
73 import android.graphics.Bitmap;
74 import android.graphics.Color;
75 import android.media.AudioManager;
76 import android.media.IAudioService;
77 import android.net.ConnectivityManager;
78 import android.net.ProxyInfo;
79 import android.net.Uri;
80 import android.net.wifi.WifiInfo;
81 import android.net.wifi.WifiManager;
82 import android.os.AsyncTask;
83 import android.os.Binder;
84 import android.os.Build;
85 import android.os.Bundle;
86 import android.os.Environment;
87 import android.os.FileUtils;
88 import android.os.Handler;
89 import android.os.IBinder;
90 import android.os.Looper;
91 import android.os.ParcelFileDescriptor;
92 import android.os.PersistableBundle;
93 import android.os.PowerManager;
94 import android.os.PowerManagerInternal;
95 import android.os.Process;
96 import android.os.RecoverySystem;
97 import android.os.RemoteCallback;
98 import android.os.RemoteException;
99 import android.os.ServiceManager;
100 import android.os.SystemClock;
101 import android.os.SystemProperties;
102 import android.os.UserHandle;
103 import android.os.UserManager;
104 import android.os.UserManagerInternal;
105 import android.os.storage.StorageManager;
106 import android.provider.ContactsContract.QuickContact;
107 import android.provider.ContactsInternal;
108 import android.provider.Settings;
109 import android.security.Credentials;
110 import android.security.IKeyChainAliasCallback;
111 import android.security.IKeyChainService;
112 import android.security.KeyChain;
113 import android.security.KeyChain.KeyChainConnection;
114 import android.service.persistentdata.PersistentDataBlockManager;
115 import android.text.TextUtils;
116 import android.util.ArrayMap;
117 import android.util.ArraySet;
118 import android.util.Log;
119 import android.util.Pair;
120 import android.util.Slog;
121 import android.util.SparseArray;
122 import android.util.Xml;
123 import android.view.IWindowManager;
124 import android.view.accessibility.AccessibilityManager;
125 import android.view.accessibility.IAccessibilityManager;
126 import android.view.inputmethod.InputMethodInfo;
127 import android.view.inputmethod.InputMethodManager;
129 import com.android.internal.R;
130 import com.android.internal.annotations.VisibleForTesting;
131 import com.android.internal.statusbar.IStatusBarService;
132 import com.android.internal.util.FastXmlSerializer;
133 import com.android.internal.util.JournaledFile;
134 import com.android.internal.util.Preconditions;
135 import com.android.internal.util.XmlUtils;
136 import com.android.internal.widget.LockPatternUtils;
137 import com.android.server.LocalServices;
138 import com.android.server.SystemService;
139 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
140 import com.android.server.pm.UserRestrictionsUtils;
142 import org.xmlpull.v1.XmlPullParser;
143 import org.xmlpull.v1.XmlPullParserException;
144 import org.xmlpull.v1.XmlSerializer;
146 import java.io.ByteArrayInputStream;
148 import java.io.FileDescriptor;
149 import java.io.FileInputStream;
150 import java.io.FileNotFoundException;
151 import java.io.FileOutputStream;
152 import java.io.IOException;
153 import java.io.PrintWriter;
154 import java.nio.charset.StandardCharsets;
155 import java.security.cert.CertificateException;
156 import java.security.cert.CertificateFactory;
157 import java.security.cert.X509Certificate;
158 import java.text.DateFormat;
159 import java.util.ArrayList;
160 import java.util.Arrays;
161 import java.util.Collections;
162 import java.util.Date;
163 import java.util.List;
164 import java.util.Map.Entry;
165 import java.util.Set;
166 import java.util.concurrent.atomic.AtomicBoolean;
169 * Implementation of the device policy APIs.
171 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
173 private static final String LOG_TAG = "DevicePolicyManagerService";
175 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
177 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
179 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
181 private static final String TAG_STATUS_BAR = "statusbar";
183 private static final String ATTR_DISABLED = "disabled";
185 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
186 "do-not-ask-credentials-on-boot";
188 private static final String TAG_AFFILIATION_ID = "affiliation-id";
190 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
192 private static final String ATTR_VALUE = "value";
194 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
196 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
198 private static final long MS_PER_DAY = 86400 * 1000;
200 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
202 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
203 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
205 private static final int MONITORING_CERT_NOTIFICATION_ID = R.string.ssl_ca_cert_warning;
206 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
208 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
209 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
210 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
211 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
213 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
214 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
215 = "application-restrictions-manager";
218 * System property whose value is either "true" or "false", indicating whether
220 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
222 private static final int STATUS_BAR_DISABLE_MASK =
223 StatusBarManager.DISABLE_EXPAND |
224 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
225 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
226 StatusBarManager.DISABLE_SEARCH;
228 private static final int STATUS_BAR_DISABLE2_MASK =
229 StatusBarManager.DISABLE2_QUICK_SETTINGS;
231 private static final Set<String> SECURE_SETTINGS_WHITELIST;
232 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
233 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
234 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
236 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
237 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
238 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
239 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
241 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
242 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
243 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
245 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
246 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
247 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
248 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
249 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
250 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
251 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
252 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
253 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
255 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
256 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
257 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
258 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
259 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
260 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
264 * Keyguard features that when set on a managed profile that doesn't have its own challenge will
265 * affect the profile's parent user. These can also be set on the managed profile's parent DPM
268 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
269 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
270 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
273 * Keyguard features that when set on a profile affect the profile content or challenge only.
274 * These cannot be set on the managed profile's parent DPM instance
276 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
277 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
279 /** Keyguard features that are allowed to be set on a managed profile */
280 private static final int PROFILE_KEYGUARD_FEATURES =
281 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
283 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
285 final Context mContext;
286 final Injector mInjector;
287 final IPackageManager mIPackageManager;
288 final UserManager mUserManager;
289 final UserManagerInternal mUserManagerInternal;
290 private final LockPatternUtils mLockPatternUtils;
293 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
294 * is requested for user u.
296 private final Set<Pair<String, Integer>> mPackagesToRemove =
297 new ArraySet<Pair<String, Integer>>();
299 final LocalService mLocalService;
301 // Stores and loads state on device and profile owners.
303 final Owners mOwners;
305 private final Binder mToken = new Binder();
308 * Whether or not device admin feature is supported. If it isn't return defaults for all
311 private boolean mHasFeature;
313 private final SecurityLogMonitor mSecurityLogMonitor;
315 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
316 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
318 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
321 if(mRemoteBugreportServiceIsActive.get()) {
327 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
330 public void onReceive(Context context, Intent intent) {
331 if (RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
332 && mRemoteBugreportServiceIsActive.get()) {
333 onBugreportFinished(intent);
338 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
341 public void onReceive(Context context, Intent intent) {
342 String action = intent.getAction();
343 mInjector.getNotificationManager().cancel(LOG_TAG,
344 RemoteBugreportUtils.NOTIFICATION_ID);
345 if (RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
346 onBugreportSharingAccepted();
347 } else if (RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_DECLINED
349 onBugreportSharingDeclined();
351 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
355 public static final class Lifecycle extends SystemService {
356 private DevicePolicyManagerService mService;
358 public Lifecycle(Context context) {
360 mService = new DevicePolicyManagerService(context);
364 public void onStart() {
365 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
369 public void onBootPhase(int phase) {
370 mService.systemReady(phase);
374 public void onStartUser(int userHandle) {
375 mService.onStartUser(userHandle);
379 public static class DevicePolicyData {
380 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
381 int mActivePasswordLength = 0;
382 int mActivePasswordUpperCase = 0;
383 int mActivePasswordLowerCase = 0;
384 int mActivePasswordLetters = 0;
385 int mActivePasswordNumeric = 0;
386 int mActivePasswordSymbols = 0;
387 int mActivePasswordNonLetter = 0;
388 int mFailedPasswordAttempts = 0;
391 int mPasswordOwner = -1;
392 long mLastMaximumTimeToLock = -1;
393 boolean mUserSetupComplete = false;
394 int mUserProvisioningState;
395 int mPermissionPolicy;
397 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
398 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
399 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
401 // This is the list of component allowed to start lock task mode.
402 List<String> mLockTaskPackages = new ArrayList<>();
404 boolean mStatusBarDisabled = false;
406 ComponentName mRestrictionsProvider;
408 String mDelegatedCertInstallerPackage;
410 boolean doNotAskCredentialsOnBoot = false;
412 String mApplicationRestrictionsManagingPackage;
414 Set<String> mAffiliationIds = new ArraySet<>();
416 // Used for initialization of users created by createAndManageUsers.
417 boolean mAdminBroadcastPending = false;
418 PersistableBundle mInitBundle = null;
420 public DevicePolicyData(int userHandle) {
421 mUserHandle = userHandle;
425 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
427 final Handler mHandler;
429 BroadcastReceiver mReceiver = new BroadcastReceiver() {
431 public void onReceive(Context context, Intent intent) {
432 final String action = intent.getAction();
433 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
436 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
437 && userHandle == mOwners.getDeviceOwnerUserId()
438 && getDeviceOwnerRemoteBugreportUri() != null) {
439 IntentFilter filterConsent = new IntentFilter();
440 filterConsent.addAction(
441 RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_DECLINED);
442 filterConsent.addAction(
443 RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_ACCEPTED);
444 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
445 mInjector.getNotificationManager().notify(LOG_TAG,
446 RemoteBugreportUtils.NOTIFICATION_ID,
447 RemoteBugreportUtils.buildNotification(mContext,
448 RemoteBugreportUtils.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED));
450 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
451 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
453 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
454 + action + " for user " + userHandle);
456 mHandler.post(new Runnable() {
459 handlePasswordExpirationNotification(userHandle);
463 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
464 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
465 new MonitoringCertNotificationTask().execute(intent);
467 if (Intent.ACTION_USER_ADDED.equals(action)) {
468 disableDeviceLoggingIfNotCompliant();
469 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
470 disableDeviceLoggingIfNotCompliant();
471 removeUserData(userHandle);
472 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
473 synchronized (DevicePolicyManagerService.this) {
474 // Reset the policy data
475 mUserData.remove(userHandle);
476 sendAdminEnabledBroadcastLocked(userHandle);
478 handlePackagesChanged(null /* check all admins */, userHandle);
479 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
480 handlePackagesChanged(null /* check all admins */, userHandle);
481 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
482 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
483 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
484 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
485 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
486 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
487 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
488 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
489 clearWipeProfileNotification();
494 static class ActiveAdmin {
495 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
496 private static final String TAG_DISABLE_CAMERA = "disable-camera";
497 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
498 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
499 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
500 = "disable-bt-contacts-sharing";
501 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
502 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
503 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
504 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
505 private static final String TAG_ACCOUNT_TYPE = "account-type";
506 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
507 = "permitted-accessiblity-services";
508 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
509 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
510 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
511 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
512 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
513 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
514 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
515 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
516 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
517 private static final String TAG_PERMITTED_IMES = "permitted-imes";
518 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
519 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
520 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
521 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
522 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
523 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
524 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
525 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
526 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
527 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
528 private static final String ATTR_VALUE = "value";
529 private static final String TAG_PASSWORD_QUALITY = "password-quality";
530 private static final String TAG_POLICIES = "policies";
531 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
532 "cross-profile-widget-providers";
533 private static final String TAG_PROVIDER = "provider";
534 private static final String TAG_PACKAGE_LIST_ITEM = "item";
535 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
536 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
537 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
538 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
539 private static final String TAG_PARENT_ADMIN = "parent-admin";
540 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
541 private static final String TAG_ORGANIZATION_NAME = "organization-name";
543 final DeviceAdminInfo info;
545 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
547 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
548 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
550 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
551 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
553 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
554 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
556 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
557 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
559 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
560 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
562 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
563 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
565 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
566 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
568 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
569 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
571 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
572 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
574 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
575 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
577 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
578 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
580 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
581 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
583 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
585 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
587 boolean encryptionRequested = false;
588 boolean disableCamera = false;
589 boolean disableCallerId = false;
590 boolean disableContactsSearch = false;
591 boolean disableBluetoothContactSharing = true;
592 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
593 boolean requireAutoTime = false; // Can only be set by a device owner.
594 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
596 ActiveAdmin parentAdmin;
597 final boolean isParent;
599 static class TrustAgentInfo {
600 public PersistableBundle options;
601 TrustAgentInfo(PersistableBundle bundle) {
606 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
608 // The list of permitted accessibility services package namesas set by a profile
609 // or device owner. Null means all accessibility services are allowed, empty means
610 // none except system services are allowed.
611 List<String> permittedAccessiblityServices;
613 // The list of permitted input methods package names as set by a profile or device owner.
614 // Null means all input methods are allowed, empty means none except system imes are
616 List<String> permittedInputMethods;
618 // List of package names to keep cached.
619 List<String> keepUninstalledPackages;
621 // TODO: review implementation decisions with frameworks team
622 boolean specifiesGlobalProxy = false;
623 String globalProxySpec = null;
624 String globalProxyExclusionList = null;
626 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
628 List<String> crossProfileWidgetProviders;
630 Bundle userRestrictions;
632 // Support text provided by the admin to display to the user.
633 String shortSupportMessage = null;
634 String longSupportMessage = null;
636 // Background color of confirm credentials screen. Default: gray.
637 static final int DEF_ORGANIZATION_COLOR = Color.GRAY;
638 int organizationColor = DEF_ORGANIZATION_COLOR;
640 // Default title of confirm credentials screen
641 String organizationName = null;
643 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
648 ActiveAdmin getParentActiveAdmin() {
649 Preconditions.checkState(!isParent);
651 if (parentAdmin == null) {
652 parentAdmin = new ActiveAdmin(info, /* parent */ true);
657 boolean hasParentActiveAdmin() {
658 return parentAdmin != null;
661 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
663 public UserHandle getUserHandle() {
664 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
667 void writeToXml(XmlSerializer out)
668 throws IllegalArgumentException, IllegalStateException, IOException {
669 out.startTag(null, TAG_POLICIES);
670 info.writePoliciesToXml(out);
671 out.endTag(null, TAG_POLICIES);
672 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
673 out.startTag(null, TAG_PASSWORD_QUALITY);
674 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
675 out.endTag(null, TAG_PASSWORD_QUALITY);
676 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
677 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
678 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
679 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
681 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
682 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
683 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
684 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
686 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
687 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
688 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
689 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
691 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
692 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
693 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
694 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
696 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
697 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
698 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
699 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
701 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
702 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
703 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
704 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
706 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
707 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
708 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
709 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
711 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
712 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
713 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
714 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
717 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
718 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
719 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
720 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
722 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
723 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
724 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
725 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
727 if (specifiesGlobalProxy) {
728 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
729 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
730 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
731 if (globalProxySpec != null) {
732 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
733 out.attribute(null, ATTR_VALUE, globalProxySpec);
734 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
736 if (globalProxyExclusionList != null) {
737 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
738 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
739 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
742 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
743 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
744 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
745 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
747 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
748 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
749 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
750 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
752 if (encryptionRequested) {
753 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
754 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
755 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
758 out.startTag(null, TAG_DISABLE_CAMERA);
759 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
760 out.endTag(null, TAG_DISABLE_CAMERA);
762 if (disableCallerId) {
763 out.startTag(null, TAG_DISABLE_CALLER_ID);
764 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
765 out.endTag(null, TAG_DISABLE_CALLER_ID);
767 if (disableContactsSearch) {
768 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
769 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
770 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
772 if (!disableBluetoothContactSharing) {
773 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
774 out.attribute(null, ATTR_VALUE,
775 Boolean.toString(disableBluetoothContactSharing));
776 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
778 if (disableScreenCapture) {
779 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
780 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
781 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
783 if (requireAutoTime) {
784 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
785 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
786 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
788 if (forceEphemeralUsers) {
789 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
790 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
791 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
793 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
794 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
795 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
796 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
798 if (!accountTypesWithManagementDisabled.isEmpty()) {
799 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
800 for (String ac : accountTypesWithManagementDisabled) {
801 out.startTag(null, TAG_ACCOUNT_TYPE);
802 out.attribute(null, ATTR_VALUE, ac);
803 out.endTag(null, TAG_ACCOUNT_TYPE);
805 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
807 if (!trustAgentInfos.isEmpty()) {
808 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
809 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
810 for (Entry<String, TrustAgentInfo> entry : set) {
811 TrustAgentInfo trustAgentInfo = entry.getValue();
812 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
813 out.attribute(null, ATTR_VALUE, entry.getKey());
814 if (trustAgentInfo.options != null) {
815 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
817 trustAgentInfo.options.saveToXml(out);
818 } catch (XmlPullParserException e) {
819 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
821 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
823 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
825 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
827 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
828 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
829 final int providerCount = crossProfileWidgetProviders.size();
830 for (int i = 0; i < providerCount; i++) {
831 String provider = crossProfileWidgetProviders.get(i);
832 out.startTag(null, TAG_PROVIDER);
833 out.attribute(null, ATTR_VALUE, provider);
834 out.endTag(null, TAG_PROVIDER);
836 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
838 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
839 permittedAccessiblityServices);
840 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
841 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
842 if (hasUserRestrictions()) {
843 UserRestrictionsUtils.writeRestrictions(
844 out, userRestrictions, TAG_USER_RESTRICTIONS);
846 if (!TextUtils.isEmpty(shortSupportMessage)) {
847 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
848 out.text(shortSupportMessage);
849 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
851 if (!TextUtils.isEmpty(longSupportMessage)) {
852 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
853 out.text(longSupportMessage);
854 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
856 if (parentAdmin != null) {
857 out.startTag(null, TAG_PARENT_ADMIN);
858 parentAdmin.writeToXml(out);
859 out.endTag(null, TAG_PARENT_ADMIN);
861 if (organizationColor != DEF_ORGANIZATION_COLOR) {
862 out.startTag(null, TAG_ORGANIZATION_COLOR);
863 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
864 out.endTag(null, TAG_ORGANIZATION_COLOR);
866 if (organizationName != null) {
867 out.startTag(null, TAG_ORGANIZATION_NAME);
868 out.text(organizationName);
869 out.endTag(null, TAG_ORGANIZATION_NAME);
873 void writePackageListToXml(XmlSerializer out, String outerTag,
874 List<String> packageList)
875 throws IllegalArgumentException, IllegalStateException, IOException {
876 if (packageList == null) {
880 out.startTag(null, outerTag);
881 for (String packageName : packageList) {
882 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
883 out.attribute(null, ATTR_VALUE, packageName);
884 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
886 out.endTag(null, outerTag);
889 void readFromXml(XmlPullParser parser)
890 throws XmlPullParserException, IOException {
891 int outerDepth = parser.getDepth();
893 while ((type=parser.next()) != END_DOCUMENT
894 && (type != END_TAG || parser.getDepth() > outerDepth)) {
895 if (type == END_TAG || type == TEXT) {
898 String tag = parser.getName();
899 if (TAG_POLICIES.equals(tag)) {
900 info.readPoliciesFromXml(parser);
901 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
902 passwordQuality = Integer.parseInt(
903 parser.getAttributeValue(null, ATTR_VALUE));
904 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
905 minimumPasswordLength = Integer.parseInt(
906 parser.getAttributeValue(null, ATTR_VALUE));
907 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
908 passwordHistoryLength = Integer.parseInt(
909 parser.getAttributeValue(null, ATTR_VALUE));
910 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
911 minimumPasswordUpperCase = Integer.parseInt(
912 parser.getAttributeValue(null, ATTR_VALUE));
913 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
914 minimumPasswordLowerCase = Integer.parseInt(
915 parser.getAttributeValue(null, ATTR_VALUE));
916 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
917 minimumPasswordLetters = Integer.parseInt(
918 parser.getAttributeValue(null, ATTR_VALUE));
919 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
920 minimumPasswordNumeric = Integer.parseInt(
921 parser.getAttributeValue(null, ATTR_VALUE));
922 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
923 minimumPasswordSymbols = Integer.parseInt(
924 parser.getAttributeValue(null, ATTR_VALUE));
925 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
926 minimumPasswordNonLetter = Integer.parseInt(
927 parser.getAttributeValue(null, ATTR_VALUE));
928 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
929 maximumTimeToUnlock = Long.parseLong(
930 parser.getAttributeValue(null, ATTR_VALUE));
931 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
932 maximumFailedPasswordsForWipe = Integer.parseInt(
933 parser.getAttributeValue(null, ATTR_VALUE));
934 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
935 specifiesGlobalProxy = Boolean.parseBoolean(
936 parser.getAttributeValue(null, ATTR_VALUE));
937 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
939 parser.getAttributeValue(null, ATTR_VALUE);
940 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
941 globalProxyExclusionList =
942 parser.getAttributeValue(null, ATTR_VALUE);
943 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
944 passwordExpirationTimeout = Long.parseLong(
945 parser.getAttributeValue(null, ATTR_VALUE));
946 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
947 passwordExpirationDate = Long.parseLong(
948 parser.getAttributeValue(null, ATTR_VALUE));
949 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
950 encryptionRequested = Boolean.parseBoolean(
951 parser.getAttributeValue(null, ATTR_VALUE));
952 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
953 disableCamera = Boolean.parseBoolean(
954 parser.getAttributeValue(null, ATTR_VALUE));
955 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
956 disableCallerId = Boolean.parseBoolean(
957 parser.getAttributeValue(null, ATTR_VALUE));
958 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
959 disableContactsSearch = Boolean.parseBoolean(
960 parser.getAttributeValue(null, ATTR_VALUE));
961 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
962 disableBluetoothContactSharing = Boolean.parseBoolean(parser
963 .getAttributeValue(null, ATTR_VALUE));
964 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
965 disableScreenCapture = Boolean.parseBoolean(
966 parser.getAttributeValue(null, ATTR_VALUE));
967 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
968 requireAutoTime = Boolean.parseBoolean(
969 parser.getAttributeValue(null, ATTR_VALUE));
970 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
971 forceEphemeralUsers = Boolean.parseBoolean(
972 parser.getAttributeValue(null, ATTR_VALUE));
973 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
974 disabledKeyguardFeatures = Integer.parseInt(
975 parser.getAttributeValue(null, ATTR_VALUE));
976 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
977 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
978 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
979 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
980 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
981 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
982 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
983 permittedAccessiblityServices = readPackageList(parser, tag);
984 } else if (TAG_PERMITTED_IMES.equals(tag)) {
985 permittedInputMethods = readPackageList(parser, tag);
986 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
987 keepUninstalledPackages = readPackageList(parser, tag);
988 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
989 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
990 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
991 type = parser.next();
992 if (type == XmlPullParser.TEXT) {
993 shortSupportMessage = parser.getText();
995 Log.w(LOG_TAG, "Missing text when loading short support message");
997 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
998 type = parser.next();
999 if (type == XmlPullParser.TEXT) {
1000 longSupportMessage = parser.getText();
1002 Log.w(LOG_TAG, "Missing text when loading long support message");
1004 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1005 Preconditions.checkState(!isParent);
1007 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1008 parentAdmin.readFromXml(parser);
1009 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1010 organizationColor = Integer.parseInt(
1011 parser.getAttributeValue(null, ATTR_VALUE));
1012 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1013 type = parser.next();
1014 if (type == XmlPullParser.TEXT) {
1015 organizationName = parser.getText();
1017 Log.w(LOG_TAG, "Missing text when loading organization name");
1020 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1021 XmlUtils.skipCurrentTag(parser);
1026 private List<String> readPackageList(XmlPullParser parser,
1027 String tag) throws XmlPullParserException, IOException {
1028 List<String> result = new ArrayList<String>();
1029 int outerDepth = parser.getDepth();
1031 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1032 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1033 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1036 String outerTag = parser.getName();
1037 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1038 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1039 if (packageName != null) {
1040 result.add(packageName);
1042 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1045 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1051 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1052 throws XmlPullParserException, IOException {
1053 int outerDepthDAM = parser.getDepth();
1055 Set<String> result = new ArraySet<>();
1056 while ((typeDAM=parser.next()) != END_DOCUMENT
1057 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1058 if (typeDAM == END_TAG || typeDAM == TEXT) {
1061 String tagDAM = parser.getName();
1062 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1063 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1065 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1071 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1072 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1073 int outerDepthDAM = parser.getDepth();
1075 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1076 while ((typeDAM=parser.next()) != END_DOCUMENT
1077 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1078 if (typeDAM == END_TAG || typeDAM == TEXT) {
1081 String tagDAM = parser.getName();
1082 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1083 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1084 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1085 result.put(component, trustAgentInfo);
1087 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1093 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1094 throws XmlPullParserException, IOException {
1095 int outerDepthDAM = parser.getDepth();
1097 TrustAgentInfo result = new TrustAgentInfo(null);
1098 while ((typeDAM=parser.next()) != END_DOCUMENT
1099 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1100 if (typeDAM == END_TAG || typeDAM == TEXT) {
1103 String tagDAM = parser.getName();
1104 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1105 PersistableBundle bundle = new PersistableBundle();
1106 bundle.restoreFromXml(parser);
1107 result.options = bundle;
1109 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1115 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1116 throws XmlPullParserException, IOException {
1117 int outerDepthDAM = parser.getDepth();
1119 ArrayList<String> result = null;
1120 while ((typeDAM=parser.next()) != END_DOCUMENT
1121 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1122 if (typeDAM == END_TAG || typeDAM == TEXT) {
1125 String tagDAM = parser.getName();
1126 if (TAG_PROVIDER.equals(tagDAM)) {
1127 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1128 if (result == null) {
1129 result = new ArrayList<>();
1131 result.add(provider);
1133 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1139 boolean hasUserRestrictions() {
1140 return userRestrictions != null && userRestrictions.size() > 0;
1143 Bundle ensureUserRestrictions() {
1144 if (userRestrictions == null) {
1145 userRestrictions = new Bundle();
1147 return userRestrictions;
1150 void dump(String prefix, PrintWriter pw) {
1151 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1152 pw.print(prefix); pw.println("policies:");
1153 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1155 for (int i=0; i<pols.size(); i++) {
1156 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1159 pw.print(prefix); pw.print("passwordQuality=0x");
1160 pw.println(Integer.toHexString(passwordQuality));
1161 pw.print(prefix); pw.print("minimumPasswordLength=");
1162 pw.println(minimumPasswordLength);
1163 pw.print(prefix); pw.print("passwordHistoryLength=");
1164 pw.println(passwordHistoryLength);
1165 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1166 pw.println(minimumPasswordUpperCase);
1167 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1168 pw.println(minimumPasswordLowerCase);
1169 pw.print(prefix); pw.print("minimumPasswordLetters=");
1170 pw.println(minimumPasswordLetters);
1171 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1172 pw.println(minimumPasswordNumeric);
1173 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1174 pw.println(minimumPasswordSymbols);
1175 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1176 pw.println(minimumPasswordNonLetter);
1177 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1178 pw.println(maximumTimeToUnlock);
1179 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1180 pw.println(maximumFailedPasswordsForWipe);
1181 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1182 pw.println(specifiesGlobalProxy);
1183 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1184 pw.println(passwordExpirationTimeout);
1185 pw.print(prefix); pw.print("passwordExpirationDate=");
1186 pw.println(passwordExpirationDate);
1187 if (globalProxySpec != null) {
1188 pw.print(prefix); pw.print("globalProxySpec=");
1189 pw.println(globalProxySpec);
1191 if (globalProxyExclusionList != null) {
1192 pw.print(prefix); pw.print("globalProxyEclusionList=");
1193 pw.println(globalProxyExclusionList);
1195 pw.print(prefix); pw.print("encryptionRequested=");
1196 pw.println(encryptionRequested);
1197 pw.print(prefix); pw.print("disableCamera=");
1198 pw.println(disableCamera);
1199 pw.print(prefix); pw.print("disableCallerId=");
1200 pw.println(disableCallerId);
1201 pw.print(prefix); pw.print("disableContactsSearch=");
1202 pw.println(disableContactsSearch);
1203 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1204 pw.println(disableBluetoothContactSharing);
1205 pw.print(prefix); pw.print("disableScreenCapture=");
1206 pw.println(disableScreenCapture);
1207 pw.print(prefix); pw.print("requireAutoTime=");
1208 pw.println(requireAutoTime);
1209 pw.print(prefix); pw.print("forceEphemeralUsers=");
1210 pw.println(forceEphemeralUsers);
1211 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1212 pw.println(disabledKeyguardFeatures);
1213 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1214 pw.println(crossProfileWidgetProviders);
1215 if (permittedAccessiblityServices != null) {
1216 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1217 pw.println(permittedAccessiblityServices);
1219 if (permittedInputMethods != null) {
1220 pw.print(prefix); pw.print("permittedInputMethods=");
1221 pw.println(permittedInputMethods);
1223 if (keepUninstalledPackages != null) {
1224 pw.print(prefix); pw.print("keepUninstalledPackages=");
1225 pw.println(keepUninstalledPackages);
1227 pw.print(prefix); pw.print("organizationColor=");
1228 pw.println(organizationColor);
1229 if (organizationName != null) {
1230 pw.print(prefix); pw.print("organizationName=");
1231 pw.println(organizationName);
1233 pw.print(prefix); pw.println("userRestrictions:");
1234 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1235 pw.print(prefix); pw.print("isParent=");
1236 pw.println(isParent);
1237 if (parentAdmin != null) {
1238 pw.print(prefix); pw.println("parentAdmin:");
1239 parentAdmin.dump(prefix + " ", pw);
1244 private void handlePackagesChanged(String packageName, int userHandle) {
1245 boolean removed = false;
1246 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1247 DevicePolicyData policy = getUserData(userHandle);
1248 synchronized (this) {
1249 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1250 ActiveAdmin aa = policy.mAdminList.get(i);
1252 // If we're checking all packages or if the specific one we're checking matches,
1253 // then check if the package and receiver still exist.
1254 final String adminPackage = aa.info.getPackageName();
1255 if (packageName == null || packageName.equals(adminPackage)) {
1256 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1257 || mIPackageManager.getReceiverInfo(
1258 aa.info.getComponent(),
1259 PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE,
1260 userHandle) == null) {
1262 policy.mAdminList.remove(i);
1263 policy.mAdminMap.remove(aa.info.getComponent());
1266 } catch (RemoteException re) {
1271 validatePasswordOwnerLocked(policy);
1272 saveSettingsLocked(policy.mUserHandle);
1275 // Check if delegated cert installer or app restrictions managing packages are removed.
1276 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1277 policy.mDelegatedCertInstallerPackage = null;
1278 saveSettingsLocked(policy.mUserHandle);
1280 if (isRemovedPackage(
1281 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1282 policy.mApplicationRestrictionsManagingPackage = null;
1283 saveSettingsLocked(policy.mUserHandle);
1287 // The removed admin might have disabled camera, so update user restrictions.
1288 pushUserRestrictions(userHandle);
1292 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1294 return targetPackage != null
1295 && (changedPackage == null || changedPackage.equals(targetPackage))
1296 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1297 } catch (RemoteException e) {
1305 * Unit test will subclass it to inject mocks.
1308 static class Injector {
1310 private final Context mContext;
1312 Injector(Context context) {
1316 Owners newOwners() {
1317 return new Owners(mContext, getUserManager(), getUserManagerInternal());
1320 UserManager getUserManager() {
1321 return UserManager.get(mContext);
1324 UserManagerInternal getUserManagerInternal() {
1325 return LocalServices.getService(UserManagerInternal.class);
1328 PackageManagerInternal getPackageManagerInternal() {
1329 return LocalServices.getService(PackageManagerInternal.class);
1332 NotificationManager getNotificationManager() {
1333 return mContext.getSystemService(NotificationManager.class);
1336 PowerManagerInternal getPowerManagerInternal() {
1337 return LocalServices.getService(PowerManagerInternal.class);
1340 IWindowManager getIWindowManager() {
1341 return IWindowManager.Stub
1342 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1345 IActivityManager getIActivityManager() {
1346 return ActivityManagerNative.getDefault();
1349 IPackageManager getIPackageManager() {
1350 return AppGlobals.getPackageManager();
1353 IBackupManager getIBackupManager() {
1354 return IBackupManager.Stub.asInterface(
1355 ServiceManager.getService(Context.BACKUP_SERVICE));
1358 IAudioService getIAudioService() {
1359 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1362 LockPatternUtils newLockPatternUtils() {
1363 return new LockPatternUtils(mContext);
1366 Looper getMyLooper() {
1367 return Looper.myLooper();
1370 WifiManager getWifiManager() {
1371 return mContext.getSystemService(WifiManager.class);
1374 long binderClearCallingIdentity() {
1375 return Binder.clearCallingIdentity();
1378 void binderRestoreCallingIdentity(long token) {
1379 Binder.restoreCallingIdentity(token);
1382 int binderGetCallingUid() {
1383 return Binder.getCallingUid();
1386 int binderGetCallingPid() {
1387 return Binder.getCallingPid();
1390 UserHandle binderGetCallingUserHandle() {
1391 return Binder.getCallingUserHandle();
1394 boolean binderIsCallingUidMyUid() {
1395 return getCallingUid() == Process.myUid();
1398 final int userHandleGetCallingUserId() {
1399 return UserHandle.getUserId(binderGetCallingUid());
1402 File environmentGetUserSystemDirectory(int userId) {
1403 return Environment.getUserSystemDirectory(userId);
1406 void powerManagerGoToSleep(long time, int reason, int flags) {
1407 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1410 void powerManagerReboot(String reason) {
1411 mContext.getSystemService(PowerManager.class).reboot(reason);
1414 boolean systemPropertiesGetBoolean(String key, boolean def) {
1415 return SystemProperties.getBoolean(key, def);
1418 long systemPropertiesGetLong(String key, long def) {
1419 return SystemProperties.getLong(key, def);
1422 String systemPropertiesGet(String key, String def) {
1423 return SystemProperties.get(key, def);
1426 String systemPropertiesGet(String key) {
1427 return SystemProperties.get(key);
1430 void systemPropertiesSet(String key, String value) {
1431 SystemProperties.set(key, value);
1434 boolean userManagerIsSplitSystemUser() {
1435 return UserManager.isSplitSystemUser();
1438 String getDevicePolicyFilePathForSystemUser() {
1439 return "/data/system/";
1442 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1443 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1444 name, def, userHandle);
1447 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1448 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1449 name, value, userHandle);
1452 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1453 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1454 name, value, userHandle);
1457 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1458 Settings.Global.putStringForUser(mContext.getContentResolver(),
1459 name, value, userHandle);
1462 void settingsSecurePutInt(String name, int value) {
1463 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1466 int settingsGlobalGetInt(String name, int def) {
1467 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1470 void settingsGlobalPutInt(String name, int value) {
1471 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1474 void settingsSecurePutString(String name, String value) {
1475 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1478 void settingsGlobalPutString(String name, String value) {
1479 Settings.Global.putString(mContext.getContentResolver(), name, value);
1482 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1483 SecurityLog.setLoggingEnabledProperty(enabled);
1486 boolean securityLogGetLoggingEnabledProperty() {
1487 return SecurityLog.getLoggingEnabledProperty();
1490 boolean securityLogIsLoggingEnabled() {
1491 return SecurityLog.isLoggingEnabled();
1496 * Instantiates the service.
1498 public DevicePolicyManagerService(Context context) {
1499 this(new Injector(context));
1503 DevicePolicyManagerService(Injector injector) {
1504 mInjector = injector;
1505 mContext = Preconditions.checkNotNull(injector.mContext);
1506 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1507 mOwners = Preconditions.checkNotNull(injector.newOwners());
1509 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1510 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1511 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1513 mLocalService = new LocalService();
1514 mLockPatternUtils = injector.newLockPatternUtils();
1516 mSecurityLogMonitor = new SecurityLogMonitor(this);
1518 mHasFeature = mContext.getPackageManager()
1519 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1521 // Skip the rest of the initialization
1524 IntentFilter filter = new IntentFilter();
1525 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1526 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1527 filter.addAction(Intent.ACTION_USER_ADDED);
1528 filter.addAction(Intent.ACTION_USER_REMOVED);
1529 filter.addAction(Intent.ACTION_USER_STARTED);
1530 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1531 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1532 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1533 filter = new IntentFilter();
1534 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1535 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1536 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1537 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1538 filter.addDataScheme("package");
1539 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1540 filter = new IntentFilter();
1541 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1542 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1544 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1548 * Creates and loads the policy data from xml.
1549 * @param userHandle the user for whom to load the policy data
1553 DevicePolicyData getUserData(int userHandle) {
1554 synchronized (this) {
1555 DevicePolicyData policy = mUserData.get(userHandle);
1556 if (policy == null) {
1557 policy = new DevicePolicyData(userHandle);
1558 mUserData.append(userHandle, policy);
1559 loadSettingsLocked(policy, userHandle);
1566 * Creates and loads the policy data from xml for data that is shared between
1567 * various profiles of a user. In contrast to {@link #getUserData(int)}
1568 * it allows access to data of users other than the calling user.
1570 * This function should only be used for shared data, e.g. everything regarding
1571 * passwords and should be removed once multiple screen locks are present.
1572 * @param userHandle the user for whom to load the policy data
1575 DevicePolicyData getUserDataUnchecked(int userHandle) {
1576 long ident = mInjector.binderClearCallingIdentity();
1578 return getUserData(userHandle);
1580 mInjector.binderRestoreCallingIdentity(ident);
1584 void removeUserData(int userHandle) {
1585 synchronized (this) {
1586 if (userHandle == UserHandle.USER_SYSTEM) {
1587 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1590 mOwners.removeProfileOwner(userHandle);
1591 mOwners.writeProfileOwner(userHandle);
1593 DevicePolicyData policy = mUserData.get(userHandle);
1594 if (policy != null) {
1595 mUserData.remove(userHandle);
1597 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1598 DEVICE_POLICIES_XML);
1599 policyFile.delete();
1600 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1602 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1606 synchronized (this) {
1608 setDeviceOwnerSystemPropertyLocked();
1609 findOwnerComponentIfNecessaryLocked();
1610 migrateUserRestrictionsIfNecessaryLocked();
1612 // TODO PO may not have a class name either due to b/17652534. Address that too.
1614 updateDeviceOwnerLocked();
1618 private void setDeviceOwnerSystemPropertyLocked() {
1619 // Device owner may still be provisioned, do not set the read-only system property yet.
1620 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1623 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1624 // always false at this point.
1625 if ("encrypted".equals(mInjector.systemPropertiesGet("ro.crypto.state"))
1626 && "trigger_restart_min_framework".equals(
1627 mInjector.systemPropertiesGet("vold.decrypt"))){
1631 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1632 Slog.wtf(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1634 if (mOwners.hasDeviceOwner()) {
1635 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1636 disableDeviceLoggingIfNotCompliant();
1637 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1638 mSecurityLogMonitor.start();
1641 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1646 private void findOwnerComponentIfNecessaryLocked() {
1647 if (!mOwners.hasDeviceOwner()) {
1650 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1652 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1653 return; // Already a full component name.
1656 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1657 doComponentName.getPackageName(),
1658 mOwners.getDeviceOwnerUserId());
1659 if (doComponent == null) {
1660 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1662 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1664 mOwners.getDeviceOwnerName(),
1665 mOwners.getDeviceOwnerUserId(),
1666 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1667 mOwners.writeDeviceOwner();
1669 Log.v(LOG_TAG, "Device owner component filled in");
1675 * We didn't use to persist user restrictions for each owners but only persisted in user
1678 private void migrateUserRestrictionsIfNecessaryLocked() {
1679 boolean migrated = false;
1680 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1681 // except for the "system controlled" ones.
1682 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1684 Log.v(LOG_TAG, "Migrating DO user restrictions");
1688 // Migrate user 0 restrictions to DO.
1689 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1691 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1692 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1694 // Push DO user restrictions to user manager.
1695 pushUserRestrictions(UserHandle.USER_SYSTEM);
1697 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1702 // The following restrictions can be set on secondary users by the device owner, so we
1703 // assume they're not from the PO.
1704 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1705 UserManager.DISALLOW_OUTGOING_CALLS,
1706 UserManager.DISALLOW_SMS);
1708 for (UserInfo ui : mUserManager.getUsers()) {
1709 final int userId = ui.id;
1710 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1712 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1716 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1718 final Set<String> exceptionList =
1719 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1721 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1722 exceptionList, /* isDeviceOwner =*/ false);
1724 // Note if a secondary user has no PO but has a DA that disables camera, we
1725 // don't get here and won't push the camera user restriction to UserManager
1726 // here. That's okay because we'll push user restrictions anyway when a user
1727 // starts. But we still do it because we want to let user manager persist
1729 pushUserRestrictions(userId);
1731 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1734 if (VERBOSE_LOG && migrated) {
1735 Log.v(LOG_TAG, "User restrictions migrated.");
1739 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1740 Set<String> exceptionList, boolean isDeviceOwner) {
1741 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1742 user.getIdentifier());
1744 final Bundle newBaseRestrictions = new Bundle();
1745 final Bundle newOwnerRestrictions = new Bundle();
1747 for (String key : origRestrictions.keySet()) {
1748 if (!origRestrictions.getBoolean(key)) {
1751 final boolean canOwnerChange = isDeviceOwner
1752 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1753 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1755 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1756 newBaseRestrictions.putBoolean(key, true);
1758 newOwnerRestrictions.putBoolean(key, true);
1763 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1764 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1765 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1767 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1768 newBaseRestrictions);
1770 if (admin != null) {
1771 admin.ensureUserRestrictions().clear();
1772 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1774 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1776 saveSettingsLocked(user.getIdentifier());
1779 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1780 final DevicePolicyData policy = getUserData(userId);
1781 final int n = policy.mAdminList.size();
1782 ComponentName found = null;
1784 for (int i = 0; i < n; i++) {
1785 final ActiveAdmin admin = policy.mAdminList.get(i);
1786 if (packageName.equals(admin.info.getPackageName())) {
1789 found = admin.info.getComponent();
1795 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1801 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1802 * reminders. Clears alarm if no expirations are configured.
1804 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1805 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1806 final long now = System.currentTimeMillis();
1807 final long timeToExpire = expiration - now;
1808 final long alarmTime;
1809 if (expiration == 0) {
1810 // No expirations are currently configured: Cancel alarm.
1812 } else if (timeToExpire <= 0) {
1813 // The password has already expired: Repeat every 24 hours.
1814 alarmTime = now + MS_PER_DAY;
1816 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1817 // the expiration time.
1818 long alarmInterval = timeToExpire % MS_PER_DAY;
1819 if (alarmInterval == 0) {
1820 alarmInterval = MS_PER_DAY;
1822 alarmTime = now + alarmInterval;
1825 long token = mInjector.binderClearCallingIdentity();
1827 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1828 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1829 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1830 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1831 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1832 UserHandle.of(affectedUserHandle));
1834 if (alarmTime != 0) {
1835 am.set(AlarmManager.RTC, alarmTime, pi);
1838 mInjector.binderRestoreCallingIdentity(token);
1842 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1843 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1845 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1846 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1852 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
1854 enforceManagedProfile(userHandle, "call APIs on the parent profile");
1856 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1857 if (admin != null && parent) {
1858 admin = admin.getParentActiveAdmin();
1863 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1864 throws SecurityException {
1865 final int callingUid = mInjector.binderGetCallingUid();
1867 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1868 if (result != null) {
1873 final int userId = UserHandle.getUserId(callingUid);
1874 final DevicePolicyData policy = getUserData(userId);
1875 ActiveAdmin admin = policy.mAdminMap.get(who);
1876 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1877 throw new SecurityException("Admin " + admin.info.getComponent()
1878 + " does not own the device");
1880 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1881 throw new SecurityException("Admin " + admin.info.getComponent()
1882 + " does not own the profile");
1884 throw new SecurityException("Admin " + admin.info.getComponent()
1885 + " did not specify uses-policy for: "
1886 + admin.info.getTagForPolicy(reqPolicy));
1888 throw new SecurityException("No active admin owned by uid "
1889 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
1893 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
1894 throws SecurityException {
1896 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
1897 "call APIs on the parent profile");
1899 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
1900 return parent ? admin.getParentActiveAdmin() : admin;
1903 * Find the admin for the component and userId bit of the uid, then check
1904 * the admin's uid matches the uid.
1906 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
1907 final int userId = UserHandle.getUserId(uid);
1908 final DevicePolicyData policy = getUserData(userId);
1909 ActiveAdmin admin = policy.mAdminMap.get(who);
1910 if (admin == null) {
1911 throw new SecurityException("No active admin " + who);
1913 if (admin.getUid() != uid) {
1914 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1919 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
1921 // Try to find an admin which can use reqPolicy
1922 final int userId = UserHandle.getUserId(uid);
1923 final DevicePolicyData policy = getUserData(userId);
1925 ActiveAdmin admin = policy.mAdminMap.get(who);
1926 if (admin == null) {
1927 throw new SecurityException("No active admin " + who);
1929 if (admin.getUid() != uid) {
1930 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1932 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
1936 for (ActiveAdmin admin : policy.mAdminList) {
1937 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
1948 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
1950 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
1951 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
1953 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1955 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1956 // DO always has the PO power.
1957 return ownsDevice || ownsProfile;
1959 return admin.info.usesPolicy(reqPolicy);
1963 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
1964 sendAdminCommandLocked(admin, action, null);
1967 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
1968 sendAdminCommandLocked(admin, action, null, result);
1972 * Send an update to one specific admin, get notified when that admin returns a result.
1974 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
1975 BroadcastReceiver result) {
1976 Intent intent = new Intent(action);
1977 intent.setComponent(admin.info.getComponent());
1978 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
1979 intent.putExtra("expiration", admin.passwordExpirationDate);
1981 if (adminExtras != null) {
1982 intent.putExtras(adminExtras);
1984 if (result != null) {
1985 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
1986 null, result, mHandler, Activity.RESULT_OK, null, null);
1988 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
1993 * Send an update to all admins of a user that enforce a specified policy.
1995 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
1996 final DevicePolicyData policy = getUserData(userHandle);
1997 final int count = policy.mAdminList.size();
1999 for (int i = 0; i < count; i++) {
2000 final ActiveAdmin admin = policy.mAdminList.get(i);
2001 if (admin.info.usesPolicy(reqPolicy)) {
2002 sendAdminCommandLocked(admin, action);
2009 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2010 * enforce a specified policy.
2012 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2014 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2015 for (UserInfo ui : profiles) {
2017 sendAdminCommandLocked(action, reqPolicy, id);
2022 * Sends a broadcast to each profile that share the password unlock with the given user id.
2024 private void sendAdminCommandForLockscreenPoliciesLocked(
2025 String action, int reqPolicy, int userHandle) {
2026 if (isSeparateProfileChallengeEnabled(userHandle)) {
2027 sendAdminCommandLocked(action, reqPolicy, userHandle);
2029 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2033 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2034 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2035 if (admin != null) {
2036 getUserData(userHandle).mRemovingAdmins.add(adminReceiver);
2037 sendAdminCommandLocked(admin,
2038 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2039 new BroadcastReceiver() {
2041 public void onReceive(Context context, Intent intent) {
2042 removeAdminArtifacts(adminReceiver, userHandle);
2043 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2050 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2051 boolean throwForMissiongPermission) {
2055 enforceFullCrossUsersPermission(userHandle);
2056 ActivityInfo ai = null;
2058 ai = mIPackageManager.getReceiverInfo(adminName,
2059 PackageManager.GET_META_DATA |
2060 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS |
2061 PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE, userHandle);
2062 } catch (RemoteException e) {
2063 // shouldn't happen.
2066 throw new IllegalArgumentException("Unknown admin: " + adminName);
2069 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2070 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2071 + permission.BIND_DEVICE_ADMIN;
2072 Slog.w(LOG_TAG, message);
2073 if (throwForMissiongPermission &&
2074 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2075 throw new IllegalArgumentException(message);
2080 return new DeviceAdminInfo(mContext, ai);
2081 } catch (XmlPullParserException | IOException e) {
2082 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2088 private JournaledFile makeJournaledFile(int userHandle) {
2089 final String base = userHandle == UserHandle.USER_SYSTEM
2090 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2091 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2092 DEVICE_POLICIES_XML).getAbsolutePath();
2094 Log.v(LOG_TAG, "Opening " + base);
2096 return new JournaledFile(new File(base), new File(base + ".tmp"));
2099 private void saveSettingsLocked(int userHandle) {
2100 DevicePolicyData policy = getUserData(userHandle);
2101 JournaledFile journal = makeJournaledFile(userHandle);
2102 FileOutputStream stream = null;
2104 stream = new FileOutputStream(journal.chooseForWrite(), false);
2105 XmlSerializer out = new FastXmlSerializer();
2106 out.setOutput(stream, StandardCharsets.UTF_8.name());
2107 out.startDocument(null, true);
2109 out.startTag(null, "policies");
2110 if (policy.mRestrictionsProvider != null) {
2111 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2112 policy.mRestrictionsProvider.flattenToString());
2114 if (policy.mUserSetupComplete) {
2115 out.attribute(null, ATTR_SETUP_COMPLETE,
2116 Boolean.toString(true));
2118 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2119 out.attribute(null, ATTR_PROVISIONING_STATE,
2120 Integer.toString(policy.mUserProvisioningState));
2122 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2123 out.attribute(null, ATTR_PERMISSION_POLICY,
2124 Integer.toString(policy.mPermissionPolicy));
2126 if (policy.mDelegatedCertInstallerPackage != null) {
2127 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2128 policy.mDelegatedCertInstallerPackage);
2130 if (policy.mApplicationRestrictionsManagingPackage != null) {
2131 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2132 policy.mApplicationRestrictionsManagingPackage);
2135 final int N = policy.mAdminList.size();
2136 for (int i=0; i<N; i++) {
2137 ActiveAdmin ap = policy.mAdminList.get(i);
2139 out.startTag(null, "admin");
2140 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2142 out.endTag(null, "admin");
2146 if (policy.mPasswordOwner >= 0) {
2147 out.startTag(null, "password-owner");
2148 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2149 out.endTag(null, "password-owner");
2152 if (policy.mFailedPasswordAttempts != 0) {
2153 out.startTag(null, "failed-password-attempts");
2154 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2155 out.endTag(null, "failed-password-attempts");
2158 if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2159 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2160 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2161 || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
2162 out.startTag(null, "active-password");
2163 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2164 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2165 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2166 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2167 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2168 out.attribute(null, "numeric", Integer
2169 .toString(policy.mActivePasswordNumeric));
2170 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2171 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2172 out.endTag(null, "active-password");
2175 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2176 String component = policy.mLockTaskPackages.get(i);
2177 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2178 out.attribute(null, "name", component);
2179 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2182 if (policy.mStatusBarDisabled) {
2183 out.startTag(null, TAG_STATUS_BAR);
2184 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2185 out.endTag(null, TAG_STATUS_BAR);
2188 if (policy.doNotAskCredentialsOnBoot) {
2189 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2190 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2193 for (String id : policy.mAffiliationIds) {
2194 out.startTag(null, TAG_AFFILIATION_ID);
2195 out.attribute(null, "id", id);
2196 out.endTag(null, TAG_AFFILIATION_ID);
2199 if (policy.mAdminBroadcastPending) {
2200 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2201 out.attribute(null, ATTR_VALUE,
2202 Boolean.toString(policy.mAdminBroadcastPending));
2203 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2206 if (policy.mInitBundle != null) {
2207 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2208 policy.mInitBundle.saveToXml(out);
2209 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2212 out.endTag(null, "policies");
2216 FileUtils.sync(stream);
2219 sendChangedNotification(userHandle);
2220 } catch (XmlPullParserException | IOException e) {
2221 Slog.w(LOG_TAG, "failed writing file", e);
2223 if (stream != null) {
2226 } catch (IOException ex) {
2233 private void sendChangedNotification(int userHandle) {
2234 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2235 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2236 long ident = mInjector.binderClearCallingIdentity();
2238 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2240 mInjector.binderRestoreCallingIdentity(ident);
2244 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2245 JournaledFile journal = makeJournaledFile(userHandle);
2246 FileInputStream stream = null;
2247 File file = journal.chooseForRead();
2249 stream = new FileInputStream(file);
2250 XmlPullParser parser = Xml.newPullParser();
2251 parser.setInput(stream, StandardCharsets.UTF_8.name());
2254 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2255 && type != XmlPullParser.START_TAG) {
2257 String tag = parser.getName();
2258 if (!"policies".equals(tag)) {
2259 throw new XmlPullParserException(
2260 "Settings do not start with policies tag: found " + tag);
2263 // Extract the permission provider component name if available
2264 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2265 if (permissionProvider != null) {
2266 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2268 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2269 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2270 policy.mUserSetupComplete = true;
2272 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2273 if (!TextUtils.isEmpty(provisioningState)) {
2274 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2276 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2277 if (!TextUtils.isEmpty(permissionPolicy)) {
2278 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2280 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2281 ATTR_DELEGATED_CERT_INSTALLER);
2282 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2283 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2285 type = parser.next();
2286 int outerDepth = parser.getDepth();
2287 policy.mLockTaskPackages.clear();
2288 policy.mAdminList.clear();
2289 policy.mAdminMap.clear();
2290 policy.mAffiliationIds.clear();
2291 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2292 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2293 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2296 tag = parser.getName();
2297 if ("admin".equals(tag)) {
2298 String name = parser.getAttributeValue(null, "name");
2300 DeviceAdminInfo dai = findAdmin(
2301 ComponentName.unflattenFromString(name), userHandle,
2302 /* throwForMissionPermission= */ false);
2304 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2306 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2307 + dai.getActivityInfo().applicationInfo.uid + " for user "
2311 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2312 ap.readFromXml(parser);
2313 policy.mAdminMap.put(ap.info.getComponent(), ap);
2315 } catch (RuntimeException e) {
2316 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2318 } else if ("failed-password-attempts".equals(tag)) {
2319 policy.mFailedPasswordAttempts = Integer.parseInt(
2320 parser.getAttributeValue(null, "value"));
2321 } else if ("password-owner".equals(tag)) {
2322 policy.mPasswordOwner = Integer.parseInt(
2323 parser.getAttributeValue(null, "value"));
2324 } else if ("active-password".equals(tag)) {
2325 policy.mActivePasswordQuality = Integer.parseInt(
2326 parser.getAttributeValue(null, "quality"));
2327 policy.mActivePasswordLength = Integer.parseInt(
2328 parser.getAttributeValue(null, "length"));
2329 policy.mActivePasswordUpperCase = Integer.parseInt(
2330 parser.getAttributeValue(null, "uppercase"));
2331 policy.mActivePasswordLowerCase = Integer.parseInt(
2332 parser.getAttributeValue(null, "lowercase"));
2333 policy.mActivePasswordLetters = Integer.parseInt(
2334 parser.getAttributeValue(null, "letters"));
2335 policy.mActivePasswordNumeric = Integer.parseInt(
2336 parser.getAttributeValue(null, "numeric"));
2337 policy.mActivePasswordSymbols = Integer.parseInt(
2338 parser.getAttributeValue(null, "symbols"));
2339 policy.mActivePasswordNonLetter = Integer.parseInt(
2340 parser.getAttributeValue(null, "nonletter"));
2341 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2342 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2343 } else if (TAG_STATUS_BAR.equals(tag)) {
2344 policy.mStatusBarDisabled = Boolean.parseBoolean(
2345 parser.getAttributeValue(null, ATTR_DISABLED));
2346 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2347 policy.doNotAskCredentialsOnBoot = true;
2348 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2349 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2350 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2351 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2352 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2353 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2354 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2356 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2357 XmlUtils.skipCurrentTag(parser);
2360 } catch (FileNotFoundException e) {
2361 // Don't be noisy, this is normal if we haven't defined any policies.
2362 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2363 | IndexOutOfBoundsException e) {
2364 Slog.w(LOG_TAG, "failed parsing " + file, e);
2367 if (stream != null) {
2370 } catch (IOException e) {
2374 // Generate a list of admins from the admin map
2375 policy.mAdminList.addAll(policy.mAdminMap.values());
2377 // Validate that what we stored for the password quality matches
2378 // sufficiently what is currently set. Note that this is only
2379 // a sanity check in case the two get out of sync; this should
2380 // never normally happen.
2381 final long identity = mInjector.binderClearCallingIdentity();
2383 int actualPasswordQuality = mLockPatternUtils.getActivePasswordQuality(userHandle);
2384 if (actualPasswordQuality < policy.mActivePasswordQuality) {
2385 Slog.w(LOG_TAG, "Active password quality 0x"
2386 + Integer.toHexString(policy.mActivePasswordQuality)
2387 + " does not match actual quality 0x"
2388 + Integer.toHexString(actualPasswordQuality));
2389 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2390 policy.mActivePasswordLength = 0;
2391 policy.mActivePasswordUpperCase = 0;
2392 policy.mActivePasswordLowerCase = 0;
2393 policy.mActivePasswordLetters = 0;
2394 policy.mActivePasswordNumeric = 0;
2395 policy.mActivePasswordSymbols = 0;
2396 policy.mActivePasswordNonLetter = 0;
2399 mInjector.binderRestoreCallingIdentity(identity);
2402 validatePasswordOwnerLocked(policy);
2403 updateMaximumTimeToLockLocked(userHandle);
2404 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2405 if (policy.mStatusBarDisabled) {
2406 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2410 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2411 long ident = mInjector.binderClearCallingIdentity();
2413 mInjector.getIActivityManager()
2414 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2415 } catch (RemoteException e) {
2416 // Not gonna happen.
2418 mInjector.binderRestoreCallingIdentity(ident);
2422 private void updateDeviceOwnerLocked() {
2423 long ident = mInjector.binderClearCallingIdentity();
2425 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2426 // user id and also protect all other DAs too.
2427 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2428 if (deviceOwnerComponent != null) {
2429 mInjector.getIActivityManager()
2430 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2432 } catch (RemoteException e) {
2433 // Not gonna happen.
2435 mInjector.binderRestoreCallingIdentity(ident);
2439 static void validateQualityConstant(int quality) {
2441 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2442 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2443 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2444 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2445 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2446 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2447 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2448 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2449 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2452 throw new IllegalArgumentException("Invalid quality constant: 0x"
2453 + Integer.toHexString(quality));
2456 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2457 if (policy.mPasswordOwner >= 0) {
2458 boolean haveOwner = false;
2459 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2460 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2466 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2467 + " no longer active; disabling");
2468 policy.mPasswordOwner = -1;
2474 void systemReady(int phase) {
2479 case SystemService.PHASE_LOCK_SETTINGS_READY:
2480 onLockSettingsReady();
2482 case SystemService.PHASE_BOOT_COMPLETED:
2483 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2488 private void onLockSettingsReady() {
2489 getUserData(UserHandle.USER_SYSTEM);
2493 onStartUser(UserHandle.USER_SYSTEM);
2495 // Register an observer for watching for user setup complete.
2496 new SetupContentObserver(mHandler).register(mContext.getContentResolver());
2497 // Initialize the user setup state, to handle the upgrade case.
2498 updateUserSetupComplete();
2500 List<String> packageList;
2501 synchronized (this) {
2502 packageList = getKeepUninstalledPackagesLocked();
2504 if (packageList != null) {
2505 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2508 synchronized (this) {
2509 // push the force-ephemeral-users policy to the user manager.
2510 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2511 if (deviceOwner != null) {
2512 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2517 private void ensureDeviceOwnerUserStarted() {
2519 synchronized (this) {
2520 if (!mOwners.hasDeviceOwner()) {
2523 userId = mOwners.getDeviceOwnerUserId();
2526 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2528 if (userId != UserHandle.USER_SYSTEM) {
2530 mInjector.getIActivityManager().startUserInBackground(userId);
2532 // STOPSHIP Prevent the DO user from being killed.
2534 } catch (RemoteException e) {
2535 Slog.w(LOG_TAG, "Exception starting user", e);
2540 private void onStartUser(int userId) {
2541 updateScreenCaptureDisabledInWindowManager(userId,
2542 getScreenCaptureDisabled(null, userId));
2543 pushUserRestrictions(userId);
2546 private void cleanUpOldUsers() {
2547 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2549 Set<Integer> usersWithProfileOwners;
2550 Set<Integer> usersWithData;
2551 synchronized(this) {
2552 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2553 usersWithData = new ArraySet<>();
2554 for (int i = 0; i < mUserData.size(); i++) {
2555 usersWithData.add(mUserData.keyAt(i));
2558 List<UserInfo> allUsers = mUserManager.getUsers();
2560 Set<Integer> deletedUsers = new ArraySet<>();
2561 deletedUsers.addAll(usersWithProfileOwners);
2562 deletedUsers.addAll(usersWithData);
2563 for (UserInfo userInfo : allUsers) {
2564 deletedUsers.remove(userInfo.id);
2566 for (Integer userId : deletedUsers) {
2567 removeUserData(userId);
2571 private void handlePasswordExpirationNotification(int userHandle) {
2572 synchronized (this) {
2573 final long now = System.currentTimeMillis();
2575 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2576 userHandle, /* parent */ false);
2577 final int N = admins.size();
2578 for (int i = 0; i < N; i++) {
2579 ActiveAdmin admin = admins.get(i);
2580 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2581 && admin.passwordExpirationTimeout > 0L
2582 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2583 && admin.passwordExpirationDate > 0L) {
2584 sendAdminCommandLocked(admin,
2585 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2588 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2592 private class MonitoringCertNotificationTask extends AsyncTask<Intent, Void, Void> {
2594 protected Void doInBackground(Intent... params) {
2595 int userHandle = params[0].getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
2597 if (userHandle == UserHandle.USER_ALL) {
2598 for (UserInfo userInfo : mUserManager.getUsers()) {
2599 manageNotification(userInfo.getUserHandle());
2602 manageNotification(new UserHandle(userHandle));
2607 private void manageNotification(UserHandle userHandle) {
2608 if (!mUserManager.isUserRunning(userHandle)) {
2612 // Call out to KeyChain to check for user-added CAs
2613 boolean hasCert = false;
2615 KeyChainConnection kcs = KeyChain.bindAsUser(mContext, userHandle);
2617 if (!kcs.getService().getUserCaAliases().getList().isEmpty()) {
2620 } catch (RemoteException e) {
2621 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
2625 } catch (InterruptedException e) {
2626 Thread.currentThread().interrupt();
2627 } catch (RuntimeException e) {
2628 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
2631 mInjector.getNotificationManager().cancelAsUser(
2632 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2636 // Build and show a warning notification
2639 // TODO Why does it use the DO name? The cert APIs are all for PO. b/25772443
2640 final String ownerName = getDeviceOwnerName();
2641 if (isManagedProfile(userHandle.getIdentifier())) {
2642 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_administrator);
2643 smallIconId = R.drawable.stat_sys_certificate_info;
2644 } else if (ownerName != null) {
2645 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, ownerName);
2646 smallIconId = R.drawable.stat_sys_certificate_info;
2648 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2649 smallIconId = android.R.drawable.stat_sys_warning;
2652 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2653 dialogIntent.setFlags(
2654 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2655 dialogIntent.setPackage("com.android.settings");
2656 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2657 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, userHandle);
2659 final Context userContext;
2661 userContext = mContext.createPackageContextAsUser("android", 0, userHandle);
2662 } catch (PackageManager.NameNotFoundException e) {
2663 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2666 final Notification noti = new Notification.Builder(userContext)
2667 .setSmallIcon(smallIconId)
2668 .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning))
2669 .setContentText(contentText)
2670 .setContentIntent(notifyIntent)
2671 .setPriority(Notification.PRIORITY_HIGH)
2673 .setColor(mContext.getColor(
2674 com.android.internal.R.color.system_notification_accent_color))
2677 mInjector.getNotificationManager().notifyAsUser(
2678 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2683 * @param adminReceiver The admin to add
2684 * @param refreshing true = update an active admin, no error
2687 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2691 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2694 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2695 Bundle onEnableData) {
2696 mContext.enforceCallingOrSelfPermission(
2697 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2698 enforceFullCrossUsersPermission(userHandle);
2700 DevicePolicyData policy = getUserData(userHandle);
2701 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2702 /* throwForMissionPermission= */ true);
2704 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2706 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2707 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2710 synchronized (this) {
2711 long ident = mInjector.binderClearCallingIdentity();
2714 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
2715 throw new IllegalArgumentException("Admin is already added");
2717 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2718 policy.mAdminMap.put(adminReceiver, newAdmin);
2719 int replaceIndex = -1;
2720 final int N = policy.mAdminList.size();
2721 for (int i=0; i < N; i++) {
2722 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2723 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2728 if (replaceIndex == -1) {
2729 policy.mAdminList.add(newAdmin);
2730 enableIfNecessary(info.getPackageName(), userHandle);
2732 policy.mAdminList.set(replaceIndex, newAdmin);
2734 saveSettingsLocked(userHandle);
2735 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2736 onEnableData, null);
2738 mInjector.binderRestoreCallingIdentity(ident);
2744 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2748 enforceFullCrossUsersPermission(userHandle);
2749 synchronized (this) {
2750 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2755 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2759 enforceFullCrossUsersPermission(userHandle);
2760 synchronized (this) {
2761 DevicePolicyData policyData = getUserData(userHandle);
2762 return policyData.mRemovingAdmins.contains(adminReceiver);
2767 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2771 enforceFullCrossUsersPermission(userHandle);
2772 synchronized (this) {
2773 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2774 if (administrator == null) {
2775 throw new SecurityException("No active admin " + adminReceiver);
2777 return administrator.info.usesPolicy(policyId);
2782 @SuppressWarnings("unchecked")
2783 public List<ComponentName> getActiveAdmins(int userHandle) {
2785 return Collections.EMPTY_LIST;
2788 enforceFullCrossUsersPermission(userHandle);
2789 synchronized (this) {
2790 DevicePolicyData policy = getUserData(userHandle);
2791 final int N = policy.mAdminList.size();
2795 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2796 for (int i=0; i<N; i++) {
2797 res.add(policy.mAdminList.get(i).info.getComponent());
2804 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2808 enforceFullCrossUsersPermission(userHandle);
2809 synchronized (this) {
2810 DevicePolicyData policy = getUserData(userHandle);
2811 final int N = policy.mAdminList.size();
2812 for (int i=0; i<N; i++) {
2813 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2822 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
2826 enforceFullCrossUsersPermission(userHandle);
2827 enforceUserUnlocked(userHandle);
2828 synchronized (this) {
2829 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2830 if (admin == null) {
2833 // Active device/profile owners must remain active admins.
2834 if (isDeviceOwner(adminReceiver, userHandle)
2835 || isProfileOwner(adminReceiver, userHandle)) {
2836 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
2840 if (admin.getUid() != mInjector.binderGetCallingUid()) {
2841 mContext.enforceCallingOrSelfPermission(
2842 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2844 long ident = mInjector.binderClearCallingIdentity();
2846 removeActiveAdminLocked(adminReceiver, userHandle);
2848 mInjector.binderRestoreCallingIdentity(ident);
2854 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
2855 ComponentName profileOwner = getProfileOwner(userHandle);
2857 // Profile challenge is supported on N or newer release.
2858 return profileOwner != null &&
2859 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
2860 } catch (RemoteException e) {
2866 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
2870 Preconditions.checkNotNull(who, "ComponentName is null");
2871 validateQualityConstant(quality);
2873 synchronized (this) {
2874 ActiveAdmin ap = getActiveAdminForCallerLocked(
2875 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
2876 if (ap.passwordQuality != quality) {
2877 ap.passwordQuality = quality;
2878 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
2884 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
2886 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2888 enforceFullCrossUsersPermission(userHandle);
2889 synchronized (this) {
2890 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2893 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
2894 return admin != null ? admin.passwordQuality : mode;
2897 // Return the strictest policy across all participating admins.
2898 List<ActiveAdmin> admins =
2899 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
2900 final int N = admins.size();
2901 for (int i = 0; i < N; i++) {
2902 ActiveAdmin admin = admins.get(i);
2903 if (mode < admin.passwordQuality) {
2904 mode = admin.passwordQuality;
2911 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
2912 int userHandle, boolean parent) {
2913 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
2914 // If this user has a separate challenge, only return its restrictions.
2915 return getUserDataUnchecked(userHandle).mAdminList;
2917 // Return all admins for this user and the profiles that are visible from this
2918 // user that do not use a separate work challenge.
2919 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
2920 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
2921 DevicePolicyData policy = getUserData(userInfo.id);
2922 if (!isManagedProfile(userInfo.id)) {
2923 admins.addAll(policy.mAdminList);
2925 // For managed profiles, we always include the policies set on the parent
2926 // profile. Additionally, we include the ones set on the managed profile
2927 // if no separate challenge is in place.
2928 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
2929 final int N = policy.mAdminList.size();
2930 for (int i = 0; i < N; i++) {
2931 ActiveAdmin admin = policy.mAdminList.get(i);
2932 if (admin.hasParentActiveAdmin()) {
2933 admins.add(admin.getParentActiveAdmin());
2935 if (!hasSeparateChallenge) {
2945 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
2946 long ident = mInjector.binderClearCallingIdentity();
2948 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
2950 mInjector.binderRestoreCallingIdentity(ident);
2955 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
2959 Preconditions.checkNotNull(who, "ComponentName is null");
2960 synchronized (this) {
2961 ActiveAdmin ap = getActiveAdminForCallerLocked(
2962 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
2963 if (ap.minimumPasswordLength != length) {
2964 ap.minimumPasswordLength = length;
2965 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
2971 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
2975 enforceFullCrossUsersPermission(userHandle);
2976 synchronized (this) {
2980 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
2981 return admin != null ? admin.minimumPasswordLength : length;
2984 // Return the strictest policy across all participating admins.
2985 List<ActiveAdmin> admins =
2986 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
2987 final int N = admins.size();
2988 for (int i = 0; i < N; i++) {
2989 ActiveAdmin admin = admins.get(i);
2990 if (length < admin.minimumPasswordLength) {
2991 length = admin.minimumPasswordLength;
2999 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3003 Preconditions.checkNotNull(who, "ComponentName is null");
3004 synchronized (this) {
3005 ActiveAdmin ap = getActiveAdminForCallerLocked(
3006 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3007 if (ap.passwordHistoryLength != length) {
3008 ap.passwordHistoryLength = length;
3009 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3015 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3019 enforceFullCrossUsersPermission(userHandle);
3020 synchronized (this) {
3024 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3025 return admin != null ? admin.passwordHistoryLength : length;
3028 // Return the strictest policy across all participating admins.
3029 List<ActiveAdmin> admins =
3030 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3031 final int N = admins.size();
3032 for (int i = 0; i < N; i++) {
3033 ActiveAdmin admin = admins.get(i);
3034 if (length < admin.passwordHistoryLength) {
3035 length = admin.passwordHistoryLength;
3044 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3048 Preconditions.checkNotNull(who, "ComponentName is null");
3049 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3050 final int userHandle = mInjector.userHandleGetCallingUserId();
3051 synchronized (this) {
3052 ActiveAdmin ap = getActiveAdminForCallerLocked(
3053 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3054 // Calling this API automatically bumps the expiration date
3055 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3056 ap.passwordExpirationDate = expiration;
3057 ap.passwordExpirationTimeout = timeout;
3059 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3060 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3061 .format(new Date(expiration)));
3063 saveSettingsLocked(userHandle);
3065 // in case this is the first one, set the alarm on the appropriate user.
3066 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3071 * Return a single admin's expiration cycle time, or the min of all cycle times.
3072 * Returns 0 if not configured.
3075 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3079 enforceFullCrossUsersPermission(userHandle);
3080 synchronized (this) {
3084 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3085 return admin != null ? admin.passwordExpirationTimeout : timeout;
3088 // Return the strictest policy across all participating admins.
3089 List<ActiveAdmin> admins =
3090 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3091 final int N = admins.size();
3092 for (int i = 0; i < N; i++) {
3093 ActiveAdmin admin = admins.get(i);
3094 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3095 && timeout > admin.passwordExpirationTimeout)) {
3096 timeout = admin.passwordExpirationTimeout;
3104 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3105 final int userId = UserHandle.getCallingUserId();
3106 List<String> changedProviders = null;
3108 synchronized (this) {
3109 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3110 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3111 if (activeAdmin.crossProfileWidgetProviders == null) {
3112 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3114 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3115 if (!providers.contains(packageName)) {
3116 providers.add(packageName);
3117 changedProviders = new ArrayList<>(providers);
3118 saveSettingsLocked(userId);
3122 if (changedProviders != null) {
3123 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3131 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3132 final int userId = UserHandle.getCallingUserId();
3133 List<String> changedProviders = null;
3135 synchronized (this) {
3136 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3137 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3138 if (activeAdmin.crossProfileWidgetProviders == null) {
3141 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3142 if (providers.remove(packageName)) {
3143 changedProviders = new ArrayList<>(providers);
3144 saveSettingsLocked(userId);
3148 if (changedProviders != null) {
3149 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3157 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3158 synchronized (this) {
3159 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3160 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3161 if (activeAdmin.crossProfileWidgetProviders == null
3162 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3165 if (mInjector.binderIsCallingUidMyUid()) {
3166 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3168 return activeAdmin.crossProfileWidgetProviders;
3174 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3175 * Returns 0 if not configured.
3177 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3181 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3182 return admin != null ? admin.passwordExpirationDate : timeout;
3185 // Return the strictest policy across all participating admins.
3186 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3187 final int N = admins.size();
3188 for (int i = 0; i < N; i++) {
3189 ActiveAdmin admin = admins.get(i);
3190 if (timeout == 0L || (admin.passwordExpirationDate != 0
3191 && timeout > admin.passwordExpirationDate)) {
3192 timeout = admin.passwordExpirationDate;
3199 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3203 enforceFullCrossUsersPermission(userHandle);
3204 synchronized (this) {
3205 return getPasswordExpirationLocked(who, userHandle, parent);
3210 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3214 Preconditions.checkNotNull(who, "ComponentName is null");
3215 synchronized (this) {
3216 ActiveAdmin ap = getActiveAdminForCallerLocked(
3217 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3218 if (ap.minimumPasswordUpperCase != length) {
3219 ap.minimumPasswordUpperCase = length;
3220 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3226 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3230 enforceFullCrossUsersPermission(userHandle);
3231 synchronized (this) {
3235 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3236 return admin != null ? admin.minimumPasswordUpperCase : length;
3239 // Return the strictest policy across all participating admins.
3240 List<ActiveAdmin> admins =
3241 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3242 final int N = admins.size();
3243 for (int i = 0; i < N; i++) {
3244 ActiveAdmin admin = admins.get(i);
3245 if (length < admin.minimumPasswordUpperCase) {
3246 length = admin.minimumPasswordUpperCase;
3254 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3255 Preconditions.checkNotNull(who, "ComponentName is null");
3256 synchronized (this) {
3257 ActiveAdmin ap = getActiveAdminForCallerLocked(
3258 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3259 if (ap.minimumPasswordLowerCase != length) {
3260 ap.minimumPasswordLowerCase = length;
3261 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3267 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3271 enforceFullCrossUsersPermission(userHandle);
3272 synchronized (this) {
3276 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3277 return admin != null ? admin.minimumPasswordLowerCase : length;
3280 // Return the strictest policy across all participating admins.
3281 List<ActiveAdmin> admins =
3282 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3283 final int N = admins.size();
3284 for (int i = 0; i < N; i++) {
3285 ActiveAdmin admin = admins.get(i);
3286 if (length < admin.minimumPasswordLowerCase) {
3287 length = admin.minimumPasswordLowerCase;
3295 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3299 Preconditions.checkNotNull(who, "ComponentName is null");
3300 synchronized (this) {
3301 ActiveAdmin ap = getActiveAdminForCallerLocked(
3302 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3303 if (ap.minimumPasswordLetters != length) {
3304 ap.minimumPasswordLetters = length;
3305 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3311 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3315 enforceFullCrossUsersPermission(userHandle);
3316 synchronized (this) {
3320 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3321 return admin != null ? admin.minimumPasswordLetters : length;
3324 // Return the strictest policy across all participating admins.
3325 List<ActiveAdmin> admins =
3326 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3327 final int N = admins.size();
3328 for (int i = 0; i < N; i++) {
3329 ActiveAdmin admin = admins.get(i);
3330 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3333 if (length < admin.minimumPasswordLetters) {
3334 length = admin.minimumPasswordLetters;
3342 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3346 Preconditions.checkNotNull(who, "ComponentName is null");
3347 synchronized (this) {
3348 ActiveAdmin ap = getActiveAdminForCallerLocked(
3349 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3350 if (ap.minimumPasswordNumeric != length) {
3351 ap.minimumPasswordNumeric = length;
3352 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3358 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3362 enforceFullCrossUsersPermission(userHandle);
3363 synchronized (this) {
3367 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3368 return admin != null ? admin.minimumPasswordNumeric : length;
3371 // Return the strictest policy across all participating admins.
3372 List<ActiveAdmin> admins =
3373 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3374 final int N = admins.size();
3375 for (int i = 0; i < N; i++) {
3376 ActiveAdmin admin = admins.get(i);
3377 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3380 if (length < admin.minimumPasswordNumeric) {
3381 length = admin.minimumPasswordNumeric;
3389 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3393 Preconditions.checkNotNull(who, "ComponentName is null");
3394 synchronized (this) {
3395 ActiveAdmin ap = getActiveAdminForCallerLocked(
3396 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3397 if (ap.minimumPasswordSymbols != length) {
3398 ap.minimumPasswordSymbols = length;
3399 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3405 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3409 enforceFullCrossUsersPermission(userHandle);
3410 synchronized (this) {
3414 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3415 return admin != null ? admin.minimumPasswordSymbols : length;
3418 // Return the strictest policy across all participating admins.
3419 List<ActiveAdmin> admins =
3420 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3421 final int N = admins.size();
3422 for (int i = 0; i < N; i++) {
3423 ActiveAdmin admin = admins.get(i);
3424 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3427 if (length < admin.minimumPasswordSymbols) {
3428 length = admin.minimumPasswordSymbols;
3436 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3440 Preconditions.checkNotNull(who, "ComponentName is null");
3441 synchronized (this) {
3442 ActiveAdmin ap = getActiveAdminForCallerLocked(
3443 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3444 if (ap.minimumPasswordNonLetter != length) {
3445 ap.minimumPasswordNonLetter = length;
3446 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3452 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3456 enforceFullCrossUsersPermission(userHandle);
3457 synchronized (this) {
3461 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3462 return admin != null ? admin.minimumPasswordNonLetter : length;
3465 // Return the strictest policy across all participating admins.
3466 List<ActiveAdmin> admins =
3467 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3468 final int N = admins.size();
3469 for (int i = 0; i < N; i++) {
3470 ActiveAdmin admin = admins.get(i);
3471 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3474 if (length < admin.minimumPasswordNonLetter) {
3475 length = admin.minimumPasswordNonLetter;
3483 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3487 enforceFullCrossUsersPermission(userHandle);
3489 synchronized (this) {
3490 // This API can only be called by an active device admin,
3491 // so try to retrieve it to check that the caller is one.
3492 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3493 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3494 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3499 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3503 enforceFullCrossUsersPermission(userHandle);
3504 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3506 synchronized (this) {
3507 int targetUser = getProfileParentId(userHandle);
3508 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3509 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3513 private boolean isActivePasswordSufficientForUserLocked(
3514 DevicePolicyData policy, int userHandle, boolean parent) {
3515 if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle, parent)
3516 || policy.mActivePasswordLength < getPasswordMinimumLength(
3517 null, userHandle, parent)) {
3520 if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3523 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3524 null, userHandle, parent)
3525 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3526 null, userHandle, parent)
3527 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3528 null, userHandle, parent)
3529 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3530 null, userHandle, parent)
3531 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3532 null, userHandle, parent)
3533 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3534 null, userHandle, parent);
3538 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3539 enforceFullCrossUsersPermission(userHandle);
3540 synchronized (this) {
3541 if (!isCallerWithSystemUid()) {
3542 // This API can only be called by an active device admin,
3543 // so try to retrieve it to check that the caller is one.
3544 getActiveAdminForCallerLocked(
3545 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3548 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3550 return policy.mFailedPasswordAttempts;
3555 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3559 Preconditions.checkNotNull(who, "ComponentName is null");
3560 synchronized (this) {
3561 // This API can only be called by an active device admin,
3562 // so try to retrieve it to check that the caller is one.
3563 getActiveAdminForCallerLocked(
3564 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3565 ActiveAdmin ap = getActiveAdminForCallerLocked(
3566 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3567 if (ap.maximumFailedPasswordsForWipe != num) {
3568 ap.maximumFailedPasswordsForWipe = num;
3569 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3575 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3579 enforceFullCrossUsersPermission(userHandle);
3580 synchronized (this) {
3581 ActiveAdmin admin = (who != null)
3582 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3583 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3584 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3589 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3591 return UserHandle.USER_NULL;
3593 enforceFullCrossUsersPermission(userHandle);
3594 synchronized (this) {
3595 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3596 userHandle, parent);
3597 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3602 * Returns the admin with the strictest policy on maximum failed passwords for:
3604 * <li>this user if it has a separate profile challenge, or
3605 * <li>this user and all profiles that don't have their own challenge otherwise.
3607 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3608 * the primary profile.
3609 * Returns {@code null} if no participating admin has that policy set.
3611 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3612 int userHandle, boolean parent) {
3614 ActiveAdmin strictestAdmin = null;
3616 // Return the strictest policy across all participating admins.
3617 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3618 final int N = admins.size();
3619 for (int i = 0; i < N; i++) {
3620 ActiveAdmin admin = admins.get(i);
3621 if (admin.maximumFailedPasswordsForWipe ==
3622 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3623 continue; // No max number of failed passwords policy set for this profile.
3626 // We always favor the primary profile if several profiles have the same value set.
3627 int userId = admin.getUserHandle().getIdentifier();
3629 count > admin.maximumFailedPasswordsForWipe ||
3630 (count == admin.maximumFailedPasswordsForWipe &&
3631 mUserManager.getUserInfo(userId).isPrimary())) {
3632 count = admin.maximumFailedPasswordsForWipe;
3633 strictestAdmin = admin;
3636 return strictestAdmin;
3640 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3644 final int callingUid = mInjector.binderGetCallingUid();
3645 final int userHandle = mInjector.userHandleGetCallingUserId();
3647 if (getCredentialOwner(userHandle, /* parent */ false) != userHandle) {
3648 throw new SecurityException("You can not change password for this profile because"
3649 + " it shares the password with the owner profile");
3652 String password = passwordOrNull != null ? passwordOrNull : "";
3655 synchronized (this) {
3656 // If caller has PO (or DO), it can clear the password, so see if that's the case
3658 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3659 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3660 if (admin == null) {
3661 // Otherwise, make sure the caller has any active admin with the right policy.
3662 admin = getActiveAdminForCallerLocked(null,
3663 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3666 final ComponentName adminComponent = admin.info.getComponent();
3668 // As of N, only profile owners and device owners can reset the password.
3669 if (!(isProfileOwner(adminComponent, userHandle)
3670 || isDeviceOwner(adminComponent, userHandle))) {
3671 final boolean preN = getTargetSdk(admin.info.getPackageName(), userHandle)
3672 <= android.os.Build.VERSION_CODES.M;
3673 // As of N, password resetting to empty/null is not allowed anymore.
3674 // TODO Should we allow DO/PO to set an empty password?
3675 if (TextUtils.isEmpty(password)) {
3677 throw new SecurityException("Cannot call with null password");
3679 Slog.e(LOG_TAG, "Cannot call with null password");
3683 // As of N, password cannot be changed by the admin if it is already set.
3684 if (isLockScreenSecureUnchecked(userHandle)) {
3686 throw new SecurityException("Admin cannot change current password");
3688 Slog.e(LOG_TAG, "Admin cannot change current password");
3693 quality = getPasswordQuality(null, userHandle, /* parent */ false);
3694 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
3695 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3697 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
3698 int realQuality = LockPatternUtils.computePasswordQuality(password);
3699 if (realQuality < quality
3700 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3701 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
3702 + Integer.toHexString(realQuality)
3703 + " does not meet required quality 0x"
3704 + Integer.toHexString(quality));
3707 quality = Math.max(realQuality, quality);
3709 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
3710 if (password.length() < length) {
3711 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
3712 + " does not meet required length " + length);
3715 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3722 for (int i = 0; i < password.length(); i++) {
3723 char c = password.charAt(i);
3724 if (c >= 'A' && c <= 'Z') {
3727 } else if (c >= 'a' && c <= 'z') {
3730 } else if (c >= '0' && c <= '9') {
3738 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
3739 if(letters < neededLetters) {
3740 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
3741 + " does not meet required number of letters " + neededLetters);
3744 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
3745 if (numbers < neededNumbers) {
3746 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
3747 + " does not meet required number of numerical digits "
3751 int neededLowerCase = getPasswordMinimumLowerCase(
3752 null, userHandle, /* parent */ false);
3753 if (lowercase < neededLowerCase) {
3754 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
3755 + " does not meet required number of lowercase letters "
3759 int neededUpperCase = getPasswordMinimumUpperCase(
3760 null, userHandle, /* parent */ false);
3761 if (uppercase < neededUpperCase) {
3762 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
3763 + " does not meet required number of uppercase letters "
3767 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
3768 if (symbols < neededSymbols) {
3769 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
3770 + " does not meet required number of special symbols " + neededSymbols);
3773 int neededNonLetter = getPasswordMinimumNonLetter(
3774 null, userHandle, /* parent */ false);
3775 if (nonletter < neededNonLetter) {
3776 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
3777 + " does not meet required number of non-letter characters "
3784 DevicePolicyData policy = getUserData(userHandle);
3785 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
3786 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
3790 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
3791 boolean doNotAskCredentialsOnBoot =
3792 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
3793 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
3794 setDoNotAskCredentialsOnBoot();
3797 // Don't do this with the lock held, because it is going to call
3798 // back in to the service.
3799 final long ident = mInjector.binderClearCallingIdentity();
3801 if (!TextUtils.isEmpty(password)) {
3802 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
3804 mLockPatternUtils.clearLock(userHandle);
3806 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
3808 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
3809 UserHandle.USER_ALL);
3811 synchronized (this) {
3812 int newOwner = requireEntry ? callingUid : -1;
3813 if (policy.mPasswordOwner != newOwner) {
3814 policy.mPasswordOwner = newOwner;
3815 saveSettingsLocked(userHandle);
3819 mInjector.binderRestoreCallingIdentity(ident);
3825 private boolean isLockScreenSecureUnchecked(int userId) {
3826 long ident = mInjector.binderClearCallingIdentity();
3828 return mLockPatternUtils.isSecure(userId);
3830 mInjector.binderRestoreCallingIdentity(ident);
3834 private void setDoNotAskCredentialsOnBoot() {
3835 synchronized (this) {
3836 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
3837 if (!policyData.doNotAskCredentialsOnBoot) {
3838 policyData.doNotAskCredentialsOnBoot = true;
3839 saveSettingsLocked(UserHandle.USER_SYSTEM);
3845 public boolean getDoNotAskCredentialsOnBoot() {
3846 mContext.enforceCallingOrSelfPermission(
3847 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
3848 synchronized (this) {
3849 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
3850 return policyData.doNotAskCredentialsOnBoot;
3855 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
3859 Preconditions.checkNotNull(who, "ComponentName is null");
3860 final int userHandle = mInjector.userHandleGetCallingUserId();
3861 synchronized (this) {
3862 ActiveAdmin ap = getActiveAdminForCallerLocked(
3863 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
3864 if (ap.maximumTimeToUnlock != timeMs) {
3865 ap.maximumTimeToUnlock = timeMs;
3866 saveSettingsLocked(userHandle);
3867 updateMaximumTimeToLockLocked(userHandle);
3872 void updateMaximumTimeToLockLocked(int userHandle) {
3873 // Calculate the min timeout for all profiles - including the ones with a separate
3874 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
3875 // challenge only and keep the screen on. However there is no easy way of doing that at the
3876 // moment so we set the screen off timeout regardless of whether it affects the parent user
3877 // or the profile challenge only.
3878 long timeMs = Long.MAX_VALUE;
3879 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3880 for (UserInfo userInfo : profiles) {
3881 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
3882 final int N = policy.mAdminList.size();
3883 for (int i = 0; i < N; i++) {
3884 ActiveAdmin admin = policy.mAdminList.get(i);
3885 if (admin.maximumTimeToUnlock > 0
3886 && timeMs > admin.maximumTimeToUnlock) {
3887 timeMs = admin.maximumTimeToUnlock;
3892 // We only store the last maximum time to lock on the parent profile. So if calling from a
3893 // managed profile, retrieve the policy for the parent.
3894 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
3895 if (policy.mLastMaximumTimeToLock == timeMs) {
3898 policy.mLastMaximumTimeToLock = timeMs;
3900 final long ident = mInjector.binderClearCallingIdentity();
3902 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
3903 // Make sure KEEP_SCREEN_ON is disabled, since that
3904 // would allow bypassing of the maximum time to lock.
3905 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
3908 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
3909 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
3911 mInjector.binderRestoreCallingIdentity(ident);
3916 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
3920 enforceFullCrossUsersPermission(userHandle);
3921 synchronized (this) {
3925 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3926 return admin != null ? admin.maximumTimeToUnlock : time;
3929 // Return the strictest policy across all participating admins.
3930 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
3931 userHandle, parent);
3932 final int N = admins.size();
3933 for (int i = 0; i < N; i++) {
3934 ActiveAdmin admin = admins.get(i);
3936 time = admin.maximumTimeToUnlock;
3937 } else if (admin.maximumTimeToUnlock != 0
3938 && time > admin.maximumTimeToUnlock) {
3939 time = admin.maximumTimeToUnlock;
3947 public void lockNow(boolean parent) {
3951 synchronized (this) {
3952 // This API can only be called by an active device admin,
3953 // so try to retrieve it to check that the caller is one.
3954 getActiveAdminForCallerLocked(
3955 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
3957 int userToLock = mInjector.userHandleGetCallingUserId();
3959 // Unless this is a managed profile with work challenge enabled, lock all users.
3960 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
3961 userToLock = UserHandle.USER_ALL;
3963 final long ident = mInjector.binderClearCallingIdentity();
3965 mLockPatternUtils.requireStrongAuth(
3966 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
3967 if (userToLock == UserHandle.USER_ALL) {
3968 // Power off the display
3969 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
3970 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
3971 mInjector.getIWindowManager().lockNow(null);
3973 } catch (RemoteException e) {
3975 mInjector.binderRestoreCallingIdentity(ident);
3981 public void enforceCanManageCaCerts(ComponentName who) {
3983 if (!isCallerDelegatedCertInstaller()) {
3984 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
3987 synchronized (this) {
3988 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3993 private void enforceCanManageInstalledKeys(ComponentName who) {
3995 if (!isCallerDelegatedCertInstaller()) {
3996 throw new SecurityException("who == null, but caller is not cert installer");
3999 synchronized (this) {
4000 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4005 private boolean isCallerDelegatedCertInstaller() {
4006 final int callingUid = mInjector.binderGetCallingUid();
4007 final int userHandle = UserHandle.getUserId(callingUid);
4008 synchronized (this) {
4009 final DevicePolicyData policy = getUserData(userHandle);
4010 if (policy.mDelegatedCertInstallerPackage == null) {
4015 int uid = mContext.getPackageManager().getPackageUidAsUser(
4016 policy.mDelegatedCertInstallerPackage, userHandle);
4017 return uid == callingUid;
4018 } catch (NameNotFoundException e) {
4025 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4026 enforceCanManageCaCerts(admin);
4030 X509Certificate cert = parseCert(certBuffer);
4031 pemCert = Credentials.convertToPem(cert);
4032 } catch (CertificateException ce) {
4033 Log.e(LOG_TAG, "Problem converting cert", ce);
4035 } catch (IOException ioe) {
4036 Log.e(LOG_TAG, "Problem reading cert", ioe);
4040 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4041 final long id = mInjector.binderClearCallingIdentity();
4043 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4045 keyChainConnection.getService().installCaCertificate(pemCert);
4047 } catch (RemoteException e) {
4048 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4050 keyChainConnection.close();
4052 } catch (InterruptedException e1) {
4053 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4054 Thread.currentThread().interrupt();
4056 mInjector.binderRestoreCallingIdentity(id);
4061 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4062 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4063 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4068 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4069 enforceCanManageCaCerts(admin);
4071 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4072 final long id = mInjector.binderClearCallingIdentity();
4074 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4076 for (int i = 0 ; i < aliases.length; i++) {
4077 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4079 } catch (RemoteException e) {
4080 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4082 keyChainConnection.close();
4084 } catch (InterruptedException ie) {
4085 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4086 Thread.currentThread().interrupt();
4088 mInjector.binderRestoreCallingIdentity(id);
4093 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, String alias,
4094 boolean requestAccess) {
4095 enforceCanManageInstalledKeys(who);
4097 final int callingUid = mInjector.binderGetCallingUid();
4098 final long id = mInjector.binderClearCallingIdentity();
4100 final KeyChainConnection keyChainConnection =
4101 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4103 IKeyChainService keyChain = keyChainConnection.getService();
4104 if (!keyChain.installKeyPair(privKey, cert, alias)) {
4107 if (requestAccess) {
4108 keyChain.setGrant(callingUid, alias, true);
4111 } catch (RemoteException e) {
4112 Log.e(LOG_TAG, "Installing certificate", e);
4114 keyChainConnection.close();
4116 } catch (InterruptedException e) {
4117 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4118 Thread.currentThread().interrupt();
4120 mInjector.binderRestoreCallingIdentity(id);
4126 public boolean removeKeyPair(ComponentName who, String alias) {
4127 enforceCanManageInstalledKeys(who);
4129 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4130 final long id = Binder.clearCallingIdentity();
4132 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4134 IKeyChainService keyChain = keyChainConnection.getService();
4135 return keyChain.removeKeyPair(alias);
4136 } catch (RemoteException e) {
4137 Log.e(LOG_TAG, "Removing keypair", e);
4139 keyChainConnection.close();
4141 } catch (InterruptedException e) {
4142 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4143 Thread.currentThread().interrupt();
4145 Binder.restoreCallingIdentity(id);
4151 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4152 final IBinder response) {
4153 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4154 if (!isCallerWithSystemUid()) {
4158 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4159 // If there is a profile owner, redirect to that; otherwise query the device owner.
4160 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4161 if (aliasChooser == null && caller.isSystem()) {
4162 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4163 if (deviceOwnerAdmin != null) {
4164 aliasChooser = deviceOwnerAdmin.info.getComponent();
4167 if (aliasChooser == null) {
4168 sendPrivateKeyAliasResponse(null, response);
4172 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4173 intent.setComponent(aliasChooser);
4174 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4175 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4176 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4177 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4179 final long id = mInjector.binderClearCallingIdentity();
4181 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4183 public void onReceive(Context context, Intent intent) {
4184 final String chosenAlias = getResultData();
4185 sendPrivateKeyAliasResponse(chosenAlias, response);
4187 }, null, Activity.RESULT_OK, null, null);
4189 mInjector.binderRestoreCallingIdentity(id);
4193 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4194 final IKeyChainAliasCallback keyChainAliasResponse =
4195 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4196 new AsyncTask<Void, Void, Void>() {
4198 protected Void doInBackground(Void... unused) {
4200 keyChainAliasResponse.alias(alias);
4201 } catch (Exception e) {
4202 // Catch everything (not just RemoteException): caller could throw a
4203 // RuntimeException back across processes.
4204 Log.e(LOG_TAG, "error while responding to callback", e);
4212 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4213 throws SecurityException {
4214 int userHandle = UserHandle.getCallingUserId();
4215 synchronized (this) {
4216 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4218 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4219 if (installerPackage != null &&
4220 !isPackageInstalledForUser(installerPackage, userHandle)) {
4221 throw new IllegalArgumentException("Package " + installerPackage
4222 + " is not installed on the current user");
4225 } catch (RemoteException e) {
4227 DevicePolicyData policy = getUserData(userHandle);
4228 policy.mDelegatedCertInstallerPackage = installerPackage;
4229 saveSettingsLocked(userHandle);
4234 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4235 int userHandle = UserHandle.getCallingUserId();
4236 synchronized (this) {
4237 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4238 DevicePolicyData policy = getUserData(userHandle);
4239 return policy.mDelegatedCertInstallerPackage;
4244 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage)
4245 throws SecurityException {
4246 synchronized (this) {
4247 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4250 final int userId = mInjector.userHandleGetCallingUserId();
4251 final long token = mInjector.binderClearCallingIdentity();
4253 ConnectivityManager connectivityManager = (ConnectivityManager)
4254 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4255 return connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage);
4257 mInjector.binderRestoreCallingIdentity(token);
4262 public String getAlwaysOnVpnPackage(ComponentName admin)
4263 throws SecurityException {
4264 synchronized (this) {
4265 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4268 final int userId = mInjector.userHandleGetCallingUserId();
4269 final long token = mInjector.binderClearCallingIdentity();
4271 ConnectivityManager connectivityManager = (ConnectivityManager)
4272 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4273 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4275 mInjector.binderRestoreCallingIdentity(token);
4279 private void wipeDataLocked(boolean wipeExtRequested, String reason) {
4280 if (wipeExtRequested) {
4281 StorageManager sm = (StorageManager) mContext.getSystemService(
4282 Context.STORAGE_SERVICE);
4283 sm.wipeAdoptableDisks();
4286 RecoverySystem.rebootWipeUserData(mContext, reason);
4287 } catch (IOException | SecurityException e) {
4288 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4293 public void wipeData(int flags) {
4297 final int userHandle = mInjector.userHandleGetCallingUserId();
4298 enforceFullCrossUsersPermission(userHandle);
4299 synchronized (this) {
4300 // This API can only be called by an active device admin,
4301 // so try to retrieve it to check that the caller is one.
4302 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4303 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4305 final String source = admin.info.getComponent().flattenToShortString();
4307 long ident = mInjector.binderClearCallingIdentity();
4309 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4310 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4311 throw new SecurityException(
4312 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4314 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4315 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4316 if (manager != null) {
4320 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4321 wipeDeviceOrUserLocked(wipeExtRequested, userHandle,
4322 "DevicePolicyManager.wipeData() from " + source);
4324 mInjector.binderRestoreCallingIdentity(ident);
4329 private void wipeDeviceOrUserLocked(boolean wipeExtRequested, final int userHandle, String reason) {
4330 if (userHandle == UserHandle.USER_SYSTEM) {
4331 wipeDataLocked(wipeExtRequested, reason);
4333 mHandler.post(new Runnable() {
4337 IActivityManager am = mInjector.getIActivityManager();
4338 if (am.getCurrentUser().id == userHandle) {
4339 am.switchUser(UserHandle.USER_SYSTEM);
4342 boolean isManagedProfile = isManagedProfile(userHandle);
4343 if (!mUserManager.removeUser(userHandle)) {
4344 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4345 } else if (isManagedProfile) {
4346 sendWipeProfileNotification();
4348 } catch (RemoteException re) {
4356 private void sendWipeProfileNotification() {
4357 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4358 Notification notification = new Notification.Builder(mContext)
4359 .setSmallIcon(android.R.drawable.stat_sys_warning)
4360 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4361 .setContentText(contentText)
4362 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4363 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4365 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4368 private void clearWipeProfileNotification() {
4369 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4373 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4377 enforceFullCrossUsersPermission(userHandle);
4378 mContext.enforceCallingOrSelfPermission(
4379 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4381 synchronized (this) {
4382 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4383 if (admin == null) {
4384 result.sendResult(null);
4387 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4388 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4389 intent.setComponent(admin.info.getComponent());
4390 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4391 null, new BroadcastReceiver() {
4393 public void onReceive(Context context, Intent intent) {
4394 result.sendResult(getResultExtras(false));
4396 }, null, Activity.RESULT_OK, null, null);
4401 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4402 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4406 enforceFullCrossUsersPermission(userHandle);
4408 // Managed Profile password can only be changed when it has a separate challenge.
4409 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4410 enforceNotManagedProfile(userHandle, "set the active password");
4413 mContext.enforceCallingOrSelfPermission(
4414 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4415 validateQualityConstant(quality);
4417 DevicePolicyData policy = getUserData(userHandle);
4419 long ident = mInjector.binderClearCallingIdentity();
4421 synchronized (this) {
4422 policy.mActivePasswordQuality = quality;
4423 policy.mActivePasswordLength = length;
4424 policy.mActivePasswordLetters = letters;
4425 policy.mActivePasswordLowerCase = lowercase;
4426 policy.mActivePasswordUpperCase = uppercase;
4427 policy.mActivePasswordNumeric = numbers;
4428 policy.mActivePasswordSymbols = symbols;
4429 policy.mActivePasswordNonLetter = nonletter;
4430 policy.mFailedPasswordAttempts = 0;
4431 saveSettingsLocked(userHandle);
4432 updatePasswordExpirationsLocked(userHandle);
4433 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
4435 // Send a broadcast to each profile using this password as its primary unlock.
4436 sendAdminCommandForLockscreenPoliciesLocked(
4437 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4438 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
4441 mInjector.binderRestoreCallingIdentity(ident);
4446 * Called any time the device password is updated. Resets all password expiration clocks.
4448 private void updatePasswordExpirationsLocked(int userHandle) {
4449 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4450 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4451 userHandle, /* parent */ false);
4452 final int N = admins.size();
4453 for (int i = 0; i < N; i++) {
4454 ActiveAdmin admin = admins.get(i);
4455 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4456 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4457 long timeout = admin.passwordExpirationTimeout;
4458 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4459 admin.passwordExpirationDate = expiration;
4462 for (int affectedUserId : affectedUserIds) {
4463 saveSettingsLocked(affectedUserId);
4468 public void reportFailedPasswordAttempt(int userHandle) {
4469 enforceFullCrossUsersPermission(userHandle);
4470 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4471 enforceNotManagedProfile(userHandle,
4472 "report failed password attempt if separate profile challenge is not in place");
4474 mContext.enforceCallingOrSelfPermission(
4475 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4477 final long ident = mInjector.binderClearCallingIdentity();
4479 boolean wipeData = false;
4481 synchronized (this) {
4482 DevicePolicyData policy = getUserData(userHandle);
4483 policy.mFailedPasswordAttempts++;
4484 saveSettingsLocked(userHandle);
4486 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4487 userHandle, /* parent */ false);
4488 int max = strictestAdmin != null
4489 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4490 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4491 // Wipe the user/profile associated with the policy that was violated. This
4492 // is not necessarily calling user: if the policy that fired was from a
4493 // managed profile rather than the main user profile, we wipe former only.
4495 identifier = strictestAdmin.getUserHandle().getIdentifier();
4498 sendAdminCommandForLockscreenPoliciesLocked(
4499 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
4500 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4504 // Call without holding lock.
4505 wipeDeviceOrUserLocked(false, identifier,
4506 "reportFailedPasswordAttempt()");
4509 mInjector.binderRestoreCallingIdentity(ident);
4512 if (mInjector.securityLogIsLoggingEnabled()) {
4513 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4514 /*method strength*/ 1);
4519 public void reportSuccessfulPasswordAttempt(int userHandle) {
4520 enforceFullCrossUsersPermission(userHandle);
4521 mContext.enforceCallingOrSelfPermission(
4522 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4524 synchronized (this) {
4525 DevicePolicyData policy = getUserData(userHandle);
4526 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
4527 long ident = mInjector.binderClearCallingIdentity();
4529 policy.mFailedPasswordAttempts = 0;
4530 policy.mPasswordOwner = -1;
4531 saveSettingsLocked(userHandle);
4533 sendAdminCommandForLockscreenPoliciesLocked(
4534 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
4535 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4538 mInjector.binderRestoreCallingIdentity(ident);
4543 if (mInjector.securityLogIsLoggingEnabled()) {
4544 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4545 /*method strength*/ 1);
4550 public void reportFailedFingerprintAttempt(int userHandle) {
4551 enforceFullCrossUsersPermission(userHandle);
4552 mContext.enforceCallingOrSelfPermission(
4553 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4554 if (mInjector.securityLogIsLoggingEnabled()) {
4555 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4556 /*method strength*/ 0);
4561 public void reportSuccessfulFingerprintAttempt(int userHandle) {
4562 enforceFullCrossUsersPermission(userHandle);
4563 mContext.enforceCallingOrSelfPermission(
4564 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4565 if (mInjector.securityLogIsLoggingEnabled()) {
4566 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4567 /*method strength*/ 0);
4572 public void reportKeyguardDismissed(int userHandle) {
4573 enforceFullCrossUsersPermission(userHandle);
4574 mContext.enforceCallingOrSelfPermission(
4575 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4577 if (mInjector.securityLogIsLoggingEnabled()) {
4578 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
4583 public void reportKeyguardSecured(int userHandle) {
4584 enforceFullCrossUsersPermission(userHandle);
4585 mContext.enforceCallingOrSelfPermission(
4586 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4588 if (mInjector.securityLogIsLoggingEnabled()) {
4589 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
4594 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
4595 String exclusionList) {
4599 synchronized(this) {
4600 Preconditions.checkNotNull(who, "ComponentName is null");
4602 // Only check if system user has set global proxy. We don't allow other users to set it.
4603 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4604 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4605 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
4607 // Scan through active admins and find if anyone has already
4608 // set the global proxy.
4609 Set<ComponentName> compSet = policy.mAdminMap.keySet();
4610 for (ComponentName component : compSet) {
4611 ActiveAdmin ap = policy.mAdminMap.get(component);
4612 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
4613 // Another admin already sets the global proxy
4614 // Return it to the caller.
4619 // If the user is not system, don't set the global proxy. Fail silently.
4620 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
4621 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
4622 + UserHandle.getCallingUserId() + " is not permitted.");
4625 if (proxySpec == null) {
4626 admin.specifiesGlobalProxy = false;
4627 admin.globalProxySpec = null;
4628 admin.globalProxyExclusionList = null;
4631 admin.specifiesGlobalProxy = true;
4632 admin.globalProxySpec = proxySpec;
4633 admin.globalProxyExclusionList = exclusionList;
4636 // Reset the global proxy accordingly
4637 // Do this using system permissions, as apps cannot write to secure settings
4638 long origId = mInjector.binderClearCallingIdentity();
4640 resetGlobalProxyLocked(policy);
4642 mInjector.binderRestoreCallingIdentity(origId);
4649 public ComponentName getGlobalProxyAdmin(int userHandle) {
4653 enforceFullCrossUsersPermission(userHandle);
4654 synchronized(this) {
4655 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4656 // Scan through active admins and find if anyone has already
4657 // set the global proxy.
4658 final int N = policy.mAdminList.size();
4659 for (int i = 0; i < N; i++) {
4660 ActiveAdmin ap = policy.mAdminList.get(i);
4661 if (ap.specifiesGlobalProxy) {
4662 // Device admin sets the global proxy
4663 // Return it to the caller.
4664 return ap.info.getComponent();
4668 // No device admin sets the global proxy.
4673 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
4674 synchronized (this) {
4675 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4677 long token = mInjector.binderClearCallingIdentity();
4679 ConnectivityManager connectivityManager = (ConnectivityManager)
4680 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4681 connectivityManager.setGlobalProxy(proxyInfo);
4683 mInjector.binderRestoreCallingIdentity(token);
4687 private void resetGlobalProxyLocked(DevicePolicyData policy) {
4688 final int N = policy.mAdminList.size();
4689 for (int i = 0; i < N; i++) {
4690 ActiveAdmin ap = policy.mAdminList.get(i);
4691 if (ap.specifiesGlobalProxy) {
4692 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
4696 // No device admins defining global proxies - reset global proxy settings to none
4697 saveGlobalProxyLocked(null, null);
4700 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
4701 if (exclusionList == null) {
4704 if (proxySpec == null) {
4707 // Remove white spaces
4708 proxySpec = proxySpec.trim();
4709 String data[] = proxySpec.split(":");
4710 int proxyPort = 8080;
4711 if (data.length > 1) {
4713 proxyPort = Integer.parseInt(data[1]);
4714 } catch (NumberFormatException e) {}
4716 exclusionList = exclusionList.trim();
4718 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
4719 if (!proxyProperties.isValid()) {
4720 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
4723 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
4724 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
4725 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
4730 * Set the storage encryption request for a single admin. Returns the new total request
4731 * status (for all admins).
4734 public int setStorageEncryption(ComponentName who, boolean encrypt) {
4736 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4738 Preconditions.checkNotNull(who, "ComponentName is null");
4739 final int userHandle = UserHandle.getCallingUserId();
4740 synchronized (this) {
4741 // Check for permissions
4742 // Only system user can set storage encryption
4743 if (userHandle != UserHandle.USER_SYSTEM) {
4744 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
4745 + UserHandle.getCallingUserId() + " is not permitted.");
4749 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4750 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
4752 // Quick exit: If the filesystem does not support encryption, we can exit early.
4753 if (!isEncryptionSupported()) {
4754 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4757 // (1) Record the value for the admin so it's sticky
4758 if (ap.encryptionRequested != encrypt) {
4759 ap.encryptionRequested = encrypt;
4760 saveSettingsLocked(userHandle);
4763 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4764 // (2) Compute "max" for all admins
4765 boolean newRequested = false;
4766 final int N = policy.mAdminList.size();
4767 for (int i = 0; i < N; i++) {
4768 newRequested |= policy.mAdminList.get(i).encryptionRequested;
4771 // Notify OS of new request
4772 setEncryptionRequested(newRequested);
4774 // Return the new global request status
4776 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
4777 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
4782 * Get the current storage encryption request status for a given admin, or aggregate of all
4786 public boolean getStorageEncryption(ComponentName who, int userHandle) {
4790 enforceFullCrossUsersPermission(userHandle);
4791 synchronized (this) {
4792 // Check for permissions if a particular caller is specified
4794 // When checking for a single caller, status is based on caller's request
4795 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
4796 return ap != null ? ap.encryptionRequested : false;
4799 // If no particular caller is specified, return the aggregate set of requests.
4800 // This is short circuited by returning true on the first hit.
4801 DevicePolicyData policy = getUserData(userHandle);
4802 final int N = policy.mAdminList.size();
4803 for (int i = 0; i < N; i++) {
4804 if (policy.mAdminList.get(i).encryptionRequested) {
4813 * Get the current encryption status of the device.
4816 public int getStorageEncryptionStatus(int userHandle) {
4818 // Ok to return current status.
4820 enforceFullCrossUsersPermission(userHandle);
4821 return getEncryptionStatus();
4825 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
4827 private boolean isEncryptionSupported() {
4828 // Note, this can be implemented as
4829 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4830 // But is provided as a separate internal method if there's a faster way to do a
4831 // simple check for supported-or-not.
4832 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4836 * Hook to low-levels: Reporting the current status of encryption.
4837 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
4838 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
4839 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, or
4840 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
4842 private int getEncryptionStatus() {
4843 String status = mInjector.systemPropertiesGet("ro.crypto.state", "unsupported");
4844 if ("encrypted".equalsIgnoreCase(status)) {
4845 final long token = mInjector.binderClearCallingIdentity();
4847 return LockPatternUtils.isDeviceEncrypted()
4848 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
4849 : DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
4851 mInjector.binderRestoreCallingIdentity(token);
4853 } else if ("unencrypted".equalsIgnoreCase(status)) {
4854 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
4856 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4861 * Hook to low-levels: If needed, record the new admin setting for encryption.
4863 private void setEncryptionRequested(boolean encrypt) {
4868 * Set whether the screen capture is disabled for the user managed by the specified admin.
4871 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
4875 Preconditions.checkNotNull(who, "ComponentName is null");
4876 final int userHandle = UserHandle.getCallingUserId();
4877 synchronized (this) {
4878 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4879 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4880 if (ap.disableScreenCapture != disabled) {
4881 ap.disableScreenCapture = disabled;
4882 saveSettingsLocked(userHandle);
4883 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
4889 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
4890 * active admin (if given admin is null).
4893 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
4897 synchronized (this) {
4899 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4900 return (admin != null) ? admin.disableScreenCapture : false;
4903 DevicePolicyData policy = getUserData(userHandle);
4904 final int N = policy.mAdminList.size();
4905 for (int i = 0; i < N; i++) {
4906 ActiveAdmin admin = policy.mAdminList.get(i);
4907 if (admin.disableScreenCapture) {
4915 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
4916 final boolean disabled) {
4917 mHandler.post(new Runnable() {
4921 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
4922 } catch (RemoteException e) {
4923 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
4930 * Set whether auto time is required by the specified admin (must be device owner).
4933 public void setAutoTimeRequired(ComponentName who, boolean required) {
4937 Preconditions.checkNotNull(who, "ComponentName is null");
4938 final int userHandle = UserHandle.getCallingUserId();
4939 synchronized (this) {
4940 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4941 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4942 if (admin.requireAutoTime != required) {
4943 admin.requireAutoTime = required;
4944 saveSettingsLocked(userHandle);
4948 // Turn AUTO_TIME on in settings if it is required
4950 long ident = mInjector.binderClearCallingIdentity();
4952 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
4954 mInjector.binderRestoreCallingIdentity(ident);
4960 * Returns whether or not auto time is required by the device owner.
4963 public boolean getAutoTimeRequired() {
4967 synchronized (this) {
4968 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
4969 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
4974 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
4978 Preconditions.checkNotNull(who, "ComponentName is null");
4979 // Allow setting this policy to true only if there is a split system user.
4980 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
4981 throw new UnsupportedOperationException(
4982 "Cannot force ephemeral users on systems without split system user.");
4984 boolean removeAllUsers = false;
4985 synchronized (this) {
4986 final ActiveAdmin deviceOwner =
4987 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4988 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
4989 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
4990 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4991 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
4992 removeAllUsers = forceEphemeralUsers;
4995 if (removeAllUsers) {
4996 long identitity = mInjector.binderClearCallingIdentity();
4998 mUserManagerInternal.removeAllUsers();
5000 mInjector.binderRestoreCallingIdentity(identitity);
5006 public boolean getForceEphemeralUsers(ComponentName who) {
5010 Preconditions.checkNotNull(who, "ComponentName is null");
5011 synchronized (this) {
5012 final ActiveAdmin deviceOwner =
5013 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5014 return deviceOwner.forceEphemeralUsers;
5018 private boolean isDeviceOwnerManagedSingleUserDevice() {
5019 synchronized (this) {
5020 if (!mOwners.hasDeviceOwner()) {
5024 final long callingIdentity = mInjector.binderClearCallingIdentity();
5026 if (mInjector.userManagerIsSplitSystemUser()) {
5027 // In split system user mode, only allow the case where the device owner is managing
5028 // the only non-system user of the device
5029 return (mUserManager.getUserCount() == 2
5030 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5032 return mUserManager.getUserCount() == 1;
5035 mInjector.binderRestoreCallingIdentity(callingIdentity);
5039 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5040 synchronized (this) {
5041 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5043 if (!isDeviceOwnerManagedSingleUserDevice()) {
5044 throw new SecurityException(
5045 "There should only be one user, managed by Device Owner");
5050 public boolean requestBugreport(ComponentName who) {
5054 Preconditions.checkNotNull(who, "ComponentName is null");
5055 ensureDeviceOwnerManagingSingleUser(who);
5057 if (mRemoteBugreportServiceIsActive.get()
5058 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5059 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5063 final long callingIdentity = mInjector.binderClearCallingIdentity();
5065 ActivityManagerNative.getDefault().requestBugReport(
5066 ActivityManager.BUGREPORT_OPTION_REMOTE);
5068 mRemoteBugreportServiceIsActive.set(true);
5069 mRemoteBugreportSharingAccepted.set(false);
5070 registerRemoteBugreportReceivers();
5071 mInjector.getNotificationManager().notify(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5072 RemoteBugreportUtils.buildNotification(mContext,
5073 RemoteBugreportUtils.NOTIFICATION_BUGREPORT_STARTED));
5074 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5075 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5077 } catch (RemoteException re) {
5078 // should never happen
5079 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5082 mInjector.binderRestoreCallingIdentity(callingIdentity);
5086 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5087 Intent intent = new Intent(action);
5088 intent.setComponent(mOwners.getDeviceOwnerComponent());
5089 if (extras != null) {
5090 intent.putExtras(extras);
5092 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5095 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5096 return mOwners.getDeviceOwnerRemoteBugreportUri();
5099 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5100 String bugreportHash) {
5101 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5104 private void registerRemoteBugreportReceivers() {
5106 IntentFilter filterFinished = new IntentFilter(
5107 RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_DISPATCH,
5108 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5109 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5110 } catch (IntentFilter.MalformedMimeTypeException e) {
5111 // should never happen, as setting a constant
5112 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5114 IntentFilter filterConsent = new IntentFilter();
5115 filterConsent.addAction(RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_DECLINED);
5116 filterConsent.addAction(RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_ACCEPTED);
5117 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5120 private void onBugreportFinished(Intent intent) {
5121 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5122 mRemoteBugreportServiceIsActive.set(false);
5123 Uri bugreportUri = intent.getData();
5124 String bugreportUriString = null;
5125 if (bugreportUri != null) {
5126 bugreportUriString = bugreportUri.toString();
5128 String bugreportHash = intent.getStringExtra(
5129 RemoteBugreportUtils.EXTRA_REMOTE_BUGREPORT_HASH);
5130 if (mRemoteBugreportSharingAccepted.get()) {
5131 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5132 mInjector.getNotificationManager().cancel(LOG_TAG,
5133 RemoteBugreportUtils.NOTIFICATION_ID);
5135 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5136 mInjector.getNotificationManager().notify(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5137 RemoteBugreportUtils.buildNotification(mContext,
5138 RemoteBugreportUtils.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED));
5140 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5143 private void onBugreportFailed() {
5144 mRemoteBugreportServiceIsActive.set(false);
5145 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5146 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5147 mRemoteBugreportSharingAccepted.set(false);
5148 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5149 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5150 Bundle extras = new Bundle();
5151 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5152 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5153 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5154 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5155 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5158 private void onBugreportSharingAccepted() {
5159 mRemoteBugreportSharingAccepted.set(true);
5160 String bugreportUriString = null;
5161 String bugreportHash = null;
5162 synchronized (this) {
5163 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5164 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5166 if (bugreportUriString != null) {
5167 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5168 } else if (mRemoteBugreportServiceIsActive.get()) {
5169 mInjector.getNotificationManager().notify(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5170 RemoteBugreportUtils.buildNotification(mContext,
5171 RemoteBugreportUtils.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED));
5175 private void onBugreportSharingDeclined() {
5176 if (mRemoteBugreportServiceIsActive.get()) {
5177 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5178 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5179 mRemoteBugreportServiceIsActive.set(false);
5180 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5181 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5183 mRemoteBugreportSharingAccepted.set(false);
5184 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5185 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5188 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5189 String bugreportHash) {
5190 ParcelFileDescriptor pfd = null;
5192 if (bugreportUriString == null) {
5193 throw new FileNotFoundException();
5195 Uri bugreportUri = Uri.parse(bugreportUriString);
5196 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5198 synchronized (this) {
5199 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5200 intent.setComponent(mOwners.getDeviceOwnerComponent());
5201 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5202 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5203 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
5204 bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5205 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5207 } catch (FileNotFoundException e) {
5208 Bundle extras = new Bundle();
5209 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5210 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5211 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5217 } catch (IOException ex) {
5220 mRemoteBugreportSharingAccepted.set(false);
5221 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5226 * Disables all device cameras according to the specified admin.
5229 public void setCameraDisabled(ComponentName who, boolean disabled) {
5233 Preconditions.checkNotNull(who, "ComponentName is null");
5234 final int userHandle = mInjector.userHandleGetCallingUserId();
5235 synchronized (this) {
5236 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5237 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5238 if (ap.disableCamera != disabled) {
5239 ap.disableCamera = disabled;
5240 saveSettingsLocked(userHandle);
5243 // Tell the user manager that the restrictions have changed.
5244 pushUserRestrictions(userHandle);
5248 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5252 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5253 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5256 private boolean getCameraDisabled(ComponentName who, int userHandle,
5257 boolean mergeDeviceOwnerRestriction) {
5261 synchronized (this) {
5263 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5264 return (admin != null) ? admin.disableCamera : false;
5266 // First, see if DO has set it. If so, it's device-wide.
5267 if (mergeDeviceOwnerRestriction) {
5268 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5269 if (deviceOwner != null && deviceOwner.disableCamera) {
5274 // Then check each device admin on the user.
5275 DevicePolicyData policy = getUserData(userHandle);
5276 // Determine whether or not the device camera is disabled for any active admins.
5277 final int N = policy.mAdminList.size();
5278 for (int i = 0; i < N; i++) {
5279 ActiveAdmin admin = policy.mAdminList.get(i);
5280 if (admin.disableCamera) {
5289 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5293 Preconditions.checkNotNull(who, "ComponentName is null");
5294 final int userHandle = mInjector.userHandleGetCallingUserId();
5295 if (isManagedProfile(userHandle)) {
5297 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5299 which = which & PROFILE_KEYGUARD_FEATURES;
5302 synchronized (this) {
5303 ActiveAdmin ap = getActiveAdminForCallerLocked(
5304 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5305 if (ap.disabledKeyguardFeatures != which) {
5306 ap.disabledKeyguardFeatures = which;
5307 saveSettingsLocked(userHandle);
5313 * Gets the disabled state for features in keyguard for the given admin,
5314 * or the aggregate of all active admins if who is null.
5317 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5321 enforceFullCrossUsersPermission(userHandle);
5322 final long ident = mInjector.binderClearCallingIdentity();
5324 synchronized (this) {
5326 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5327 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5330 final List<ActiveAdmin> admins;
5331 if (!parent && isManagedProfile(userHandle)) {
5332 // If we are being asked about a managed profile, just return keyguard features
5333 // disabled by admins in the profile.
5334 admins = getUserDataUnchecked(userHandle).mAdminList;
5336 // Otherwise return those set by admins in the user and its profiles.
5337 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5340 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5341 final int N = admins.size();
5342 for (int i = 0; i < N; i++) {
5343 ActiveAdmin admin = admins.get(i);
5344 int userId = admin.getUserHandle().getIdentifier();
5345 boolean isRequestedUser = !parent && (userId == userHandle);
5346 if (isRequestedUser || !isManagedProfile(userId)) {
5347 // If we are being asked explicitly about this user
5348 // return all disabled features even if its a managed profile.
5349 which |= admin.disabledKeyguardFeatures;
5351 // Otherwise a managed profile is only allowed to disable
5352 // some features on the parent user.
5353 which |= (admin.disabledKeyguardFeatures
5354 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5360 mInjector.binderRestoreCallingIdentity(ident);
5365 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5369 Preconditions.checkNotNull(who, "ComponentName is null");
5370 Preconditions.checkNotNull(packageList, "packageList is null");
5371 final int userHandle = UserHandle.getCallingUserId();
5372 synchronized (this) {
5373 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5374 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5375 admin.keepUninstalledPackages = packageList;
5376 saveSettingsLocked(userHandle);
5377 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5382 public List<String> getKeepUninstalledPackages(ComponentName who) {
5383 Preconditions.checkNotNull(who, "ComponentName is null");
5387 // TODO In split system user mode, allow apps on user 0 to query the list
5388 synchronized (this) {
5389 // Check if this is the device owner who is calling
5390 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5391 return getKeepUninstalledPackagesLocked();
5395 private List<String> getKeepUninstalledPackagesLocked() {
5396 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5397 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5401 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5406 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5407 throw new IllegalArgumentException("Invalid component " + admin
5408 + " for device owner");
5410 synchronized (this) {
5411 enforceCanSetDeviceOwnerLocked(userId);
5412 if (getActiveAdminUncheckedLocked(admin, userId) == null) {
5413 throw new IllegalArgumentException("Not active admin: " + admin);
5416 // Shutting down backup manager service permanently.
5417 long ident = mInjector.binderClearCallingIdentity();
5419 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5420 } catch (RemoteException e) {
5421 throw new IllegalStateException("Failed deactivating backup service.", e);
5423 mInjector.binderRestoreCallingIdentity(ident);
5426 mOwners.setDeviceOwner(admin, ownerName, userId);
5427 mOwners.writeDeviceOwner();
5428 updateDeviceOwnerLocked();
5429 setDeviceOwnerSystemPropertyLocked();
5430 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5432 ident = mInjector.binderClearCallingIdentity();
5434 // TODO Send to system too?
5435 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5437 mInjector.binderRestoreCallingIdentity(ident);
5443 public boolean isDeviceOwner(ComponentName who, int userId) {
5444 synchronized (this) {
5445 return mOwners.hasDeviceOwner()
5446 && mOwners.getDeviceOwnerUserId() == userId
5447 && mOwners.getDeviceOwnerComponent().equals(who);
5451 public boolean isProfileOwner(ComponentName who, int userId) {
5452 final ComponentName profileOwner = getProfileOwner(userId);
5453 return who != null && who.equals(profileOwner);
5457 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5461 if (!callingUserOnly) {
5462 enforceManageUsers();
5464 synchronized (this) {
5465 if (!mOwners.hasDeviceOwner()) {
5468 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
5469 mOwners.getDeviceOwnerUserId()) {
5472 return mOwners.getDeviceOwnerComponent();
5477 public int getDeviceOwnerUserId() {
5479 return UserHandle.USER_NULL;
5481 enforceManageUsers();
5482 synchronized (this) {
5483 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
5488 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
5492 public String getDeviceOwnerName() {
5496 enforceManageUsers();
5497 synchronized (this) {
5498 if (!mOwners.hasDeviceOwner()) {
5501 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
5502 // Should setDeviceOwner/ProfileOwner still take a name?
5503 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
5504 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
5508 // Returns the active device owner or null if there is no device owner.
5510 ActiveAdmin getDeviceOwnerAdminLocked() {
5511 ComponentName component = mOwners.getDeviceOwnerComponent();
5512 if (component == null) {
5516 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
5517 final int n = policy.mAdminList.size();
5518 for (int i = 0; i < n; i++) {
5519 ActiveAdmin admin = policy.mAdminList.get(i);
5520 if (component.equals(admin.info.getComponent())) {
5524 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
5529 public void clearDeviceOwner(String packageName) {
5530 Preconditions.checkNotNull(packageName, "packageName is null");
5531 final int callingUid = mInjector.binderGetCallingUid();
5533 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
5534 UserHandle.getUserId(callingUid));
5535 if (uid != callingUid) {
5536 throw new SecurityException("Invalid packageName");
5538 } catch (NameNotFoundException e) {
5539 throw new SecurityException(e);
5541 synchronized (this) {
5542 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
5543 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
5544 if (!mOwners.hasDeviceOwner()
5545 || !deviceOwnerComponent.getPackageName().equals(packageName)
5546 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
5547 throw new SecurityException(
5548 "clearDeviceOwner can only be called by the device owner");
5550 enforceUserUnlocked(deviceOwnerUserId);
5552 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
5553 if (admin != null) {
5554 admin.disableCamera = false;
5555 admin.userRestrictions = null;
5556 admin.forceEphemeralUsers = false;
5557 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
5559 clearUserPoliciesLocked(deviceOwnerUserId);
5561 mOwners.clearDeviceOwner();
5562 mOwners.writeDeviceOwner();
5563 updateDeviceOwnerLocked();
5564 disableDeviceLoggingIfNotCompliant();
5565 // Reactivate backup service.
5566 long ident = mInjector.binderClearCallingIdentity();
5568 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
5570 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
5571 } catch (RemoteException e) {
5572 throw new IllegalStateException("Failed reactivating backup service.", e);
5574 mInjector.binderRestoreCallingIdentity(ident);
5580 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
5585 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
5586 throw new IllegalArgumentException("Component " + who
5587 + " not installed for userId:" + userHandle);
5589 synchronized (this) {
5590 enforceCanSetProfileOwnerLocked(userHandle);
5592 if (getActiveAdminUncheckedLocked(who, userHandle) == null) {
5593 throw new IllegalArgumentException("Not active admin: " + who);
5596 mOwners.setProfileOwner(who, ownerName, userHandle);
5597 mOwners.writeProfileOwner(userHandle);
5603 public void clearProfileOwner(ComponentName who) {
5607 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
5608 final int userId = callingUser.getIdentifier();
5609 enforceNotManagedProfile(userId, "clear profile owner");
5610 enforceUserUnlocked(userId);
5611 // Check if this is the profile owner who is calling
5612 final ActiveAdmin admin =
5613 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5614 synchronized (this) {
5615 admin.disableCamera = false;
5616 admin.userRestrictions = null;
5617 clearUserPoliciesLocked(userId);
5618 mOwners.removeProfileOwner(userId);
5619 mOwners.writeProfileOwner(userId);
5621 final long ident = mInjector.binderClearCallingIdentity();
5623 removeActiveAdminLocked(who, userId);
5625 mInjector.binderRestoreCallingIdentity(ident);
5631 public boolean setDeviceOwnerLockScreenInfo(ComponentName who, String info) {
5632 Preconditions.checkNotNull(who, "ComponentName is null");
5637 synchronized (this) {
5638 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5639 long token = mInjector.binderClearCallingIdentity();
5641 mLockPatternUtils.setDeviceOwnerInfo(info);
5643 mInjector.binderRestoreCallingIdentity(token);
5650 public String getDeviceOwnerLockScreenInfo() {
5651 return mLockPatternUtils.getDeviceOwnerInfo();
5654 private void clearUserPoliciesLocked(int userId) {
5655 // Reset some of the user-specific policies
5656 DevicePolicyData policy = getUserData(userId);
5657 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
5658 policy.mDelegatedCertInstallerPackage = null;
5659 policy.mApplicationRestrictionsManagingPackage = null;
5660 policy.mStatusBarDisabled = false;
5661 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
5662 saveSettingsLocked(userId);
5664 final long ident = mInjector.binderClearCallingIdentity();
5666 mIPackageManager.updatePermissionFlagsForAllApps(
5667 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
5668 0 /* flagValues */, userId);
5669 pushUserRestrictions(userId);
5670 } catch (RemoteException re) {
5672 mInjector.binderRestoreCallingIdentity(ident);
5677 public boolean hasUserSetupCompleted() {
5678 return hasUserSetupCompleted(UserHandle.getCallingUserId());
5681 private boolean hasUserSetupCompleted(int userHandle) {
5685 return getUserData(userHandle).mUserSetupComplete;
5689 public int getUserProvisioningState() {
5691 return DevicePolicyManager.STATE_USER_UNMANAGED;
5693 int userHandle = mInjector.userHandleGetCallingUserId();
5694 return getUserProvisioningState(userHandle);
5697 private int getUserProvisioningState(int userHandle) {
5698 return getUserData(userHandle).mUserProvisioningState;
5702 public void setUserProvisioningState(int newState, int userHandle) {
5707 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
5708 && getManagedUserId(userHandle) == -1) {
5709 // No managed device, user or profile, so setting provisioning state makes no sense.
5710 throw new IllegalStateException("Not allowed to change provisioning state unless a "
5711 + "device or profile owner is set.");
5714 synchronized (this) {
5715 boolean transitionCheckNeeded = true;
5717 // Calling identity/permission checks.
5718 final int callingUid = mInjector.binderGetCallingUid();
5719 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
5720 // ADB shell can only move directly from un-managed to finalized as part of directly
5721 // setting profile-owner or device-owner.
5722 if (getUserProvisioningState(userHandle) !=
5723 DevicePolicyManager.STATE_USER_UNMANAGED
5724 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
5725 throw new IllegalStateException("Not allowed to change provisioning state "
5726 + "unless current provisioning state is unmanaged, and new state is "
5729 transitionCheckNeeded = false;
5731 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
5732 mContext.enforceCallingOrSelfPermission(
5733 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
5736 final DevicePolicyData policyData = getUserData(userHandle);
5737 if (transitionCheckNeeded) {
5738 // Optional state transition check for non-ADB case.
5739 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
5741 policyData.mUserProvisioningState = newState;
5742 saveSettingsLocked(userHandle);
5746 private void checkUserProvisioningStateTransition(int currentState, int newState) {
5747 // Valid transitions for normal use-cases.
5748 switch (currentState) {
5749 case DevicePolicyManager.STATE_USER_UNMANAGED:
5750 // Can move to any state from unmanaged (except itself as an edge case)..
5751 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
5755 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
5756 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
5757 // Can only move to finalized from these states.
5758 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
5762 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
5763 // Current user has a managed-profile, but current user is not managed, so
5764 // rather than moving to finalized state, go back to unmanaged once
5765 // profile provisioning is complete.
5766 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
5770 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
5771 // Cannot transition out of finalized.
5775 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
5776 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
5777 + "from state [" + currentState + "]");
5781 public void setProfileEnabled(ComponentName who) {
5785 Preconditions.checkNotNull(who, "ComponentName is null");
5786 synchronized (this) {
5787 // Check if this is the profile owner who is calling
5788 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5789 final int userId = UserHandle.getCallingUserId();
5790 enforceManagedProfile(userId, "enable the profile");
5792 long id = mInjector.binderClearCallingIdentity();
5794 mUserManager.setUserEnabled(userId);
5795 UserInfo parent = mUserManager.getProfileParent(userId);
5796 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
5797 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
5798 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
5799 Intent.FLAG_RECEIVER_FOREGROUND);
5800 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
5802 mInjector.binderRestoreCallingIdentity(id);
5808 public void setProfileName(ComponentName who, String profileName) {
5809 Preconditions.checkNotNull(who, "ComponentName is null");
5810 int userId = UserHandle.getCallingUserId();
5811 // Check if this is the profile owner (includes device owner).
5812 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5814 long id = mInjector.binderClearCallingIdentity();
5816 mUserManager.setUserName(userId, profileName);
5818 mInjector.binderRestoreCallingIdentity(id);
5823 public ComponentName getProfileOwner(int userHandle) {
5828 synchronized (this) {
5829 return mOwners.getProfileOwnerComponent(userHandle);
5833 // Returns the active profile owner for this user or null if the current user has no
5836 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
5837 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
5838 if (profileOwner == null) {
5841 DevicePolicyData policy = getUserData(userHandle);
5842 final int n = policy.mAdminList.size();
5843 for (int i = 0; i < n; i++) {
5844 ActiveAdmin admin = policy.mAdminList.get(i);
5845 if (profileOwner.equals(admin.info.getComponent())) {
5853 public String getProfileOwnerName(int userHandle) {
5857 enforceManageUsers();
5858 ComponentName profileOwner = getProfileOwner(userHandle);
5859 if (profileOwner == null) {
5862 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
5866 * Canonical name for a given package.
5868 private String getApplicationLabel(String packageName, int userHandle) {
5869 long token = mInjector.binderClearCallingIdentity();
5871 final Context userContext;
5873 UserHandle handle = new UserHandle(userHandle);
5874 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
5875 } catch (PackageManager.NameNotFoundException nnfe) {
5876 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
5879 ApplicationInfo appInfo = userContext.getApplicationInfo();
5880 CharSequence result = null;
5881 if (appInfo != null) {
5882 PackageManager pm = userContext.getPackageManager();
5883 result = pm.getApplicationLabel(appInfo);
5885 return result != null ? result.toString() : null;
5887 mInjector.binderRestoreCallingIdentity(token);
5892 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
5894 * The profile owner can only be set before the user setup phase has completed,
5897 * - adb if there are not accounts.
5899 private void enforceCanSetProfileOwnerLocked(int userHandle) {
5900 UserInfo info = mUserManager.getUserInfo(userHandle);
5902 // User doesn't exist.
5903 throw new IllegalArgumentException(
5904 "Attempted to set profile owner for invalid userId: " + userHandle);
5906 if (info.isGuest()) {
5907 throw new IllegalStateException("Cannot set a profile owner on a guest");
5909 if (mOwners.hasProfileOwner(userHandle)) {
5910 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
5911 + "is already set.");
5913 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
5914 throw new IllegalStateException("Trying to set the profile owner, but the user "
5915 + "already has a device owner.");
5917 int callingUid = mInjector.binderGetCallingUid();
5918 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
5919 if (hasUserSetupCompleted(userHandle) &&
5920 AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) {
5921 throw new IllegalStateException("Not allowed to set the profile owner because "
5922 + "there are already some accounts on the profile");
5926 mContext.enforceCallingOrSelfPermission(
5927 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
5928 if (hasUserSetupCompleted(userHandle) && !isCallerWithSystemUid()) {
5929 throw new IllegalStateException("Cannot set the profile owner on a user which is "
5930 + "already set-up");
5935 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
5937 * The device owner can only be set before the setup phase of the primary user has completed,
5938 * except for adb if no accounts or additional users are present on the device.
5940 private void enforceCanSetDeviceOwnerLocked(int userId) {
5941 if (mOwners.hasDeviceOwner()) {
5942 throw new IllegalStateException("Trying to set the device owner, but device owner "
5943 + "is already set.");
5945 if (mOwners.hasProfileOwner(userId)) {
5946 throw new IllegalStateException("Trying to set the device owner, but the user already "
5947 + "has a profile owner.");
5949 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
5950 throw new IllegalStateException("User not running: " + userId);
5953 int callingUid = mInjector.binderGetCallingUid();
5954 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
5955 if (!hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
5958 // STOPSHIP Do proper check in split user mode
5959 if (!mInjector.userManagerIsSplitSystemUser()) {
5960 if (mUserManager.getUserCount() > 1) {
5961 throw new IllegalStateException(
5962 "Not allowed to set the device owner because there "
5963 + "are already several users on the device");
5965 if (AccountManager.get(mContext).getAccounts().length > 0) {
5966 throw new IllegalStateException(
5967 "Not allowed to set the device owner because there "
5968 + "are already some accounts on the device");
5973 // STOPSHIP check the caller UID with userId
5975 mContext.enforceCallingOrSelfPermission(
5976 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
5977 // STOPSHIP Do proper check in split user mode
5978 if (!mInjector.userManagerIsSplitSystemUser()) {
5979 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
5980 throw new IllegalStateException("Cannot set the device owner if the device is "
5981 + "already set-up");
5986 private void enforceUserUnlocked(int userId) {
5987 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
5988 "User must be running and unlocked");
5991 private void enforceManageUsers() {
5992 final int callingUid = mInjector.binderGetCallingUid();
5993 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
5994 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
5998 private void enforceFullCrossUsersPermission(int userHandle) {
5999 enforceSystemUserOrPermission(userHandle,
6000 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6003 private void enforceCrossUsersPermission(int userHandle) {
6004 enforceSystemUserOrPermission(userHandle,
6005 android.Manifest.permission.INTERACT_ACROSS_USERS);
6008 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6009 if (userHandle < 0) {
6010 throw new IllegalArgumentException("Invalid userId " + userHandle);
6012 final int callingUid = mInjector.binderGetCallingUid();
6013 if (userHandle == UserHandle.getUserId(callingUid)) {
6016 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6017 mContext.enforceCallingOrSelfPermission(permission,
6018 "Must be system or have " + permission + " permission");
6022 private void enforceManagedProfile(int userHandle, String message) {
6023 if(!isManagedProfile(userHandle)) {
6024 throw new SecurityException("You can not " + message + " outside a managed profile.");
6028 private void enforceNotManagedProfile(int userHandle, String message) {
6029 if(isManagedProfile(userHandle)) {
6030 throw new SecurityException("You can not " + message + " for a managed profile.");
6034 private boolean isCallerWithSystemUid() {
6035 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6038 private int getProfileParentId(int userHandle) {
6039 final long ident = mInjector.binderClearCallingIdentity();
6041 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6042 return parentUser != null ? parentUser.id : userHandle;
6044 mInjector.binderRestoreCallingIdentity(ident);
6048 private int getCredentialOwner(int userHandle, boolean parent) {
6049 final long ident = mInjector.binderClearCallingIdentity();
6052 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6053 if (parentProfile != null) {
6054 userHandle = parentProfile.id;
6057 return mUserManager.getCredentialOwnerProfile(userHandle);
6059 mInjector.binderRestoreCallingIdentity(ident);
6063 private boolean isManagedProfile(int userHandle) {
6064 long ident = mInjector.binderClearCallingIdentity();
6066 return mUserManager.getUserInfo(userHandle).isManagedProfile();
6068 mInjector.binderRestoreCallingIdentity(ident);
6072 private void enableIfNecessary(String packageName, int userId) {
6074 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6075 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6077 if (ai.enabledSetting
6078 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6079 mIPackageManager.setApplicationEnabledSetting(packageName,
6080 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6081 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6083 } catch (RemoteException e) {
6088 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6089 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6090 != PackageManager.PERMISSION_GRANTED) {
6092 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6093 + mInjector.binderGetCallingPid()
6094 + ", uid=" + mInjector.binderGetCallingUid());
6098 synchronized (this) {
6099 pw.println("Current Device Policy Manager state:");
6100 mOwners.dump(" ", pw);
6101 int userCount = mUserData.size();
6102 for (int u = 0; u < userCount; u++) {
6103 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6105 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6106 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6107 final int N = policy.mAdminList.size();
6108 for (int i=0; i<N; i++) {
6109 ActiveAdmin ap = policy.mAdminList.get(i);
6111 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6116 if (!policy.mRemovingAdmins.isEmpty()) {
6117 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6118 + policy.mRemovingAdmins);
6122 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6128 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6129 ComponentName activity) {
6130 Preconditions.checkNotNull(who, "ComponentName is null");
6131 final int userHandle = UserHandle.getCallingUserId();
6132 synchronized (this) {
6133 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6135 long id = mInjector.binderClearCallingIdentity();
6137 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6138 } catch (RemoteException re) {
6141 mInjector.binderRestoreCallingIdentity(id);
6147 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6148 Preconditions.checkNotNull(who, "ComponentName is null");
6149 final int userHandle = UserHandle.getCallingUserId();
6150 synchronized (this) {
6151 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6153 long id = mInjector.binderClearCallingIdentity();
6155 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6156 } catch (RemoteException re) {
6159 mInjector.binderRestoreCallingIdentity(id);
6165 public void setApplicationRestrictionsManagingPackage(ComponentName admin, String packageName) {
6166 Preconditions.checkNotNull(admin, "ComponentName is null");
6168 final int userHandle = mInjector.userHandleGetCallingUserId();
6169 synchronized (this) {
6170 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6171 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6172 throw new IllegalArgumentException("Package " + packageName + " is not installed "
6173 + "on the current user");
6175 DevicePolicyData policy = getUserData(userHandle);
6176 policy.mApplicationRestrictionsManagingPackage = packageName;
6177 saveSettingsLocked(userHandle);
6182 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6183 Preconditions.checkNotNull(admin, "ComponentName is null");
6185 final int userHandle = mInjector.userHandleGetCallingUserId();
6186 synchronized (this) {
6187 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6188 DevicePolicyData policy = getUserData(userHandle);
6189 return policy.mApplicationRestrictionsManagingPackage;
6194 public boolean isCallerApplicationRestrictionsManagingPackage() {
6195 final int callingUid = mInjector.binderGetCallingUid();
6196 final int userHandle = UserHandle.getUserId(callingUid);
6197 synchronized (this) {
6198 final DevicePolicyData policy = getUserData(userHandle);
6199 if (policy.mApplicationRestrictionsManagingPackage == null) {
6204 int uid = mContext.getPackageManager().getPackageUidAsUser(
6205 policy.mApplicationRestrictionsManagingPackage, userHandle);
6206 return uid == callingUid;
6207 } catch (NameNotFoundException e) {
6213 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6215 synchronized (this) {
6216 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6218 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6219 throw new SecurityException(
6220 "No admin component given, and caller cannot manage application restrictions "
6221 + "for other apps.");
6226 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6227 enforceCanManageApplicationRestrictions(who);
6229 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6230 final long id = mInjector.binderClearCallingIdentity();
6232 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6234 mInjector.binderRestoreCallingIdentity(id);
6239 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6240 PersistableBundle args) {
6244 Preconditions.checkNotNull(admin, "admin is null");
6245 Preconditions.checkNotNull(agent, "agent is null");
6246 final int userHandle = UserHandle.getCallingUserId();
6247 enforceNotManagedProfile(userHandle, "set trust agent configuration");
6248 synchronized (this) {
6249 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6250 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
6251 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6252 saveSettingsLocked(userHandle);
6257 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6258 ComponentName agent, int userHandle) {
6262 Preconditions.checkNotNull(agent, "agent null");
6263 enforceFullCrossUsersPermission(userHandle);
6265 synchronized (this) {
6266 final String componentName = agent.flattenToString();
6267 if (admin != null) {
6268 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle);
6269 if (ap == null) return null;
6270 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6271 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6272 List<PersistableBundle> result = new ArrayList<PersistableBundle>();
6273 result.add(trustAgentInfo.options);
6277 // Return strictest policy for this user and profiles that are visible from this user.
6278 final List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
6279 List<PersistableBundle> result = null;
6281 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6282 // of the options. If any admin doesn't have options, discard options for the rest
6284 boolean allAdminsHaveOptions = true;
6285 for (UserInfo userInfo : profiles) {
6286 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
6287 final int N = policy.mAdminList.size();
6288 for (int i=0; i < N; i++) {
6289 final ActiveAdmin active = policy.mAdminList.get(i);
6290 final boolean disablesTrust = (active.disabledKeyguardFeatures
6291 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6292 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6293 if (info != null && info.options != null && !info.options.isEmpty()) {
6294 if (disablesTrust) {
6295 if (result == null) {
6296 result = new ArrayList<PersistableBundle>();
6298 result.add(info.options);
6300 Log.w(LOG_TAG, "Ignoring admin " + active.info
6301 + " because it has trust options but doesn't declare "
6302 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6304 } else if (disablesTrust) {
6305 allAdminsHaveOptions = false;
6310 return allAdminsHaveOptions ? result : null;
6315 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6316 Preconditions.checkNotNull(who, "ComponentName is null");
6317 synchronized (this) {
6318 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6320 int userHandle = UserHandle.getCallingUserId();
6321 DevicePolicyData userData = getUserData(userHandle);
6322 userData.mRestrictionsProvider = permissionProvider;
6323 saveSettingsLocked(userHandle);
6328 public ComponentName getRestrictionsProvider(int userHandle) {
6329 synchronized (this) {
6330 if (!isCallerWithSystemUid()) {
6331 throw new SecurityException("Only the system can query the permission provider");
6333 DevicePolicyData userData = getUserData(userHandle);
6334 return userData != null ? userData.mRestrictionsProvider : null;
6339 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6340 Preconditions.checkNotNull(who, "ComponentName is null");
6341 int callingUserId = UserHandle.getCallingUserId();
6342 synchronized (this) {
6343 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6345 long id = mInjector.binderClearCallingIdentity();
6347 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6348 if (parent == null) {
6349 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6353 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6354 mIPackageManager.addCrossProfileIntentFilter(
6355 filter, who.getPackageName(), callingUserId, parent.id, 0);
6357 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6358 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6359 parent.id, callingUserId, 0);
6361 } catch (RemoteException re) {
6364 mInjector.binderRestoreCallingIdentity(id);
6370 public void clearCrossProfileIntentFilters(ComponentName who) {
6371 Preconditions.checkNotNull(who, "ComponentName is null");
6372 int callingUserId = UserHandle.getCallingUserId();
6373 synchronized (this) {
6374 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6375 long id = mInjector.binderClearCallingIdentity();
6377 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6378 if (parent == null) {
6379 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6383 // Removing those that go from the managed profile to the parent.
6384 mIPackageManager.clearCrossProfileIntentFilters(
6385 callingUserId, who.getPackageName());
6386 // And those that go from the parent to the managed profile.
6387 // If we want to support multiple managed profiles, we will have to only remove
6388 // those that have callingUserId as their target.
6389 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6390 } catch (RemoteException re) {
6393 mInjector.binderRestoreCallingIdentity(id);
6399 * @return true if all packages in enabledPackages are either in the list
6400 * permittedList or are a system app.
6402 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6403 List<String> permittedList, int userIdToCheck) {
6404 long id = mInjector.binderClearCallingIdentity();
6406 // If we have an enabled packages list for a managed profile the packages
6407 // we should check are installed for the parent user.
6408 UserInfo user = mUserManager.getUserInfo(userIdToCheck);
6409 if (user.isManagedProfile()) {
6410 userIdToCheck = user.profileGroupId;
6413 for (String enabledPackage : enabledPackages) {
6414 boolean systemService = false;
6416 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
6417 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
6418 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6419 } catch (RemoteException e) {
6420 Log.i(LOG_TAG, "Can't talk to package managed", e);
6422 if (!systemService && !permittedList.contains(enabledPackage)) {
6427 mInjector.binderRestoreCallingIdentity(id);
6432 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
6433 // Not using AccessibilityManager.getInstance because that guesses
6434 // at the user you require based on callingUid and caches for a given
6436 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
6437 IAccessibilityManager service = iBinder == null
6438 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
6439 return new AccessibilityManager(mContext, service, userId);
6443 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
6447 Preconditions.checkNotNull(who, "ComponentName is null");
6449 if (packageList != null) {
6450 int userId = UserHandle.getCallingUserId();
6451 List<AccessibilityServiceInfo> enabledServices = null;
6452 long id = mInjector.binderClearCallingIdentity();
6454 UserInfo user = mUserManager.getUserInfo(userId);
6455 if (user.isManagedProfile()) {
6456 userId = user.profileGroupId;
6458 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
6459 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
6460 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
6462 mInjector.binderRestoreCallingIdentity(id);
6465 if (enabledServices != null) {
6466 List<String> enabledPackages = new ArrayList<String>();
6467 for (AccessibilityServiceInfo service : enabledServices) {
6468 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
6470 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6472 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
6473 + "because it contains already enabled accesibility services.");
6479 synchronized (this) {
6480 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6481 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6482 admin.permittedAccessiblityServices = packageList;
6483 saveSettingsLocked(UserHandle.getCallingUserId());
6489 public List getPermittedAccessibilityServices(ComponentName who) {
6493 Preconditions.checkNotNull(who, "ComponentName is null");
6495 synchronized (this) {
6496 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6497 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6498 return admin.permittedAccessiblityServices;
6503 public List getPermittedAccessibilityServicesForUser(int userId) {
6507 synchronized (this) {
6508 List<String> result = null;
6509 // If we have multiple profiles we return the intersection of the
6510 // permitted lists. This can happen in cases where we have a device
6511 // and profile owner.
6512 List<UserInfo> profiles = mUserManager.getProfiles(userId);
6513 final int PROFILES_SIZE = profiles.size();
6514 for (int i = 0; i < PROFILES_SIZE; ++i) {
6515 // Just loop though all admins, only device or profiles
6516 // owners can have permitted lists set.
6517 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
6518 final int N = policy.mAdminList.size();
6519 for (int j = 0; j < N; j++) {
6520 ActiveAdmin admin = policy.mAdminList.get(j);
6521 List<String> fromAdmin = admin.permittedAccessiblityServices;
6522 if (fromAdmin != null) {
6523 if (result == null) {
6524 result = new ArrayList<String>(fromAdmin);
6526 result.retainAll(fromAdmin);
6532 // If we have a permitted list add all system accessibility services.
6533 if (result != null) {
6534 long id = mInjector.binderClearCallingIdentity();
6536 UserInfo user = mUserManager.getUserInfo(userId);
6537 if (user.isManagedProfile()) {
6538 userId = user.profileGroupId;
6540 AccessibilityManager accessibilityManager =
6541 getAccessibilityManagerForUser(userId);
6542 List<AccessibilityServiceInfo> installedServices =
6543 accessibilityManager.getInstalledAccessibilityServiceList();
6545 if (installedServices != null) {
6546 for (AccessibilityServiceInfo service : installedServices) {
6547 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
6548 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
6549 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6550 result.add(serviceInfo.packageName);
6555 mInjector.binderRestoreCallingIdentity(id);
6564 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
6569 Preconditions.checkNotNull(who, "ComponentName is null");
6570 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
6571 if (!isCallerWithSystemUid()){
6572 throw new SecurityException(
6573 "Only the system can query if an accessibility service is disabled by admin");
6575 synchronized (this) {
6576 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6577 if (admin.permittedAccessiblityServices == null) {
6580 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
6581 admin.permittedAccessiblityServices, userHandle);
6585 private boolean checkCallerIsCurrentUserOrProfile() {
6586 int callingUserId = UserHandle.getCallingUserId();
6587 long token = mInjector.binderClearCallingIdentity();
6589 UserInfo currentUser;
6590 UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
6592 currentUser = mInjector.getIActivityManager().getCurrentUser();
6593 } catch (RemoteException e) {
6594 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
6598 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
6599 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
6600 + "of a user that isn't the foreground user.");
6603 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
6604 Slog.e(LOG_TAG, "Cannot set permitted input methods "
6605 + "of a user that isn't the foreground user.");
6609 mInjector.binderRestoreCallingIdentity(token);
6615 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
6619 Preconditions.checkNotNull(who, "ComponentName is null");
6621 // TODO When InputMethodManager supports per user calls remove
6622 // this restriction.
6623 if (!checkCallerIsCurrentUserOrProfile()) {
6627 if (packageList != null) {
6628 // InputMethodManager fetches input methods for current user.
6629 // So this can only be set when calling user is the current user
6630 // or parent is current user in case of managed profiles.
6631 InputMethodManager inputMethodManager =
6632 mContext.getSystemService(InputMethodManager.class);
6633 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
6635 if (enabledImes != null) {
6636 List<String> enabledPackages = new ArrayList<String>();
6637 for (InputMethodInfo ime : enabledImes) {
6638 enabledPackages.add(ime.getPackageName());
6640 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6641 mInjector.binderGetCallingUserHandle().getIdentifier())) {
6642 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
6643 + "because it contains already enabled input method.");
6649 synchronized (this) {
6650 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6651 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6652 admin.permittedInputMethods = packageList;
6653 saveSettingsLocked(UserHandle.getCallingUserId());
6659 public List getPermittedInputMethods(ComponentName who) {
6663 Preconditions.checkNotNull(who, "ComponentName is null");
6665 synchronized (this) {
6666 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6667 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6668 return admin.permittedInputMethods;
6673 public List getPermittedInputMethodsForCurrentUser() {
6674 UserInfo currentUser;
6676 currentUser = mInjector.getIActivityManager().getCurrentUser();
6677 } catch (RemoteException e) {
6678 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
6679 // Activity managed is dead, just allow all IMEs
6683 int userId = currentUser.id;
6684 synchronized (this) {
6685 List<String> result = null;
6686 // If we have multiple profiles we return the intersection of the
6687 // permitted lists. This can happen in cases where we have a device
6688 // and profile owner.
6689 List<UserInfo> profiles = mUserManager.getProfiles(userId);
6690 final int PROFILES_SIZE = profiles.size();
6691 for (int i = 0; i < PROFILES_SIZE; ++i) {
6692 // Just loop though all admins, only device or profiles
6693 // owners can have permitted lists set.
6694 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
6695 final int N = policy.mAdminList.size();
6696 for (int j = 0; j < N; j++) {
6697 ActiveAdmin admin = policy.mAdminList.get(j);
6698 List<String> fromAdmin = admin.permittedInputMethods;
6699 if (fromAdmin != null) {
6700 if (result == null) {
6701 result = new ArrayList<String>(fromAdmin);
6703 result.retainAll(fromAdmin);
6709 // If we have a permitted list add all system input methods.
6710 if (result != null) {
6711 InputMethodManager inputMethodManager =
6712 mContext.getSystemService(InputMethodManager.class);
6713 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
6714 long id = mInjector.binderClearCallingIdentity();
6717 for (InputMethodInfo ime : imes) {
6718 ServiceInfo serviceInfo = ime.getServiceInfo();
6719 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
6720 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6721 result.add(serviceInfo.packageName);
6726 mInjector.binderRestoreCallingIdentity(id);
6734 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
6739 Preconditions.checkNotNull(who, "ComponentName is null");
6740 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
6741 if (!isCallerWithSystemUid()) {
6742 throw new SecurityException(
6743 "Only the system can query if an input method is disabled by admin");
6745 synchronized (this) {
6746 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6747 if (admin.permittedInputMethods == null) {
6750 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
6751 admin.permittedInputMethods, userHandle);
6755 private void sendAdminEnabledBroadcastLocked(int userHandle) {
6756 DevicePolicyData policyData = getUserData(userHandle);
6757 if (policyData.mAdminBroadcastPending) {
6758 // Send the initialization data to profile owner and delete the data
6759 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
6760 if (admin != null) {
6761 PersistableBundle initBundle = policyData.mInitBundle;
6762 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
6763 initBundle == null ? null : new Bundle(initBundle), null);
6765 policyData.mInitBundle = null;
6766 policyData.mAdminBroadcastPending = false;
6767 saveSettingsLocked(userHandle);
6772 public UserHandle createAndManageUser(ComponentName admin, String name,
6773 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
6774 Preconditions.checkNotNull(admin, "admin is null");
6775 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
6776 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
6777 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
6778 + admin + " are not in the same package");
6780 // Only allow the system user to use this method
6781 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
6782 throw new SecurityException("createAndManageUser was called from non-system user");
6784 if (!mInjector.userManagerIsSplitSystemUser()
6785 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
6786 throw new IllegalArgumentException(
6787 "Ephemeral users are only supported on systems with a split system user.");
6790 UserHandle user = null;
6791 synchronized (this) {
6792 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6794 final long id = mInjector.binderClearCallingIdentity();
6796 int userInfoFlags = 0;
6797 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
6798 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
6800 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
6802 if (userInfo != null) {
6803 user = userInfo.getUserHandle();
6806 mInjector.binderRestoreCallingIdentity(id);
6813 final long id = mInjector.binderClearCallingIdentity();
6815 final String adminPkg = admin.getPackageName();
6817 final int userHandle = user.getIdentifier();
6819 // Install the profile owner if not present.
6820 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
6821 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
6823 } catch (RemoteException e) {
6824 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
6825 + "removing created user", e);
6826 mUserManager.removeUser(user.getIdentifier());
6830 setActiveAdmin(profileOwner, true, userHandle);
6831 // User is not started yet, the broadcast by setActiveAdmin will not be received.
6832 // So we store adminExtras for broadcasting when the user starts for first time.
6833 synchronized(this) {
6834 DevicePolicyData policyData = getUserData(userHandle);
6835 policyData.mInitBundle = adminExtras;
6836 policyData.mAdminBroadcastPending = true;
6837 saveSettingsLocked(userHandle);
6839 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
6840 setProfileOwner(profileOwner, ownerName, userHandle);
6842 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
6843 Settings.Secure.putIntForUser(mContext.getContentResolver(),
6844 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
6849 mInjector.binderRestoreCallingIdentity(id);
6854 public boolean removeUser(ComponentName who, UserHandle userHandle) {
6855 Preconditions.checkNotNull(who, "ComponentName is null");
6856 synchronized (this) {
6857 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6859 long id = mInjector.binderClearCallingIdentity();
6861 return mUserManager.removeUser(userHandle.getIdentifier());
6863 mInjector.binderRestoreCallingIdentity(id);
6869 public boolean switchUser(ComponentName who, UserHandle userHandle) {
6870 Preconditions.checkNotNull(who, "ComponentName is null");
6871 synchronized (this) {
6872 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6874 long id = mInjector.binderClearCallingIdentity();
6876 int userId = UserHandle.USER_SYSTEM;
6877 if (userHandle != null) {
6878 userId = userHandle.getIdentifier();
6880 return mInjector.getIActivityManager().switchUser(userId);
6881 } catch (RemoteException e) {
6882 Log.e(LOG_TAG, "Couldn't switch user", e);
6885 mInjector.binderRestoreCallingIdentity(id);
6891 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
6892 enforceCanManageApplicationRestrictions(who);
6894 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6895 final long id = mInjector.binderClearCallingIdentity();
6897 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
6898 // if no restrictions were saved, mUserManager.getApplicationRestrictions
6899 // returns null, but DPM method should return an empty Bundle as per JavaDoc
6900 return bundle != null ? bundle : Bundle.EMPTY;
6902 mInjector.binderRestoreCallingIdentity(id);
6907 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
6908 boolean suspended) {
6909 Preconditions.checkNotNull(who, "ComponentName is null");
6910 int callingUserId = UserHandle.getCallingUserId();
6911 synchronized (this) {
6912 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6914 long id = mInjector.binderClearCallingIdentity();
6916 return mIPackageManager.setPackagesSuspendedAsUser(
6917 packageNames, suspended, callingUserId);
6918 } catch (RemoteException re) {
6919 // Shouldn't happen.
6920 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
6922 mInjector.binderRestoreCallingIdentity(id);
6924 return packageNames;
6929 public boolean getPackageSuspended(ComponentName who, String packageName) {
6930 Preconditions.checkNotNull(who, "ComponentName is null");
6931 int callingUserId = UserHandle.getCallingUserId();
6932 synchronized (this) {
6933 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6935 long id = mInjector.binderClearCallingIdentity();
6937 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
6938 } catch (RemoteException re) {
6939 // Shouldn't happen.
6940 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
6942 mInjector.binderRestoreCallingIdentity(id);
6949 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
6950 Preconditions.checkNotNull(who, "ComponentName is null");
6951 if (!UserRestrictionsUtils.isValidRestriction(key)) {
6955 final int userHandle = mInjector.userHandleGetCallingUserId();
6956 synchronized (this) {
6957 ActiveAdmin activeAdmin =
6958 getActiveAdminForCallerLocked(who,
6959 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6960 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
6961 if (isDeviceOwner) {
6962 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
6963 throw new SecurityException("Device owner cannot set user restriction " + key);
6965 } else { // profile owner
6966 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
6967 throw new SecurityException("Profile owner cannot set user restriction " + key);
6971 // Save the restriction to ActiveAdmin.
6972 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
6973 saveSettingsLocked(userHandle);
6975 pushUserRestrictions(userHandle);
6977 sendChangedNotification(userHandle);
6981 private void pushUserRestrictions(int userId) {
6982 synchronized (this) {
6983 final Bundle global;
6984 final Bundle local = new Bundle();
6985 if (mOwners.isDeviceOwnerUserId(userId)) {
6986 global = new Bundle();
6988 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6989 if (deviceOwner == null) {
6990 return; // Shouldn't happen.
6993 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
6995 // DO can disable camera globally.
6996 if (deviceOwner.disableCamera) {
6997 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7002 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7003 if (profileOwner != null) {
7004 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7007 // Also merge in *local* camera restriction.
7008 if (getCameraDisabled(/* who= */ null,
7009 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7010 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7012 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7017 public Bundle getUserRestrictions(ComponentName who, int userHandle) {
7018 Preconditions.checkNotNull(who, "ComponentName is null");
7019 enforceFullCrossUsersPermission(userHandle);
7020 synchronized (this) {
7021 ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(who, userHandle);
7022 if (activeAdmin == null) {
7023 throw new SecurityException("No active admin: " + activeAdmin);
7025 if (activeAdmin.getUid() != mInjector.binderGetCallingUid()) {
7026 mContext.enforceCallingOrSelfPermission(
7027 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
7028 "Calling uid " + mInjector.binderGetCallingUid() + " neither owns the admin"
7029 + " " + who + " nor has MANAGE_PROFILE_AND_DEVICE_OWNERS permission");
7031 return activeAdmin.userRestrictions;
7036 public boolean setApplicationHidden(ComponentName who, String packageName,
7038 Preconditions.checkNotNull(who, "ComponentName is null");
7039 int callingUserId = UserHandle.getCallingUserId();
7040 synchronized (this) {
7041 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7043 long id = mInjector.binderClearCallingIdentity();
7045 return mIPackageManager.setApplicationHiddenSettingAsUser(
7046 packageName, hidden, callingUserId);
7047 } catch (RemoteException re) {
7049 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7051 mInjector.binderRestoreCallingIdentity(id);
7058 public boolean isApplicationHidden(ComponentName who, String packageName) {
7059 Preconditions.checkNotNull(who, "ComponentName is null");
7060 int callingUserId = UserHandle.getCallingUserId();
7061 synchronized (this) {
7062 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7064 long id = mInjector.binderClearCallingIdentity();
7066 return mIPackageManager.getApplicationHiddenSettingAsUser(
7067 packageName, callingUserId);
7068 } catch (RemoteException re) {
7070 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7072 mInjector.binderRestoreCallingIdentity(id);
7079 public void enableSystemApp(ComponentName who, String packageName) {
7080 Preconditions.checkNotNull(who, "ComponentName is null");
7081 synchronized (this) {
7082 // This API can only be called by an active device admin,
7083 // so try to retrieve it to check that the caller is one.
7084 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7086 int userId = UserHandle.getCallingUserId();
7087 long id = mInjector.binderClearCallingIdentity();
7091 Slog.v(LOG_TAG, "installing " + packageName + " for "
7095 int parentUserId = getProfileParentId(userId);
7096 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7097 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7101 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7103 } catch (RemoteException re) {
7105 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7107 mInjector.binderRestoreCallingIdentity(id);
7113 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7114 Preconditions.checkNotNull(who, "ComponentName is null");
7115 synchronized (this) {
7116 // This API can only be called by an active device admin,
7117 // so try to retrieve it to check that the caller is one.
7118 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7120 int userId = UserHandle.getCallingUserId();
7121 long id = mInjector.binderClearCallingIdentity();
7124 int parentUserId = getProfileParentId(userId);
7125 List<ResolveInfo> activitiesToEnable = mIPackageManager.queryIntentActivities(
7127 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7128 PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE,
7132 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7134 int numberOfAppsInstalled = 0;
7135 if (activitiesToEnable != null) {
7136 for (ResolveInfo info : activitiesToEnable) {
7137 if (info.activityInfo != null) {
7138 String packageName = info.activityInfo.packageName;
7139 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7140 numberOfAppsInstalled++;
7141 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7143 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7149 return numberOfAppsInstalled;
7150 } catch (RemoteException e) {
7152 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7155 mInjector.binderRestoreCallingIdentity(id);
7160 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7161 throws RemoteException {
7162 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7164 if (appInfo == null) {
7165 throw new IllegalArgumentException("The application " + packageName +
7166 " is not present on this device");
7168 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7172 public void setAccountManagementDisabled(ComponentName who, String accountType,
7177 Preconditions.checkNotNull(who, "ComponentName is null");
7178 synchronized (this) {
7179 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7180 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7182 ap.accountTypesWithManagementDisabled.add(accountType);
7184 ap.accountTypesWithManagementDisabled.remove(accountType);
7186 saveSettingsLocked(UserHandle.getCallingUserId());
7191 public String[] getAccountTypesWithManagementDisabled() {
7192 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7196 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7197 enforceFullCrossUsersPermission(userId);
7201 synchronized (this) {
7202 DevicePolicyData policy = getUserData(userId);
7203 final int N = policy.mAdminList.size();
7204 ArraySet<String> resultSet = new ArraySet<>();
7205 for (int i = 0; i < N; i++) {
7206 ActiveAdmin admin = policy.mAdminList.get(i);
7207 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7209 return resultSet.toArray(new String[resultSet.size()]);
7214 public void setUninstallBlocked(ComponentName who, String packageName,
7215 boolean uninstallBlocked) {
7216 Preconditions.checkNotNull(who, "ComponentName is null");
7217 final int userId = UserHandle.getCallingUserId();
7218 synchronized (this) {
7219 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7221 long id = mInjector.binderClearCallingIdentity();
7223 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7224 } catch (RemoteException re) {
7225 // Shouldn't happen.
7226 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7228 mInjector.binderRestoreCallingIdentity(id);
7234 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7235 // This function should return true if and only if the package is blocked by
7236 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7237 // when the package is a system app, or when it is an active device admin.
7238 final int userId = UserHandle.getCallingUserId();
7240 synchronized (this) {
7242 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7245 long id = mInjector.binderClearCallingIdentity();
7247 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7248 } catch (RemoteException re) {
7249 // Shouldn't happen.
7250 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7252 mInjector.binderRestoreCallingIdentity(id);
7259 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7263 Preconditions.checkNotNull(who, "ComponentName is null");
7264 synchronized (this) {
7265 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7266 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7267 if (admin.disableCallerId != disabled) {
7268 admin.disableCallerId = disabled;
7269 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7275 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7279 Preconditions.checkNotNull(who, "ComponentName is null");
7280 synchronized (this) {
7281 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7282 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7283 return admin.disableCallerId;
7288 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7289 enforceCrossUsersPermission(userId);
7290 synchronized (this) {
7291 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7292 return (admin != null) ? admin.disableCallerId : false;
7297 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7301 Preconditions.checkNotNull(who, "ComponentName is null");
7302 synchronized (this) {
7303 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7304 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7305 if (admin.disableContactsSearch != disabled) {
7306 admin.disableContactsSearch = disabled;
7307 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7313 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7317 Preconditions.checkNotNull(who, "ComponentName is null");
7318 synchronized (this) {
7319 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7320 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7321 return admin.disableContactsSearch;
7326 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7327 enforceCrossUsersPermission(userId);
7328 synchronized (this) {
7329 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7330 return (admin != null) ? admin.disableContactsSearch : false;
7335 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7336 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7337 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7338 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7339 final int callingUserId = UserHandle.getCallingUserId();
7341 final long ident = mInjector.binderClearCallingIdentity();
7343 synchronized (this) {
7344 final int managedUserId = getManagedUserId(callingUserId);
7345 if (managedUserId < 0) {
7348 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7351 "Cross-profile contacts access disabled for user " + managedUserId);
7355 ContactsInternal.startQuickContactWithErrorToastForUser(
7356 mContext, intent, new UserHandle(managedUserId));
7359 mInjector.binderRestoreCallingIdentity(ident);
7364 * @return true if cross-profile QuickContact is disabled
7366 private boolean isCrossProfileQuickContactDisabled(int userId) {
7367 return getCrossProfileCallerIdDisabledForUser(userId)
7368 && getCrossProfileContactsSearchDisabledForUser(userId);
7372 * @return the user ID of the managed user that is linked to the current user, if any.
7375 public int getManagedUserId(int callingUserId) {
7377 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7380 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7381 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7382 continue; // Caller user self, or not a managed profile. Skip.
7385 Log.v(LOG_TAG, "Managed user=" + ui.id);
7390 Log.v(LOG_TAG, "Managed user not found.");
7396 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7400 Preconditions.checkNotNull(who, "ComponentName is null");
7401 synchronized (this) {
7402 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7403 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7404 if (admin.disableBluetoothContactSharing != disabled) {
7405 admin.disableBluetoothContactSharing = disabled;
7406 saveSettingsLocked(UserHandle.getCallingUserId());
7412 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
7416 Preconditions.checkNotNull(who, "ComponentName is null");
7417 synchronized (this) {
7418 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7419 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7420 return admin.disableBluetoothContactSharing;
7425 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
7426 // TODO: Should there be a check to make sure this relationship is
7427 // within a profile group?
7428 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
7429 synchronized (this) {
7430 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7431 return (admin != null) ? admin.disableBluetoothContactSharing : false;
7436 * Sets which packages may enter lock task mode.
7438 * This function can only be called by the device owner.
7439 * @param packages The list of packages allowed to enter lock task mode.
7442 public void setLockTaskPackages(ComponentName who, String[] packages)
7443 throws SecurityException {
7444 Preconditions.checkNotNull(who, "ComponentName is null");
7445 synchronized (this) {
7446 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7448 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
7449 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
7453 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
7454 DevicePolicyData policy = getUserData(userHandle);
7455 policy.mLockTaskPackages = packages;
7457 // Store the settings persistently.
7458 saveSettingsLocked(userHandle);
7459 updateLockTaskPackagesLocked(packages, userHandle);
7463 * This function returns the list of components allowed to start the task lock mode.
7466 public String[] getLockTaskPackages(ComponentName who) {
7467 Preconditions.checkNotNull(who, "ComponentName is null");
7468 synchronized (this) {
7469 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7470 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
7471 final List<String> packages = getLockTaskPackagesLocked(userHandle);
7472 return packages.toArray(new String[packages.size()]);
7476 private List<String> getLockTaskPackagesLocked(int userHandle) {
7477 final DevicePolicyData policy = getUserData(userHandle);
7478 return policy.mLockTaskPackages;
7482 * This function lets the caller know whether the given package is allowed to start the
7484 * @param pkg The package to check
7487 public boolean isLockTaskPermitted(String pkg) {
7488 // Get current user's devicepolicy
7489 int uid = mInjector.binderGetCallingUid();
7490 int userHandle = UserHandle.getUserId(uid);
7491 DevicePolicyData policy = getUserData(userHandle);
7492 synchronized (this) {
7493 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
7494 String lockTaskPackage = policy.mLockTaskPackages.get(i);
7496 // If the given package equals one of the packages stored our list,
7497 // we allow this package to start lock task mode.
7498 if (lockTaskPackage.equals(pkg)) {
7507 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
7508 if (!isCallerWithSystemUid()) {
7509 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
7511 synchronized (this) {
7512 final DevicePolicyData policy = getUserData(userHandle);
7513 Bundle adminExtras = new Bundle();
7514 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
7515 for (ActiveAdmin admin : policy.mAdminList) {
7516 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
7517 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
7518 if (ownsDevice || ownsProfile) {
7520 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
7523 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
7531 public void setGlobalSetting(ComponentName who, String setting, String value) {
7532 Preconditions.checkNotNull(who, "ComponentName is null");
7534 synchronized (this) {
7535 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7537 // Some settings are no supported any more. However we do not want to throw a
7538 // SecurityException to avoid breaking apps.
7539 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
7540 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
7544 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
7545 throw new SecurityException(String.format(
7546 "Permission denial: device owners cannot update %1$s", setting));
7549 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
7550 // ignore if it contradicts an existing policy
7551 long timeMs = getMaximumTimeToLock(
7552 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
7553 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
7558 long id = mInjector.binderClearCallingIdentity();
7560 mInjector.settingsGlobalPutString(setting, value);
7562 mInjector.binderRestoreCallingIdentity(id);
7568 public void setSecureSetting(ComponentName who, String setting, String value) {
7569 Preconditions.checkNotNull(who, "ComponentName is null");
7570 int callingUserId = mInjector.userHandleGetCallingUserId();
7572 synchronized (this) {
7573 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7575 if (isDeviceOwner(who, callingUserId)) {
7576 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
7577 throw new SecurityException(String.format(
7578 "Permission denial: Device owners cannot update %1$s", setting));
7580 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
7581 throw new SecurityException(String.format(
7582 "Permission denial: Profile owners cannot update %1$s", setting));
7585 long id = mInjector.binderClearCallingIdentity();
7587 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
7589 mInjector.binderRestoreCallingIdentity(id);
7595 public void setMasterVolumeMuted(ComponentName who, boolean on) {
7596 Preconditions.checkNotNull(who, "ComponentName is null");
7597 synchronized (this) {
7598 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7599 int userId = UserHandle.getCallingUserId();
7600 long identity = mInjector.binderClearCallingIdentity();
7602 IAudioService iAudioService = IAudioService.Stub.asInterface(
7603 ServiceManager.getService(Context.AUDIO_SERVICE));
7604 iAudioService.setMasterMute(on, 0, mContext.getPackageName(), userId);
7605 } catch (RemoteException re) {
7606 Slog.e(LOG_TAG, "Failed to setMasterMute", re);
7608 mInjector.binderRestoreCallingIdentity(identity);
7614 public boolean isMasterVolumeMuted(ComponentName who) {
7615 Preconditions.checkNotNull(who, "ComponentName is null");
7616 synchronized (this) {
7617 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7619 AudioManager audioManager =
7620 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
7621 return audioManager.isMasterMute();
7626 public void setUserIcon(ComponentName who, Bitmap icon) {
7627 synchronized (this) {
7628 Preconditions.checkNotNull(who, "ComponentName is null");
7629 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7631 int userId = UserHandle.getCallingUserId();
7632 long id = mInjector.binderClearCallingIdentity();
7634 mUserManagerInternal.setUserIcon(userId, icon);
7636 mInjector.binderRestoreCallingIdentity(id);
7642 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
7643 Preconditions.checkNotNull(who, "ComponentName is null");
7644 synchronized (this) {
7645 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7647 final int userId = UserHandle.getCallingUserId();
7649 long ident = mInjector.binderClearCallingIdentity();
7651 // disallow disabling the keyguard if a password is currently set
7652 if (disabled && mLockPatternUtils.isSecure(userId)) {
7655 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
7657 mInjector.binderRestoreCallingIdentity(ident);
7663 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
7664 int userId = UserHandle.getCallingUserId();
7665 synchronized (this) {
7666 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7667 DevicePolicyData policy = getUserData(userId);
7668 if (policy.mStatusBarDisabled != disabled) {
7669 if (!setStatusBarDisabledInternal(disabled, userId)) {
7672 policy.mStatusBarDisabled = disabled;
7673 saveSettingsLocked(userId);
7679 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
7680 long ident = mInjector.binderClearCallingIdentity();
7682 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
7683 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
7684 if (statusBarService != null) {
7685 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
7686 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
7687 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
7688 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
7691 } catch (RemoteException e) {
7692 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
7694 mInjector.binderRestoreCallingIdentity(ident);
7700 * We need to update the internal state of whether a user has completed setup once. After
7701 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
7702 * as we don't trust any apps that might try to reset it.
7704 * Unfortunately, we don't know which user's setup state was changed, so we write all of
7707 void updateUserSetupComplete() {
7708 List<UserInfo> users = mUserManager.getUsers(true);
7709 final int N = users.size();
7710 for (int i = 0; i < N; i++) {
7711 int userHandle = users.get(i).id;
7712 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
7714 DevicePolicyData policy = getUserData(userHandle);
7715 if (!policy.mUserSetupComplete) {
7716 policy.mUserSetupComplete = true;
7717 synchronized (this) {
7718 saveSettingsLocked(userHandle);
7725 private class SetupContentObserver extends ContentObserver {
7727 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
7728 Settings.Secure.USER_SETUP_COMPLETE);
7729 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
7730 Settings.Global.DEVICE_PROVISIONED);
7732 public SetupContentObserver(Handler handler) {
7736 void register(ContentResolver resolver) {
7737 resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
7738 resolver.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
7742 public void onChange(boolean selfChange, Uri uri) {
7743 if (mUserSetupComplete.equals(uri)) {
7744 updateUserSetupComplete();
7745 } else if (mDeviceProvisioned.equals(uri)) {
7746 synchronized (DevicePolicyManagerService.this) {
7747 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
7748 // is delayed until device is marked as provisioned.
7749 setDeviceOwnerSystemPropertyLocked();
7756 final class LocalService extends DevicePolicyManagerInternal {
7757 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
7760 public List<String> getCrossProfileWidgetProviders(int profileId) {
7761 synchronized (DevicePolicyManagerService.this) {
7762 if (mOwners == null) {
7763 return Collections.emptyList();
7765 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
7766 if (ownerComponent == null) {
7767 return Collections.emptyList();
7770 DevicePolicyData policy = getUserDataUnchecked(profileId);
7771 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
7773 if (admin == null || admin.crossProfileWidgetProviders == null
7774 || admin.crossProfileWidgetProviders.isEmpty()) {
7775 return Collections.emptyList();
7778 return admin.crossProfileWidgetProviders;
7783 public void addOnCrossProfileWidgetProvidersChangeListener(
7784 OnCrossProfileWidgetProvidersChangeListener listener) {
7785 synchronized (DevicePolicyManagerService.this) {
7786 if (mWidgetProviderListeners == null) {
7787 mWidgetProviderListeners = new ArrayList<>();
7789 if (!mWidgetProviderListeners.contains(listener)) {
7790 mWidgetProviderListeners.add(listener);
7796 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
7797 synchronized(DevicePolicyManagerService.this) {
7798 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
7802 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
7803 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
7804 synchronized (DevicePolicyManagerService.this) {
7805 listeners = new ArrayList<>(mWidgetProviderListeners);
7807 final int listenerCount = listeners.size();
7808 for (int i = 0; i < listenerCount; i++) {
7809 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
7810 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
7816 * Returns true if specified admin is allowed to limit passwords and has a
7817 * {@code passwordQuality} of at least {@code minPasswordQuality}
7819 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
7820 if (admin.passwordQuality < minPasswordQuality) {
7823 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
7827 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
7828 if (policy != null && !policy.isValid()) {
7829 throw new IllegalArgumentException("Invalid system update policy.");
7831 synchronized (this) {
7832 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7833 if (policy == null) {
7834 mOwners.clearSystemUpdatePolicy();
7836 mOwners.setSystemUpdatePolicy(policy);
7838 mOwners.writeDeviceOwner();
7840 mContext.sendBroadcastAsUser(
7841 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
7846 public SystemUpdatePolicy getSystemUpdatePolicy() {
7847 synchronized (this) {
7848 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
7849 if (policy != null && !policy.isValid()) {
7850 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
7858 * Checks if the caller of the method is the device owner app.
7860 * @param callerUid UID of the caller.
7861 * @return true if the caller is the device owner app
7864 boolean isCallerDeviceOwner(int callerUid) {
7865 synchronized (this) {
7866 if (!mOwners.hasDeviceOwner()) {
7869 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
7872 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
7874 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
7876 for (String pkg : pkgs) {
7877 if (deviceOwnerPackageName.equals(pkg)) {
7887 public void notifyPendingSystemUpdate(long updateReceivedTime) {
7888 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
7889 "Only the system update service can broadcast update information");
7891 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
7892 Slog.w(LOG_TAG, "Only the system update service in the system user " +
7893 "can broadcast update information.");
7896 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
7897 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
7898 updateReceivedTime);
7900 synchronized (this) {
7901 final String deviceOwnerPackage =
7902 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
7904 if (deviceOwnerPackage == null) {
7907 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
7909 ActivityInfo[] receivers = null;
7911 receivers = mContext.getPackageManager().getPackageInfo(
7912 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
7913 } catch (NameNotFoundException e) {
7914 Log.e(LOG_TAG, "Cannot find device owner package", e);
7916 if (receivers != null) {
7917 long ident = mInjector.binderClearCallingIdentity();
7919 for (int i = 0; i < receivers.length; i++) {
7920 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
7921 intent.setComponent(new ComponentName(deviceOwnerPackage,
7922 receivers[i].name));
7923 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
7927 mInjector.binderRestoreCallingIdentity(ident);
7934 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
7935 int userId = UserHandle.getCallingUserId();
7936 synchronized (this) {
7937 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7938 DevicePolicyData userPolicy = getUserData(userId);
7939 if (userPolicy.mPermissionPolicy != policy) {
7940 userPolicy.mPermissionPolicy = policy;
7941 saveSettingsLocked(userId);
7947 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
7948 int userId = UserHandle.getCallingUserId();
7949 synchronized (this) {
7950 DevicePolicyData userPolicy = getUserData(userId);
7951 return userPolicy.mPermissionPolicy;
7956 public boolean setPermissionGrantState(ComponentName admin, String packageName,
7957 String permission, int grantState) throws RemoteException {
7958 UserHandle user = mInjector.binderGetCallingUserHandle();
7959 synchronized (this) {
7960 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7961 long ident = mInjector.binderClearCallingIdentity();
7963 if (getTargetSdk(packageName, user.getIdentifier())
7964 < android.os.Build.VERSION_CODES.M) {
7967 final PackageManager packageManager = mContext.getPackageManager();
7968 switch (grantState) {
7969 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
7970 packageManager.grantRuntimePermission(packageName, permission, user);
7971 packageManager.updatePermissionFlags(permission, packageName,
7972 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
7973 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
7976 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
7977 packageManager.revokeRuntimePermission(packageName,
7979 packageManager.updatePermissionFlags(permission, packageName,
7980 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
7981 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
7984 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
7985 packageManager.updatePermissionFlags(permission, packageName,
7986 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
7990 } catch (SecurityException se) {
7993 mInjector.binderRestoreCallingIdentity(ident);
7999 public int getPermissionGrantState(ComponentName admin, String packageName,
8000 String permission) throws RemoteException {
8001 PackageManager packageManager = mContext.getPackageManager();
8003 UserHandle user = mInjector.binderGetCallingUserHandle();
8004 synchronized (this) {
8005 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8006 long ident = mInjector.binderClearCallingIdentity();
8008 int granted = mIPackageManager.checkPermission(permission,
8009 packageName, user.getIdentifier());
8010 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8011 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8012 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8013 // Not controlled by policy
8014 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8016 // Policy controlled so return result based on permission grant state
8017 return granted == PackageManager.PERMISSION_GRANTED
8018 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8019 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8022 mInjector.binderRestoreCallingIdentity(ident);
8027 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8029 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8031 return (pi != null) && (pi.applicationInfo.flags != 0);
8032 } catch (RemoteException re) {
8033 throw new RuntimeException("Package manager has died", re);
8038 public boolean isProvisioningAllowed(String action) {
8039 final int callingUserId = mInjector.userHandleGetCallingUserId();
8040 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8041 if (!hasFeatureManagedUsers()) {
8044 synchronized (this) {
8045 if (mOwners.hasDeviceOwner()) {
8046 if (!mInjector.userManagerIsSplitSystemUser()) {
8047 // Only split-system-user systems support managed-profiles in combination with
8051 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8052 // Only system device-owner supports managed-profiles. Non-system device-owner
8056 if (callingUserId == UserHandle.USER_SYSTEM) {
8057 // Managed-profiles cannot be setup on the system user, only regular users.
8062 if (getProfileOwner(callingUserId) != null) {
8063 // Managed user cannot have a managed profile.
8066 final long ident = mInjector.binderClearCallingIdentity();
8068 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8072 mInjector.binderRestoreCallingIdentity(ident);
8075 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8076 return isDeviceOwnerProvisioningAllowed(callingUserId);
8077 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8078 if (!hasFeatureManagedUsers()) {
8081 if (!mInjector.userManagerIsSplitSystemUser()) {
8082 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8085 if (callingUserId == UserHandle.USER_SYSTEM) {
8086 // System user cannot be a managed user.
8089 if (hasUserSetupCompleted(callingUserId)) {
8093 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8094 if (!mInjector.userManagerIsSplitSystemUser()) {
8095 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8098 return isDeviceOwnerProvisioningAllowed(callingUserId);
8100 throw new IllegalArgumentException("Unknown provisioning action " + action);
8103 private boolean isDeviceOwnerProvisioningAllowed(int callingUserId) {
8104 synchronized (this) {
8105 if (mOwners.hasDeviceOwner()) {
8109 if (getProfileOwner(callingUserId) != null) {
8112 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
8115 if (callingUserId != UserHandle.USER_SYSTEM) {
8116 // Device owner provisioning can only be initiated from system user.
8122 private boolean hasFeatureManagedUsers() {
8124 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8125 } catch (RemoteException e) {
8131 public String getWifiMacAddress() {
8132 // Make sure caller has DO.
8133 synchronized (this) {
8134 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8137 final long ident = mInjector.binderClearCallingIdentity();
8139 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8140 if (wifiInfo == null) {
8143 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8145 mInjector.binderRestoreCallingIdentity(ident);
8150 * Returns the target sdk version number that the given packageName was built for
8151 * in the given user.
8153 private int getTargetSdk(String packageName, int userId) throws RemoteException {
8154 final ApplicationInfo ai = mIPackageManager
8155 .getApplicationInfo(packageName, 0, userId);
8156 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8157 return targetSdkVersion;
8161 public boolean isManagedProfile(ComponentName admin) {
8162 synchronized (this) {
8163 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8165 final int callingUserId = mInjector.userHandleGetCallingUserId();
8166 final UserInfo user;
8167 long ident = mInjector.binderClearCallingIdentity();
8169 user = mUserManager.getUserInfo(callingUserId);
8171 mInjector.binderRestoreCallingIdentity(ident);
8173 return user != null && user.isManagedProfile();
8177 public boolean isSystemOnlyUser(ComponentName admin) {
8178 synchronized (this) {
8179 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8181 final int callingUserId = mInjector.userHandleGetCallingUserId();
8182 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8186 public void reboot(ComponentName admin) {
8187 Preconditions.checkNotNull(admin);
8188 // Make sure caller has DO.
8189 synchronized (this) {
8190 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8192 long ident = mInjector.binderClearCallingIdentity();
8194 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8196 mInjector.binderRestoreCallingIdentity(ident);
8201 public void setShortSupportMessage(@NonNull ComponentName who, String message) {
8205 Preconditions.checkNotNull(who, "ComponentName is null");
8206 final int userHandle = mInjector.userHandleGetCallingUserId();
8207 synchronized (this) {
8208 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8209 mInjector.binderGetCallingUid());
8210 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8211 admin.shortSupportMessage = message;
8212 saveSettingsLocked(userHandle);
8218 public String getShortSupportMessage(@NonNull ComponentName who) {
8222 Preconditions.checkNotNull(who, "ComponentName is null");
8223 synchronized (this) {
8224 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8225 mInjector.binderGetCallingUid());
8226 return admin.shortSupportMessage;
8231 public void setLongSupportMessage(@NonNull ComponentName who, String message) {
8235 Preconditions.checkNotNull(who, "ComponentName is null");
8236 final int userHandle = mInjector.userHandleGetCallingUserId();
8237 synchronized (this) {
8238 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8239 mInjector.binderGetCallingUid());
8240 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8241 admin.longSupportMessage = message;
8242 saveSettingsLocked(userHandle);
8248 public String getLongSupportMessage(@NonNull ComponentName who) {
8252 Preconditions.checkNotNull(who, "ComponentName is null");
8253 synchronized (this) {
8254 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8255 mInjector.binderGetCallingUid());
8256 return admin.longSupportMessage;
8261 public String getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8265 Preconditions.checkNotNull(who, "ComponentName is null");
8266 if (!isCallerWithSystemUid()) {
8267 throw new SecurityException("Only the system can query support message for user");
8269 synchronized (this) {
8270 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8271 if (admin != null) {
8272 return admin.shortSupportMessage;
8279 public String getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8283 Preconditions.checkNotNull(who, "ComponentName is null");
8284 if (!isCallerWithSystemUid()) {
8285 throw new SecurityException("Only the system can query support message for user");
8287 synchronized (this) {
8288 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8289 if (admin != null) {
8290 return admin.longSupportMessage;
8297 public void setOrganizationColor(@NonNull ComponentName who, int color) {
8301 Preconditions.checkNotNull(who, "ComponentName is null");
8302 final int userHandle = mInjector.userHandleGetCallingUserId();
8303 enforceManagedProfile(userHandle, "set organization color");
8304 synchronized (this) {
8305 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8306 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8307 admin.organizationColor = color;
8308 saveSettingsLocked(userHandle);
8313 public void setOrganizationColorForUser(int color, int userId) {
8317 enforceFullCrossUsersPermission(userId);
8318 enforceManageUsers();
8319 enforceManagedProfile(userId, "set organization color");
8320 synchronized (this) {
8321 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8322 admin.organizationColor = color;
8323 saveSettingsLocked(userId);
8328 public int getOrganizationColor(@NonNull ComponentName who) {
8330 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8332 Preconditions.checkNotNull(who, "ComponentName is null");
8333 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
8334 synchronized (this) {
8335 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8336 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8337 return admin.organizationColor;
8342 public int getOrganizationColorForUser(int userHandle) {
8344 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8346 enforceFullCrossUsersPermission(userHandle);
8347 enforceManagedProfile(userHandle, "get organization color");
8348 synchronized (this) {
8349 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8350 return (profileOwner != null)
8351 ? profileOwner.organizationColor
8352 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
8357 public void setOrganizationName(@NonNull ComponentName who, String text) {
8361 Preconditions.checkNotNull(who, "ComponentName is null");
8362 final int userHandle = mInjector.userHandleGetCallingUserId();
8363 enforceManagedProfile(userHandle, "set organization name");
8364 synchronized (this) {
8365 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8366 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8367 if (!TextUtils.equals(admin.organizationName, text)) {
8368 admin.organizationName = TextUtils.nullIfEmpty(text);
8369 saveSettingsLocked(userHandle);
8375 public String getOrganizationName(@NonNull ComponentName who) {
8379 Preconditions.checkNotNull(who, "ComponentName is null");
8380 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
8381 synchronized(this) {
8382 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8383 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8384 return admin.organizationName;
8389 public String getOrganizationNameForUser(int userHandle) {
8393 enforceFullCrossUsersPermission(userHandle);
8394 enforceManagedProfile(userHandle, "get organization name");
8395 synchronized (this) {
8396 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8397 return (profileOwner != null)
8398 ? profileOwner.organizationName
8404 public void setAffiliationIds(ComponentName admin, List<String> ids) {
8405 final Set<String> affiliationIds = new ArraySet<String>(ids);
8406 final int callingUserId = mInjector.userHandleGetCallingUserId();
8408 synchronized (this) {
8409 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8410 getUserData(callingUserId).mAffiliationIds = affiliationIds;
8411 saveSettingsLocked(callingUserId);
8412 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
8413 // Affiliation ids specified by the device owner are additionally stored in
8414 // UserHandle.USER_SYSTEM's DevicePolicyData.
8415 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
8416 saveSettingsLocked(UserHandle.USER_SYSTEM);
8422 public boolean isAffiliatedUser() {
8423 final int callingUserId = mInjector.userHandleGetCallingUserId();
8425 synchronized (this) {
8426 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
8427 // The user that the DO is installed on is always affiliated.
8430 final ComponentName profileOwner = getProfileOwner(callingUserId);
8431 if (profileOwner == null
8432 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
8435 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
8436 final Set<String> deviceAffiliationIds =
8437 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
8438 for (String id : userAffiliationIds) {
8439 if (deviceAffiliationIds.contains(id)) {
8447 private synchronized void disableDeviceLoggingIfNotCompliant() {
8448 if (!isDeviceOwnerManagedSingleUserDevice()) {
8449 mInjector.securityLogSetLoggingEnabledProperty(false);
8450 Slog.w(LOG_TAG, "Device logging turned off as it's no longer a single user device.");
8455 public void setDeviceLoggingEnabled(ComponentName admin, boolean enabled) {
8456 Preconditions.checkNotNull(admin);
8457 ensureDeviceOwnerManagingSingleUser(admin);
8459 synchronized (this) {
8460 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
8463 mInjector.securityLogSetLoggingEnabledProperty(enabled);
8465 mSecurityLogMonitor.start();
8467 mSecurityLogMonitor.stop();
8473 public boolean getDeviceLoggingEnabled(ComponentName admin) {
8474 Preconditions.checkNotNull(admin);
8475 synchronized (this) {
8476 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8477 return mInjector.securityLogGetLoggingEnabledProperty();
8482 public ParceledListSlice<SecurityEvent> retrievePreviousDeviceLogs(ComponentName admin) {
8483 Preconditions.checkNotNull(admin);
8484 ensureDeviceOwnerManagingSingleUser(admin);
8486 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
8488 SecurityLog.readPreviousEvents(output);
8489 return new ParceledListSlice<SecurityEvent>(output);
8490 } catch (IOException e) {
8491 Slog.w(LOG_TAG, "Fail to read previous events" , e);
8492 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
8497 public ParceledListSlice<SecurityEvent> retrieveDeviceLogs(ComponentName admin) {
8498 Preconditions.checkNotNull(admin);
8499 ensureDeviceOwnerManagingSingleUser(admin);
8501 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
8502 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
8505 private void enforceCanManageDeviceAdmin() {
8506 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
8511 public boolean isUninstallInQueue(final String packageName) {
8512 enforceCanManageDeviceAdmin();
8513 final int userId = mInjector.userHandleGetCallingUserId();
8514 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8515 synchronized (this) {
8516 return mPackagesToRemove.contains(packageUserPair);
8521 public void uninstallPackageWithActiveAdmins(final String packageName) {
8522 enforceCanManageDeviceAdmin();
8523 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
8525 final int userId = mInjector.userHandleGetCallingUserId();
8527 enforceUserUnlocked(userId);
8529 final ComponentName profileOwner = getProfileOwner(userId);
8530 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
8531 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
8534 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
8535 if (getDeviceOwnerUserId() == userId && deviceOwner != null
8536 && packageName.equals(deviceOwner.getPackageName())) {
8537 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
8540 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8541 synchronized (this) {
8542 mPackagesToRemove.add(packageUserPair);
8545 // All active admins on the user.
8546 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
8548 // Active admins in the target package.
8549 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
8550 if (allActiveAdmins != null) {
8551 for (ComponentName activeAdmin : allActiveAdmins) {
8552 if (packageName.equals(activeAdmin.getPackageName())) {
8553 packageActiveAdmins.add(activeAdmin);
8554 removeActiveAdmin(activeAdmin, userId);
8558 if (packageActiveAdmins.size() == 0) {
8559 startUninstallIntent(packageName, userId);
8561 mHandler.postDelayed(new Runnable() {
8564 for (ComponentName activeAdmin : packageActiveAdmins) {
8565 removeAdminArtifacts(activeAdmin, userId);
8567 startUninstallIntent(packageName, userId);
8569 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
8573 private void removePackageIfRequired(final String packageName, final int userId) {
8574 if (!packageHasActiveAdmins(packageName, userId)) {
8575 // Will not do anything if uninstall was not requested or was already started.
8576 startUninstallIntent(packageName, userId);
8580 private void startUninstallIntent(final String packageName, final int userId) {
8581 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8582 synchronized (this) {
8583 if (!mPackagesToRemove.contains(packageUserPair)) {
8584 // Do nothing if uninstall was not requested or was already started.
8587 mPackagesToRemove.remove(packageUserPair);
8590 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
8591 // Package does not exist. Nothing to do.
8594 } catch (RemoteException re) {
8595 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
8598 try { // force stop the package before uninstalling
8599 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
8600 } catch (RemoteException re) {
8601 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
8603 final Uri packageURI = Uri.parse("package:" + packageName);
8604 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
8605 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8606 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
8610 * Removes the admin from the policy. Ideally called after the admin's
8611 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
8613 * @param adminReceiver The admin to remove
8614 * @param userHandle The user for which this admin has to be removed.
8616 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
8617 synchronized (this) {
8618 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
8619 if (admin == null) {
8622 final DevicePolicyData policy = getUserData(userHandle);
8623 final boolean doProxyCleanup = admin.info.usesPolicy(
8624 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
8625 policy.mAdminList.remove(admin);
8626 policy.mAdminMap.remove(adminReceiver);
8627 validatePasswordOwnerLocked(policy);
8628 if (doProxyCleanup) {
8629 resetGlobalProxyLocked(policy);
8631 saveSettingsLocked(userHandle);
8632 updateMaximumTimeToLockLocked(userHandle);
8633 policy.mRemovingAdmins.remove(adminReceiver);
8635 // The removed admin might have disabled camera, so update user
8637 pushUserRestrictions(userHandle);