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;
25 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
26 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
27 import static org.xmlpull.v1.XmlPullParser.END_TAG;
28 import static org.xmlpull.v1.XmlPullParser.TEXT;
30 import android.Manifest.permission;
31 import android.accessibilityservice.AccessibilityServiceInfo;
32 import android.accounts.Account;
33 import android.accounts.AccountManager;
34 import android.annotation.IntDef;
35 import android.annotation.NonNull;
36 import android.annotation.Nullable;
37 import android.annotation.UserIdInt;
38 import android.app.Activity;
39 import android.app.ActivityManager;
40 import android.app.ActivityManagerNative;
41 import android.app.AlarmManager;
42 import android.app.AppGlobals;
43 import android.app.IActivityManager;
44 import android.app.Notification;
45 import android.app.NotificationManager;
46 import android.app.PendingIntent;
47 import android.app.StatusBarManager;
48 import android.app.admin.DeviceAdminInfo;
49 import android.app.admin.DeviceAdminReceiver;
50 import android.app.admin.DevicePolicyManager;
51 import android.app.admin.DevicePolicyManagerInternal;
52 import android.app.admin.IDevicePolicyManager;
53 import android.app.admin.SecurityLog;
54 import android.app.admin.SecurityLog.SecurityEvent;
55 import android.app.admin.SystemUpdatePolicy;
56 import android.app.backup.IBackupManager;
57 import android.app.trust.TrustManager;
58 import android.content.BroadcastReceiver;
59 import android.content.ComponentName;
60 import android.content.Context;
61 import android.content.Intent;
62 import android.content.IntentFilter;
63 import android.content.pm.ActivityInfo;
64 import android.content.pm.ApplicationInfo;
65 import android.content.pm.IPackageManager;
66 import android.content.pm.PackageInfo;
67 import android.content.pm.PackageManager;
68 import android.content.pm.PackageManager.NameNotFoundException;
69 import android.content.pm.PackageManagerInternal;
70 import android.content.pm.ParceledListSlice;
71 import android.content.pm.ResolveInfo;
72 import android.content.pm.ServiceInfo;
73 import android.content.pm.UserInfo;
74 import android.database.ContentObserver;
75 import android.graphics.Bitmap;
76 import android.graphics.Color;
77 import android.media.AudioManager;
78 import android.media.IAudioService;
79 import android.net.ConnectivityManager;
80 import android.net.ProxyInfo;
81 import android.net.Uri;
82 import android.net.wifi.WifiInfo;
83 import android.net.wifi.WifiManager;
84 import android.os.AsyncTask;
85 import android.os.Binder;
86 import android.os.Build;
87 import android.os.Bundle;
88 import android.os.Environment;
89 import android.os.FileUtils;
90 import android.os.Handler;
91 import android.os.IBinder;
92 import android.os.Looper;
93 import android.os.ParcelFileDescriptor;
94 import android.os.PersistableBundle;
95 import android.os.PowerManager;
96 import android.os.PowerManagerInternal;
97 import android.os.Process;
98 import android.os.RecoverySystem;
99 import android.os.RemoteCallback;
100 import android.os.RemoteException;
101 import android.os.ServiceManager;
102 import android.os.SystemClock;
103 import android.os.SystemProperties;
104 import android.os.UserHandle;
105 import android.os.UserManager;
106 import android.os.UserManagerInternal;
107 import android.os.storage.StorageManager;
108 import android.provider.ContactsContract.QuickContact;
109 import android.provider.ContactsInternal;
110 import android.provider.Settings;
111 import android.security.Credentials;
112 import android.security.IKeyChainAliasCallback;
113 import android.security.IKeyChainService;
114 import android.security.KeyChain;
115 import android.security.KeyChain.KeyChainConnection;
116 import android.service.persistentdata.PersistentDataBlockManager;
117 import android.telephony.TelephonyManager;
118 import android.text.TextUtils;
119 import android.util.ArrayMap;
120 import android.util.ArraySet;
121 import android.util.Log;
122 import android.util.Pair;
123 import android.util.Slog;
124 import android.util.SparseArray;
125 import android.util.Xml;
126 import android.view.IWindowManager;
127 import android.view.accessibility.AccessibilityManager;
128 import android.view.accessibility.IAccessibilityManager;
129 import android.view.inputmethod.InputMethodInfo;
130 import android.view.inputmethod.InputMethodManager;
132 import com.android.internal.R;
133 import com.android.internal.annotations.VisibleForTesting;
134 import com.android.internal.statusbar.IStatusBarService;
135 import com.android.internal.util.FastXmlSerializer;
136 import com.android.internal.util.JournaledFile;
137 import com.android.internal.util.ParcelableString;
138 import com.android.internal.util.Preconditions;
139 import com.android.internal.util.XmlUtils;
140 import com.android.internal.widget.LockPatternUtils;
141 import com.android.server.LocalServices;
142 import com.android.server.SystemService;
143 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
144 import com.android.server.pm.UserRestrictionsUtils;
145 import com.google.android.collect.Sets;
147 import org.xmlpull.v1.XmlPullParser;
148 import org.xmlpull.v1.XmlPullParserException;
149 import org.xmlpull.v1.XmlSerializer;
151 import java.io.ByteArrayInputStream;
153 import java.io.FileDescriptor;
154 import java.io.FileInputStream;
155 import java.io.FileNotFoundException;
156 import java.io.FileOutputStream;
157 import java.io.IOException;
158 import java.io.PrintWriter;
159 import java.lang.annotation.Retention;
160 import java.lang.annotation.RetentionPolicy;
161 import java.nio.charset.StandardCharsets;
162 import java.security.cert.CertificateException;
163 import java.security.cert.CertificateFactory;
164 import java.security.cert.X509Certificate;
165 import java.text.DateFormat;
166 import java.util.ArrayList;
167 import java.util.Arrays;
168 import java.util.Collections;
169 import java.util.Date;
170 import java.util.List;
171 import java.util.Map.Entry;
172 import java.util.Set;
173 import java.util.concurrent.atomic.AtomicBoolean;
176 * Implementation of the device policy APIs.
178 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
180 private static final String LOG_TAG = "DevicePolicyManagerService";
182 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
184 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
186 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
188 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
190 private static final String TAG_STATUS_BAR = "statusbar";
192 private static final String ATTR_DISABLED = "disabled";
194 private static final String ATTR_NAME = "name";
196 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
197 "do-not-ask-credentials-on-boot";
199 private static final String TAG_AFFILIATION_ID = "affiliation-id";
201 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
203 private static final String ATTR_VALUE = "value";
205 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
207 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
209 private static final long MS_PER_DAY = 86400 * 1000;
211 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
213 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
214 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
216 private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
217 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
219 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
220 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
221 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
222 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
223 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
224 "device-provisioning-config-applied";
226 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
227 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
228 = "application-restrictions-manager";
231 * System property whose value is either "true" or "false", indicating whether
233 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
235 private static final int STATUS_BAR_DISABLE_MASK =
236 StatusBarManager.DISABLE_EXPAND |
237 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
238 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
239 StatusBarManager.DISABLE_SEARCH;
241 private static final int STATUS_BAR_DISABLE2_MASK =
242 StatusBarManager.DISABLE2_QUICK_SETTINGS;
244 private static final Set<String> SECURE_SETTINGS_WHITELIST;
245 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
246 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
247 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
249 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
250 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
251 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
252 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
254 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
255 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
256 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
258 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
259 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
260 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
261 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
262 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
263 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
264 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
265 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
266 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
268 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
269 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
270 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
271 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
272 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
273 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
277 * Keyguard features that when set on a managed profile that doesn't have its own challenge will
278 * affect the profile's parent user. These can also be set on the managed profile's parent DPM
281 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
282 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
283 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
286 * Keyguard features that when set on a profile affect the profile content or challenge only.
287 * These cannot be set on the managed profile's parent DPM instance
289 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
290 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
292 /** Keyguard features that are allowed to be set on a managed profile */
293 private static final int PROFILE_KEYGUARD_FEATURES =
294 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
296 private static final int CODE_OK = 0;
297 private static final int CODE_HAS_DEVICE_OWNER = 1;
298 private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
299 private static final int CODE_USER_NOT_RUNNING = 3;
300 private static final int CODE_USER_SETUP_COMPLETED = 4;
301 private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
302 private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
303 private static final int CODE_NOT_SYSTEM_USER = 7;
305 @Retention(RetentionPolicy.SOURCE)
306 @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
307 CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
308 private @interface DeviceOwnerPreConditionCode {}
310 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
312 final Context mContext;
313 final Injector mInjector;
314 final IPackageManager mIPackageManager;
315 final UserManager mUserManager;
316 final UserManagerInternal mUserManagerInternal;
317 final TelephonyManager mTelephonyManager;
318 private final LockPatternUtils mLockPatternUtils;
321 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
322 * is requested for user u.
324 private final Set<Pair<String, Integer>> mPackagesToRemove =
325 new ArraySet<Pair<String, Integer>>();
327 final LocalService mLocalService;
329 // Stores and loads state on device and profile owners.
331 final Owners mOwners;
333 private final Binder mToken = new Binder();
336 * Whether or not device admin feature is supported. If it isn't return defaults for all
341 private final SecurityLogMonitor mSecurityLogMonitor;
343 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
344 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
346 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
349 if(mRemoteBugreportServiceIsActive.get()) {
355 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
358 public void onReceive(Context context, Intent intent) {
359 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
360 && mRemoteBugreportServiceIsActive.get()) {
361 onBugreportFinished(intent);
366 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
369 public void onReceive(Context context, Intent intent) {
370 String action = intent.getAction();
371 mInjector.getNotificationManager().cancel(LOG_TAG,
372 RemoteBugreportUtils.NOTIFICATION_ID);
373 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
374 onBugreportSharingAccepted();
375 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
376 onBugreportSharingDeclined();
378 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
382 public static final class Lifecycle extends SystemService {
383 private DevicePolicyManagerService mService;
385 public Lifecycle(Context context) {
387 mService = new DevicePolicyManagerService(context);
391 public void onStart() {
392 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
396 public void onBootPhase(int phase) {
397 mService.systemReady(phase);
401 public void onStartUser(int userHandle) {
402 mService.onStartUser(userHandle);
406 public static class DevicePolicyData {
407 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
408 int mActivePasswordLength = 0;
409 int mActivePasswordUpperCase = 0;
410 int mActivePasswordLowerCase = 0;
411 int mActivePasswordLetters = 0;
412 int mActivePasswordNumeric = 0;
413 int mActivePasswordSymbols = 0;
414 int mActivePasswordNonLetter = 0;
415 int mFailedPasswordAttempts = 0;
418 int mPasswordOwner = -1;
419 long mLastMaximumTimeToLock = -1;
420 boolean mUserSetupComplete = false;
421 int mUserProvisioningState;
422 int mPermissionPolicy;
424 boolean mDeviceProvisioningConfigApplied = false;
426 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
427 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
428 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
430 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
432 // This is the list of component allowed to start lock task mode.
433 List<String> mLockTaskPackages = new ArrayList<>();
435 boolean mStatusBarDisabled = false;
437 ComponentName mRestrictionsProvider;
439 String mDelegatedCertInstallerPackage;
441 boolean doNotAskCredentialsOnBoot = false;
443 String mApplicationRestrictionsManagingPackage;
445 Set<String> mAffiliationIds = new ArraySet<>();
447 // Used for initialization of users created by createAndManageUsers.
448 boolean mAdminBroadcastPending = false;
449 PersistableBundle mInitBundle = null;
451 public DevicePolicyData(int userHandle) {
452 mUserHandle = userHandle;
456 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
458 final Handler mHandler;
460 BroadcastReceiver mReceiver = new BroadcastReceiver() {
462 public void onReceive(Context context, Intent intent) {
463 final String action = intent.getAction();
464 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
467 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
468 && userHandle == mOwners.getDeviceOwnerUserId()
469 && getDeviceOwnerRemoteBugreportUri() != null) {
470 IntentFilter filterConsent = new IntentFilter();
471 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
472 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
473 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
474 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
475 RemoteBugreportUtils.NOTIFICATION_ID,
476 RemoteBugreportUtils.buildNotification(mContext,
477 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
480 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
481 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
483 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
484 + action + " for user " + userHandle);
486 mHandler.post(new Runnable() {
489 handlePasswordExpirationNotification(userHandle);
493 if (Intent.ACTION_USER_UNLOCKED.equals(action)
494 || Intent.ACTION_USER_STARTED.equals(action)
495 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
496 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
497 new MonitoringCertNotificationTask().execute(userId);
499 if (Intent.ACTION_USER_ADDED.equals(action)) {
500 disableSecurityLoggingIfNotCompliant();
501 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
502 disableSecurityLoggingIfNotCompliant();
503 removeUserData(userHandle);
504 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
505 synchronized (DevicePolicyManagerService.this) {
506 // Reset the policy data
507 mUserData.remove(userHandle);
508 sendAdminEnabledBroadcastLocked(userHandle);
510 handlePackagesChanged(null /* check all admins */, userHandle);
511 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
512 handlePackagesChanged(null /* check all admins */, userHandle);
513 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
514 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
515 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
516 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
517 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
518 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
519 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
520 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
521 clearWipeProfileNotification();
526 static class ActiveAdmin {
527 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
528 private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
529 private static final String TAG_DISABLE_CAMERA = "disable-camera";
530 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
531 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
532 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
533 = "disable-bt-contacts-sharing";
534 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
535 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
536 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
537 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
538 private static final String TAG_ACCOUNT_TYPE = "account-type";
539 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
540 = "permitted-accessiblity-services";
541 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
542 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
543 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
544 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
545 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
546 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
547 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
548 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
549 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
550 private static final String TAG_PERMITTED_IMES = "permitted-imes";
551 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
552 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
553 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
554 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
555 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
556 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
557 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
558 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
559 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
560 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
561 private static final String ATTR_VALUE = "value";
562 private static final String TAG_PASSWORD_QUALITY = "password-quality";
563 private static final String TAG_POLICIES = "policies";
564 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
565 "cross-profile-widget-providers";
566 private static final String TAG_PROVIDER = "provider";
567 private static final String TAG_PACKAGE_LIST_ITEM = "item";
568 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
569 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
570 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
571 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
572 private static final String TAG_PARENT_ADMIN = "parent-admin";
573 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
574 private static final String TAG_ORGANIZATION_NAME = "organization-name";
576 final DeviceAdminInfo info;
578 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
580 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
581 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
583 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
584 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
586 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
587 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
589 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
590 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
592 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
593 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
595 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
596 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
598 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
599 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
601 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
602 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
604 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
605 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
607 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
608 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
610 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
611 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
613 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
614 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
616 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
618 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
620 boolean encryptionRequested = false;
621 boolean testOnlyAdmin = false;
622 boolean disableCamera = false;
623 boolean disableCallerId = false;
624 boolean disableContactsSearch = false;
625 boolean disableBluetoothContactSharing = true;
626 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
627 boolean requireAutoTime = false; // Can only be set by a device owner.
628 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
630 ActiveAdmin parentAdmin;
631 final boolean isParent;
633 static class TrustAgentInfo {
634 public PersistableBundle options;
635 TrustAgentInfo(PersistableBundle bundle) {
640 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
642 // The list of permitted accessibility services package namesas set by a profile
643 // or device owner. Null means all accessibility services are allowed, empty means
644 // none except system services are allowed.
645 List<String> permittedAccessiblityServices;
647 // The list of permitted input methods package names as set by a profile or device owner.
648 // Null means all input methods are allowed, empty means none except system imes are
650 List<String> permittedInputMethods;
652 // List of package names to keep cached.
653 List<String> keepUninstalledPackages;
655 // TODO: review implementation decisions with frameworks team
656 boolean specifiesGlobalProxy = false;
657 String globalProxySpec = null;
658 String globalProxyExclusionList = null;
660 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
662 List<String> crossProfileWidgetProviders;
664 Bundle userRestrictions;
666 // Support text provided by the admin to display to the user.
667 CharSequence shortSupportMessage = null;
668 CharSequence longSupportMessage = null;
670 // Background color of confirm credentials screen. Default: teal.
671 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
672 int organizationColor = DEF_ORGANIZATION_COLOR;
674 // Default title of confirm credentials screen
675 String organizationName = null;
677 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
682 ActiveAdmin getParentActiveAdmin() {
683 Preconditions.checkState(!isParent);
685 if (parentAdmin == null) {
686 parentAdmin = new ActiveAdmin(info, /* parent */ true);
691 boolean hasParentActiveAdmin() {
692 return parentAdmin != null;
695 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
697 public UserHandle getUserHandle() {
698 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
701 void writeToXml(XmlSerializer out)
702 throws IllegalArgumentException, IllegalStateException, IOException {
703 out.startTag(null, TAG_POLICIES);
704 info.writePoliciesToXml(out);
705 out.endTag(null, TAG_POLICIES);
706 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
707 out.startTag(null, TAG_PASSWORD_QUALITY);
708 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
709 out.endTag(null, TAG_PASSWORD_QUALITY);
710 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
711 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
712 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
713 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
715 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
716 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
717 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
718 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
720 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
721 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
722 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
723 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
725 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
726 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
727 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
728 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
730 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
731 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
732 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
733 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
735 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
736 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
737 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
738 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
740 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
741 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
742 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
743 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
745 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
746 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
747 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
748 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
751 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
752 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
753 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
754 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
756 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
757 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
758 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
759 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
761 if (specifiesGlobalProxy) {
762 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
763 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
764 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
765 if (globalProxySpec != null) {
766 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
767 out.attribute(null, ATTR_VALUE, globalProxySpec);
768 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
770 if (globalProxyExclusionList != null) {
771 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
772 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
773 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
776 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
777 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
778 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
779 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
781 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
782 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
783 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
784 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
786 if (encryptionRequested) {
787 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
788 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
789 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
792 out.startTag(null, TAG_TEST_ONLY_ADMIN);
793 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
794 out.endTag(null, TAG_TEST_ONLY_ADMIN);
797 out.startTag(null, TAG_DISABLE_CAMERA);
798 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
799 out.endTag(null, TAG_DISABLE_CAMERA);
801 if (disableCallerId) {
802 out.startTag(null, TAG_DISABLE_CALLER_ID);
803 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
804 out.endTag(null, TAG_DISABLE_CALLER_ID);
806 if (disableContactsSearch) {
807 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
808 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
809 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
811 if (!disableBluetoothContactSharing) {
812 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
813 out.attribute(null, ATTR_VALUE,
814 Boolean.toString(disableBluetoothContactSharing));
815 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
817 if (disableScreenCapture) {
818 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
819 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
820 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
822 if (requireAutoTime) {
823 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
824 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
825 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
827 if (forceEphemeralUsers) {
828 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
829 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
830 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
832 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
833 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
834 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
835 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
837 if (!accountTypesWithManagementDisabled.isEmpty()) {
838 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
839 for (String ac : accountTypesWithManagementDisabled) {
840 out.startTag(null, TAG_ACCOUNT_TYPE);
841 out.attribute(null, ATTR_VALUE, ac);
842 out.endTag(null, TAG_ACCOUNT_TYPE);
844 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
846 if (!trustAgentInfos.isEmpty()) {
847 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
848 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
849 for (Entry<String, TrustAgentInfo> entry : set) {
850 TrustAgentInfo trustAgentInfo = entry.getValue();
851 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
852 out.attribute(null, ATTR_VALUE, entry.getKey());
853 if (trustAgentInfo.options != null) {
854 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
856 trustAgentInfo.options.saveToXml(out);
857 } catch (XmlPullParserException e) {
858 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
860 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
862 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
864 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
866 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
867 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
868 final int providerCount = crossProfileWidgetProviders.size();
869 for (int i = 0; i < providerCount; i++) {
870 String provider = crossProfileWidgetProviders.get(i);
871 out.startTag(null, TAG_PROVIDER);
872 out.attribute(null, ATTR_VALUE, provider);
873 out.endTag(null, TAG_PROVIDER);
875 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
877 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
878 permittedAccessiblityServices);
879 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
880 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
881 if (hasUserRestrictions()) {
882 UserRestrictionsUtils.writeRestrictions(
883 out, userRestrictions, TAG_USER_RESTRICTIONS);
885 if (!TextUtils.isEmpty(shortSupportMessage)) {
886 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
887 out.text(shortSupportMessage.toString());
888 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
890 if (!TextUtils.isEmpty(longSupportMessage)) {
891 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
892 out.text(longSupportMessage.toString());
893 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
895 if (parentAdmin != null) {
896 out.startTag(null, TAG_PARENT_ADMIN);
897 parentAdmin.writeToXml(out);
898 out.endTag(null, TAG_PARENT_ADMIN);
900 if (organizationColor != DEF_ORGANIZATION_COLOR) {
901 out.startTag(null, TAG_ORGANIZATION_COLOR);
902 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
903 out.endTag(null, TAG_ORGANIZATION_COLOR);
905 if (organizationName != null) {
906 out.startTag(null, TAG_ORGANIZATION_NAME);
907 out.text(organizationName);
908 out.endTag(null, TAG_ORGANIZATION_NAME);
912 void writePackageListToXml(XmlSerializer out, String outerTag,
913 List<String> packageList)
914 throws IllegalArgumentException, IllegalStateException, IOException {
915 if (packageList == null) {
919 out.startTag(null, outerTag);
920 for (String packageName : packageList) {
921 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
922 out.attribute(null, ATTR_VALUE, packageName);
923 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
925 out.endTag(null, outerTag);
928 void readFromXml(XmlPullParser parser)
929 throws XmlPullParserException, IOException {
930 int outerDepth = parser.getDepth();
932 while ((type=parser.next()) != END_DOCUMENT
933 && (type != END_TAG || parser.getDepth() > outerDepth)) {
934 if (type == END_TAG || type == TEXT) {
937 String tag = parser.getName();
938 if (TAG_POLICIES.equals(tag)) {
939 info.readPoliciesFromXml(parser);
940 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
941 passwordQuality = Integer.parseInt(
942 parser.getAttributeValue(null, ATTR_VALUE));
943 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
944 minimumPasswordLength = Integer.parseInt(
945 parser.getAttributeValue(null, ATTR_VALUE));
946 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
947 passwordHistoryLength = Integer.parseInt(
948 parser.getAttributeValue(null, ATTR_VALUE));
949 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
950 minimumPasswordUpperCase = Integer.parseInt(
951 parser.getAttributeValue(null, ATTR_VALUE));
952 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
953 minimumPasswordLowerCase = Integer.parseInt(
954 parser.getAttributeValue(null, ATTR_VALUE));
955 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
956 minimumPasswordLetters = Integer.parseInt(
957 parser.getAttributeValue(null, ATTR_VALUE));
958 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
959 minimumPasswordNumeric = Integer.parseInt(
960 parser.getAttributeValue(null, ATTR_VALUE));
961 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
962 minimumPasswordSymbols = Integer.parseInt(
963 parser.getAttributeValue(null, ATTR_VALUE));
964 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
965 minimumPasswordNonLetter = Integer.parseInt(
966 parser.getAttributeValue(null, ATTR_VALUE));
967 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
968 maximumTimeToUnlock = Long.parseLong(
969 parser.getAttributeValue(null, ATTR_VALUE));
970 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
971 maximumFailedPasswordsForWipe = Integer.parseInt(
972 parser.getAttributeValue(null, ATTR_VALUE));
973 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
974 specifiesGlobalProxy = Boolean.parseBoolean(
975 parser.getAttributeValue(null, ATTR_VALUE));
976 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
978 parser.getAttributeValue(null, ATTR_VALUE);
979 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
980 globalProxyExclusionList =
981 parser.getAttributeValue(null, ATTR_VALUE);
982 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
983 passwordExpirationTimeout = Long.parseLong(
984 parser.getAttributeValue(null, ATTR_VALUE));
985 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
986 passwordExpirationDate = Long.parseLong(
987 parser.getAttributeValue(null, ATTR_VALUE));
988 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
989 encryptionRequested = Boolean.parseBoolean(
990 parser.getAttributeValue(null, ATTR_VALUE));
991 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
992 testOnlyAdmin = Boolean.parseBoolean(
993 parser.getAttributeValue(null, ATTR_VALUE));
994 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
995 disableCamera = Boolean.parseBoolean(
996 parser.getAttributeValue(null, ATTR_VALUE));
997 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
998 disableCallerId = Boolean.parseBoolean(
999 parser.getAttributeValue(null, ATTR_VALUE));
1000 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1001 disableContactsSearch = Boolean.parseBoolean(
1002 parser.getAttributeValue(null, ATTR_VALUE));
1003 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1004 disableBluetoothContactSharing = Boolean.parseBoolean(parser
1005 .getAttributeValue(null, ATTR_VALUE));
1006 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1007 disableScreenCapture = Boolean.parseBoolean(
1008 parser.getAttributeValue(null, ATTR_VALUE));
1009 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1010 requireAutoTime = Boolean.parseBoolean(
1011 parser.getAttributeValue(null, ATTR_VALUE));
1012 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1013 forceEphemeralUsers = Boolean.parseBoolean(
1014 parser.getAttributeValue(null, ATTR_VALUE));
1015 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1016 disabledKeyguardFeatures = Integer.parseInt(
1017 parser.getAttributeValue(null, ATTR_VALUE));
1018 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1019 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
1020 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1021 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1022 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1023 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
1024 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1025 permittedAccessiblityServices = readPackageList(parser, tag);
1026 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1027 permittedInputMethods = readPackageList(parser, tag);
1028 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1029 keepUninstalledPackages = readPackageList(parser, tag);
1030 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1031 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
1032 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1033 type = parser.next();
1034 if (type == XmlPullParser.TEXT) {
1035 shortSupportMessage = parser.getText();
1037 Log.w(LOG_TAG, "Missing text when loading short support message");
1039 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1040 type = parser.next();
1041 if (type == XmlPullParser.TEXT) {
1042 longSupportMessage = parser.getText();
1044 Log.w(LOG_TAG, "Missing text when loading long support message");
1046 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1047 Preconditions.checkState(!isParent);
1049 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1050 parentAdmin.readFromXml(parser);
1051 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1052 organizationColor = Integer.parseInt(
1053 parser.getAttributeValue(null, ATTR_VALUE));
1054 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1055 type = parser.next();
1056 if (type == XmlPullParser.TEXT) {
1057 organizationName = parser.getText();
1059 Log.w(LOG_TAG, "Missing text when loading organization name");
1062 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1063 XmlUtils.skipCurrentTag(parser);
1068 private List<String> readPackageList(XmlPullParser parser,
1069 String tag) throws XmlPullParserException, IOException {
1070 List<String> result = new ArrayList<String>();
1071 int outerDepth = parser.getDepth();
1073 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1074 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1075 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1078 String outerTag = parser.getName();
1079 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1080 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1081 if (packageName != null) {
1082 result.add(packageName);
1084 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1087 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1093 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1094 throws XmlPullParserException, IOException {
1095 int outerDepthDAM = parser.getDepth();
1097 Set<String> result = new ArraySet<>();
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_ACCOUNT_TYPE.equals(tagDAM)) {
1105 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1107 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1113 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1114 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1115 int outerDepthDAM = parser.getDepth();
1117 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1118 while ((typeDAM=parser.next()) != END_DOCUMENT
1119 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1120 if (typeDAM == END_TAG || typeDAM == TEXT) {
1123 String tagDAM = parser.getName();
1124 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1125 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1126 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1127 result.put(component, trustAgentInfo);
1129 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1135 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1136 throws XmlPullParserException, IOException {
1137 int outerDepthDAM = parser.getDepth();
1139 TrustAgentInfo result = new TrustAgentInfo(null);
1140 while ((typeDAM=parser.next()) != END_DOCUMENT
1141 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1142 if (typeDAM == END_TAG || typeDAM == TEXT) {
1145 String tagDAM = parser.getName();
1146 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1147 result.options = PersistableBundle.restoreFromXml(parser);
1149 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1155 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1156 throws XmlPullParserException, IOException {
1157 int outerDepthDAM = parser.getDepth();
1159 ArrayList<String> result = null;
1160 while ((typeDAM=parser.next()) != END_DOCUMENT
1161 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1162 if (typeDAM == END_TAG || typeDAM == TEXT) {
1165 String tagDAM = parser.getName();
1166 if (TAG_PROVIDER.equals(tagDAM)) {
1167 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1168 if (result == null) {
1169 result = new ArrayList<>();
1171 result.add(provider);
1173 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1179 boolean hasUserRestrictions() {
1180 return userRestrictions != null && userRestrictions.size() > 0;
1183 Bundle ensureUserRestrictions() {
1184 if (userRestrictions == null) {
1185 userRestrictions = new Bundle();
1187 return userRestrictions;
1190 void dump(String prefix, PrintWriter pw) {
1191 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1192 pw.print(prefix); pw.print("testOnlyAdmin=");
1193 pw.println(testOnlyAdmin);
1194 pw.print(prefix); pw.println("policies:");
1195 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1197 for (int i=0; i<pols.size(); i++) {
1198 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1201 pw.print(prefix); pw.print("passwordQuality=0x");
1202 pw.println(Integer.toHexString(passwordQuality));
1203 pw.print(prefix); pw.print("minimumPasswordLength=");
1204 pw.println(minimumPasswordLength);
1205 pw.print(prefix); pw.print("passwordHistoryLength=");
1206 pw.println(passwordHistoryLength);
1207 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1208 pw.println(minimumPasswordUpperCase);
1209 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1210 pw.println(minimumPasswordLowerCase);
1211 pw.print(prefix); pw.print("minimumPasswordLetters=");
1212 pw.println(minimumPasswordLetters);
1213 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1214 pw.println(minimumPasswordNumeric);
1215 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1216 pw.println(minimumPasswordSymbols);
1217 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1218 pw.println(minimumPasswordNonLetter);
1219 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1220 pw.println(maximumTimeToUnlock);
1221 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1222 pw.println(maximumFailedPasswordsForWipe);
1223 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1224 pw.println(specifiesGlobalProxy);
1225 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1226 pw.println(passwordExpirationTimeout);
1227 pw.print(prefix); pw.print("passwordExpirationDate=");
1228 pw.println(passwordExpirationDate);
1229 if (globalProxySpec != null) {
1230 pw.print(prefix); pw.print("globalProxySpec=");
1231 pw.println(globalProxySpec);
1233 if (globalProxyExclusionList != null) {
1234 pw.print(prefix); pw.print("globalProxyEclusionList=");
1235 pw.println(globalProxyExclusionList);
1237 pw.print(prefix); pw.print("encryptionRequested=");
1238 pw.println(encryptionRequested);
1239 pw.print(prefix); pw.print("disableCamera=");
1240 pw.println(disableCamera);
1241 pw.print(prefix); pw.print("disableCallerId=");
1242 pw.println(disableCallerId);
1243 pw.print(prefix); pw.print("disableContactsSearch=");
1244 pw.println(disableContactsSearch);
1245 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1246 pw.println(disableBluetoothContactSharing);
1247 pw.print(prefix); pw.print("disableScreenCapture=");
1248 pw.println(disableScreenCapture);
1249 pw.print(prefix); pw.print("requireAutoTime=");
1250 pw.println(requireAutoTime);
1251 pw.print(prefix); pw.print("forceEphemeralUsers=");
1252 pw.println(forceEphemeralUsers);
1253 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1254 pw.println(disabledKeyguardFeatures);
1255 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1256 pw.println(crossProfileWidgetProviders);
1257 if (permittedAccessiblityServices != null) {
1258 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1259 pw.println(permittedAccessiblityServices);
1261 if (permittedInputMethods != null) {
1262 pw.print(prefix); pw.print("permittedInputMethods=");
1263 pw.println(permittedInputMethods);
1265 if (keepUninstalledPackages != null) {
1266 pw.print(prefix); pw.print("keepUninstalledPackages=");
1267 pw.println(keepUninstalledPackages);
1269 pw.print(prefix); pw.print("organizationColor=");
1270 pw.println(organizationColor);
1271 if (organizationName != null) {
1272 pw.print(prefix); pw.print("organizationName=");
1273 pw.println(organizationName);
1275 pw.print(prefix); pw.println("userRestrictions:");
1276 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1277 pw.print(prefix); pw.print("isParent=");
1278 pw.println(isParent);
1279 if (parentAdmin != null) {
1280 pw.print(prefix); pw.println("parentAdmin:");
1281 parentAdmin.dump(prefix + " ", pw);
1286 private void handlePackagesChanged(String packageName, int userHandle) {
1287 boolean removed = false;
1288 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1289 DevicePolicyData policy = getUserData(userHandle);
1290 synchronized (this) {
1291 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1292 ActiveAdmin aa = policy.mAdminList.get(i);
1294 // If we're checking all packages or if the specific one we're checking matches,
1295 // then check if the package and receiver still exist.
1296 final String adminPackage = aa.info.getPackageName();
1297 if (packageName == null || packageName.equals(adminPackage)) {
1298 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1299 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1300 PackageManager.MATCH_DIRECT_BOOT_AWARE
1301 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1302 userHandle) == null) {
1304 policy.mAdminList.remove(i);
1305 policy.mAdminMap.remove(aa.info.getComponent());
1308 } catch (RemoteException re) {
1313 validatePasswordOwnerLocked(policy);
1314 saveSettingsLocked(policy.mUserHandle);
1317 // Check if delegated cert installer or app restrictions managing packages are removed.
1318 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1319 policy.mDelegatedCertInstallerPackage = null;
1320 saveSettingsLocked(policy.mUserHandle);
1322 if (isRemovedPackage(
1323 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1324 policy.mApplicationRestrictionsManagingPackage = null;
1325 saveSettingsLocked(policy.mUserHandle);
1329 // The removed admin might have disabled camera, so update user restrictions.
1330 pushUserRestrictions(userHandle);
1334 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1336 return targetPackage != null
1337 && (changedPackage == null || changedPackage.equals(targetPackage))
1338 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1339 } catch (RemoteException e) {
1347 * Unit test will subclass it to inject mocks.
1350 static class Injector {
1352 private final Context mContext;
1354 Injector(Context context) {
1358 Owners newOwners() {
1359 return new Owners(getUserManager(), getUserManagerInternal(),
1360 getPackageManagerInternal());
1363 UserManager getUserManager() {
1364 return UserManager.get(mContext);
1367 UserManagerInternal getUserManagerInternal() {
1368 return LocalServices.getService(UserManagerInternal.class);
1371 PackageManagerInternal getPackageManagerInternal() {
1372 return LocalServices.getService(PackageManagerInternal.class);
1375 NotificationManager getNotificationManager() {
1376 return mContext.getSystemService(NotificationManager.class);
1379 PowerManagerInternal getPowerManagerInternal() {
1380 return LocalServices.getService(PowerManagerInternal.class);
1383 TelephonyManager getTelephonyManager() {
1384 return TelephonyManager.from(mContext);
1387 TrustManager getTrustManager() {
1388 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1391 IWindowManager getIWindowManager() {
1392 return IWindowManager.Stub
1393 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1396 IActivityManager getIActivityManager() {
1397 return ActivityManagerNative.getDefault();
1400 IPackageManager getIPackageManager() {
1401 return AppGlobals.getPackageManager();
1404 IBackupManager getIBackupManager() {
1405 return IBackupManager.Stub.asInterface(
1406 ServiceManager.getService(Context.BACKUP_SERVICE));
1409 IAudioService getIAudioService() {
1410 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1413 LockPatternUtils newLockPatternUtils() {
1414 return new LockPatternUtils(mContext);
1417 boolean storageManagerIsFileBasedEncryptionEnabled() {
1418 return StorageManager.isFileEncryptedNativeOnly();
1421 boolean storageManagerIsNonDefaultBlockEncrypted() {
1422 long identity = Binder.clearCallingIdentity();
1424 return StorageManager.isNonDefaultBlockEncrypted();
1426 Binder.restoreCallingIdentity(identity);
1430 boolean storageManagerIsEncrypted() {
1431 return StorageManager.isEncrypted();
1434 boolean storageManagerIsEncryptable() {
1435 return StorageManager.isEncryptable();
1438 Looper getMyLooper() {
1439 return Looper.myLooper();
1442 WifiManager getWifiManager() {
1443 return mContext.getSystemService(WifiManager.class);
1446 long binderClearCallingIdentity() {
1447 return Binder.clearCallingIdentity();
1450 void binderRestoreCallingIdentity(long token) {
1451 Binder.restoreCallingIdentity(token);
1454 int binderGetCallingUid() {
1455 return Binder.getCallingUid();
1458 int binderGetCallingPid() {
1459 return Binder.getCallingPid();
1462 UserHandle binderGetCallingUserHandle() {
1463 return Binder.getCallingUserHandle();
1466 boolean binderIsCallingUidMyUid() {
1467 return getCallingUid() == Process.myUid();
1470 final int userHandleGetCallingUserId() {
1471 return UserHandle.getUserId(binderGetCallingUid());
1474 File environmentGetUserSystemDirectory(int userId) {
1475 return Environment.getUserSystemDirectory(userId);
1478 void powerManagerGoToSleep(long time, int reason, int flags) {
1479 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1482 void powerManagerReboot(String reason) {
1483 mContext.getSystemService(PowerManager.class).reboot(reason);
1486 boolean systemPropertiesGetBoolean(String key, boolean def) {
1487 return SystemProperties.getBoolean(key, def);
1490 long systemPropertiesGetLong(String key, long def) {
1491 return SystemProperties.getLong(key, def);
1494 String systemPropertiesGet(String key, String def) {
1495 return SystemProperties.get(key, def);
1498 String systemPropertiesGet(String key) {
1499 return SystemProperties.get(key);
1502 void systemPropertiesSet(String key, String value) {
1503 SystemProperties.set(key, value);
1506 boolean userManagerIsSplitSystemUser() {
1507 return UserManager.isSplitSystemUser();
1510 String getDevicePolicyFilePathForSystemUser() {
1511 return "/data/system/";
1514 void registerContentObserver(Uri uri, boolean notifyForDescendents,
1515 ContentObserver observer, int userHandle) {
1516 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1517 observer, userHandle);
1520 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1521 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1522 name, def, userHandle);
1525 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1526 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1527 name, value, userHandle);
1530 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1531 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1532 name, value, userHandle);
1535 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1536 Settings.Global.putStringForUser(mContext.getContentResolver(),
1537 name, value, userHandle);
1540 void settingsSecurePutInt(String name, int value) {
1541 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1544 int settingsGlobalGetInt(String name, int def) {
1545 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1548 void settingsGlobalPutInt(String name, int value) {
1549 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1552 void settingsSecurePutString(String name, String value) {
1553 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1556 void settingsGlobalPutString(String name, String value) {
1557 Settings.Global.putString(mContext.getContentResolver(), name, value);
1560 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1561 SecurityLog.setLoggingEnabledProperty(enabled);
1564 boolean securityLogGetLoggingEnabledProperty() {
1565 return SecurityLog.getLoggingEnabledProperty();
1568 boolean securityLogIsLoggingEnabled() {
1569 return SecurityLog.isLoggingEnabled();
1574 * Instantiates the service.
1576 public DevicePolicyManagerService(Context context) {
1577 this(new Injector(context));
1581 DevicePolicyManagerService(Injector injector) {
1582 mInjector = injector;
1583 mContext = Preconditions.checkNotNull(injector.mContext);
1584 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1585 mOwners = Preconditions.checkNotNull(injector.newOwners());
1587 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1588 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1589 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1590 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1592 mLocalService = new LocalService();
1593 mLockPatternUtils = injector.newLockPatternUtils();
1595 mSecurityLogMonitor = new SecurityLogMonitor(this);
1597 mHasFeature = mContext.getPackageManager()
1598 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1600 // Skip the rest of the initialization
1603 IntentFilter filter = new IntentFilter();
1604 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1605 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1606 filter.addAction(Intent.ACTION_USER_ADDED);
1607 filter.addAction(Intent.ACTION_USER_REMOVED);
1608 filter.addAction(Intent.ACTION_USER_STARTED);
1609 filter.addAction(Intent.ACTION_USER_UNLOCKED);
1610 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1611 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1612 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1613 filter = new IntentFilter();
1614 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1615 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1616 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1617 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1618 filter.addDataScheme("package");
1619 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1620 filter = new IntentFilter();
1621 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1622 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1624 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1628 * Creates and loads the policy data from xml.
1629 * @param userHandle the user for whom to load the policy data
1633 DevicePolicyData getUserData(int userHandle) {
1634 synchronized (this) {
1635 DevicePolicyData policy = mUserData.get(userHandle);
1636 if (policy == null) {
1637 policy = new DevicePolicyData(userHandle);
1638 mUserData.append(userHandle, policy);
1639 loadSettingsLocked(policy, userHandle);
1646 * Creates and loads the policy data from xml for data that is shared between
1647 * various profiles of a user. In contrast to {@link #getUserData(int)}
1648 * it allows access to data of users other than the calling user.
1650 * This function should only be used for shared data, e.g. everything regarding
1651 * passwords and should be removed once multiple screen locks are present.
1652 * @param userHandle the user for whom to load the policy data
1655 DevicePolicyData getUserDataUnchecked(int userHandle) {
1656 long ident = mInjector.binderClearCallingIdentity();
1658 return getUserData(userHandle);
1660 mInjector.binderRestoreCallingIdentity(ident);
1664 void removeUserData(int userHandle) {
1665 synchronized (this) {
1666 if (userHandle == UserHandle.USER_SYSTEM) {
1667 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1670 mOwners.removeProfileOwner(userHandle);
1671 mOwners.writeProfileOwner(userHandle);
1673 DevicePolicyData policy = mUserData.get(userHandle);
1674 if (policy != null) {
1675 mUserData.remove(userHandle);
1677 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1678 DEVICE_POLICIES_XML);
1679 policyFile.delete();
1680 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1682 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1686 synchronized (this) {
1688 setDeviceOwnerSystemPropertyLocked();
1689 findOwnerComponentIfNecessaryLocked();
1690 migrateUserRestrictionsIfNecessaryLocked();
1692 // TODO PO may not have a class name either due to b/17652534. Address that too.
1694 updateDeviceOwnerLocked();
1698 private void setDeviceOwnerSystemPropertyLocked() {
1699 // Device owner may still be provisioned, do not set the read-only system property yet.
1700 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1703 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1704 // always false at this point.
1705 if (StorageManager.inCryptKeeperBounce()) {
1709 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1710 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1712 if (mOwners.hasDeviceOwner()) {
1713 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1714 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1715 disableSecurityLoggingIfNotCompliant();
1716 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1717 mSecurityLogMonitor.start();
1720 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1721 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1726 private void findOwnerComponentIfNecessaryLocked() {
1727 if (!mOwners.hasDeviceOwner()) {
1730 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1732 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1733 return; // Already a full component name.
1736 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1737 doComponentName.getPackageName(),
1738 mOwners.getDeviceOwnerUserId());
1739 if (doComponent == null) {
1740 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1742 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1744 mOwners.getDeviceOwnerName(),
1745 mOwners.getDeviceOwnerUserId(),
1746 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1747 mOwners.writeDeviceOwner();
1749 Log.v(LOG_TAG, "Device owner component filled in");
1755 * We didn't use to persist user restrictions for each owners but only persisted in user
1758 private void migrateUserRestrictionsIfNecessaryLocked() {
1759 boolean migrated = false;
1760 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1761 // except for the "system controlled" ones.
1762 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1764 Log.v(LOG_TAG, "Migrating DO user restrictions");
1768 // Migrate user 0 restrictions to DO.
1769 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1771 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1772 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1774 // Push DO user restrictions to user manager.
1775 pushUserRestrictions(UserHandle.USER_SYSTEM);
1777 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1782 // The following restrictions can be set on secondary users by the device owner, so we
1783 // assume they're not from the PO.
1784 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1785 UserManager.DISALLOW_OUTGOING_CALLS,
1786 UserManager.DISALLOW_SMS);
1788 for (UserInfo ui : mUserManager.getUsers()) {
1789 final int userId = ui.id;
1790 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1792 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1796 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1798 final Set<String> exceptionList =
1799 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1801 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1802 exceptionList, /* isDeviceOwner =*/ false);
1804 // Note if a secondary user has no PO but has a DA that disables camera, we
1805 // don't get here and won't push the camera user restriction to UserManager
1806 // here. That's okay because we'll push user restrictions anyway when a user
1807 // starts. But we still do it because we want to let user manager persist
1809 pushUserRestrictions(userId);
1811 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1814 if (VERBOSE_LOG && migrated) {
1815 Log.v(LOG_TAG, "User restrictions migrated.");
1819 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1820 Set<String> exceptionList, boolean isDeviceOwner) {
1821 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1822 user.getIdentifier());
1824 final Bundle newBaseRestrictions = new Bundle();
1825 final Bundle newOwnerRestrictions = new Bundle();
1827 for (String key : origRestrictions.keySet()) {
1828 if (!origRestrictions.getBoolean(key)) {
1831 final boolean canOwnerChange = isDeviceOwner
1832 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1833 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1835 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1836 newBaseRestrictions.putBoolean(key, true);
1838 newOwnerRestrictions.putBoolean(key, true);
1843 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1844 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1845 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1847 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1848 newBaseRestrictions);
1850 if (admin != null) {
1851 admin.ensureUserRestrictions().clear();
1852 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1854 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1856 saveSettingsLocked(user.getIdentifier());
1859 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1860 final DevicePolicyData policy = getUserData(userId);
1861 final int n = policy.mAdminList.size();
1862 ComponentName found = null;
1864 for (int i = 0; i < n; i++) {
1865 final ActiveAdmin admin = policy.mAdminList.get(i);
1866 if (packageName.equals(admin.info.getPackageName())) {
1869 found = admin.info.getComponent();
1875 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1881 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1882 * reminders. Clears alarm if no expirations are configured.
1884 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1885 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1886 final long now = System.currentTimeMillis();
1887 final long timeToExpire = expiration - now;
1888 final long alarmTime;
1889 if (expiration == 0) {
1890 // No expirations are currently configured: Cancel alarm.
1892 } else if (timeToExpire <= 0) {
1893 // The password has already expired: Repeat every 24 hours.
1894 alarmTime = now + MS_PER_DAY;
1896 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1897 // the expiration time.
1898 long alarmInterval = timeToExpire % MS_PER_DAY;
1899 if (alarmInterval == 0) {
1900 alarmInterval = MS_PER_DAY;
1902 alarmTime = now + alarmInterval;
1905 long token = mInjector.binderClearCallingIdentity();
1907 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1908 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1909 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1910 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1911 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1912 UserHandle.of(affectedUserHandle));
1914 if (alarmTime != 0) {
1915 am.set(AlarmManager.RTC, alarmTime, pi);
1918 mInjector.binderRestoreCallingIdentity(token);
1922 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1923 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1925 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1926 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1932 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
1934 enforceManagedProfile(userHandle, "call APIs on the parent profile");
1936 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1937 if (admin != null && parent) {
1938 admin = admin.getParentActiveAdmin();
1943 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1944 throws SecurityException {
1945 final int callingUid = mInjector.binderGetCallingUid();
1947 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1948 if (result != null) {
1953 final int userId = UserHandle.getUserId(callingUid);
1954 final DevicePolicyData policy = getUserData(userId);
1955 ActiveAdmin admin = policy.mAdminMap.get(who);
1956 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1957 throw new SecurityException("Admin " + admin.info.getComponent()
1958 + " does not own the device");
1960 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1961 throw new SecurityException("Admin " + admin.info.getComponent()
1962 + " does not own the profile");
1964 throw new SecurityException("Admin " + admin.info.getComponent()
1965 + " did not specify uses-policy for: "
1966 + admin.info.getTagForPolicy(reqPolicy));
1968 throw new SecurityException("No active admin owned by uid "
1969 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
1973 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
1974 throws SecurityException {
1976 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
1977 "call APIs on the parent profile");
1979 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
1980 return parent ? admin.getParentActiveAdmin() : admin;
1983 * Find the admin for the component and userId bit of the uid, then check
1984 * the admin's uid matches the uid.
1986 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
1987 final int userId = UserHandle.getUserId(uid);
1988 final DevicePolicyData policy = getUserData(userId);
1989 ActiveAdmin admin = policy.mAdminMap.get(who);
1990 if (admin == null) {
1991 throw new SecurityException("No active admin " + who);
1993 if (admin.getUid() != uid) {
1994 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1999 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2001 // Try to find an admin which can use reqPolicy
2002 final int userId = UserHandle.getUserId(uid);
2003 final DevicePolicyData policy = getUserData(userId);
2005 ActiveAdmin admin = policy.mAdminMap.get(who);
2006 if (admin == null) {
2007 throw new SecurityException("No active admin " + who);
2009 if (admin.getUid() != uid) {
2010 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2012 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2016 for (ActiveAdmin admin : policy.mAdminList) {
2017 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2028 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2030 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2031 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2033 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2035 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2036 // DO always has the PO power.
2037 return ownsDevice || ownsProfile;
2039 return admin.info.usesPolicy(reqPolicy);
2043 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2044 sendAdminCommandLocked(admin, action, null);
2047 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2048 sendAdminCommandLocked(admin, action, null, result);
2052 * Send an update to one specific admin, get notified when that admin returns a result.
2054 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2055 BroadcastReceiver result) {
2056 Intent intent = new Intent(action);
2057 intent.setComponent(admin.info.getComponent());
2058 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2059 intent.putExtra("expiration", admin.passwordExpirationDate);
2061 if (adminExtras != null) {
2062 intent.putExtras(adminExtras);
2064 if (result != null) {
2065 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2066 null, result, mHandler, Activity.RESULT_OK, null, null);
2068 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2073 * Send an update to all admins of a user that enforce a specified policy.
2075 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2076 final DevicePolicyData policy = getUserData(userHandle);
2077 final int count = policy.mAdminList.size();
2079 for (int i = 0; i < count; i++) {
2080 final ActiveAdmin admin = policy.mAdminList.get(i);
2081 if (admin.info.usesPolicy(reqPolicy)) {
2082 sendAdminCommandLocked(admin, action);
2089 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2090 * enforce a specified policy.
2092 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2094 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2095 for (int profileId : profileIds) {
2096 sendAdminCommandLocked(action, reqPolicy, profileId);
2101 * Sends a broadcast to each profile that share the password unlock with the given user id.
2103 private void sendAdminCommandForLockscreenPoliciesLocked(
2104 String action, int reqPolicy, int userHandle) {
2105 if (isSeparateProfileChallengeEnabled(userHandle)) {
2106 sendAdminCommandLocked(action, reqPolicy, userHandle);
2108 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2112 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2113 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2114 DevicePolicyData policy = getUserData(userHandle);
2115 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2116 policy.mRemovingAdmins.add(adminReceiver);
2117 sendAdminCommandLocked(admin,
2118 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2119 new BroadcastReceiver() {
2121 public void onReceive(Context context, Intent intent) {
2122 removeAdminArtifacts(adminReceiver, userHandle);
2123 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2130 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2131 boolean throwForMissiongPermission) {
2135 enforceFullCrossUsersPermission(userHandle);
2136 ActivityInfo ai = null;
2138 ai = mIPackageManager.getReceiverInfo(adminName,
2139 PackageManager.GET_META_DATA |
2140 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2141 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2142 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2143 } catch (RemoteException e) {
2144 // shouldn't happen.
2147 throw new IllegalArgumentException("Unknown admin: " + adminName);
2150 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2151 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2152 + permission.BIND_DEVICE_ADMIN;
2153 Slog.w(LOG_TAG, message);
2154 if (throwForMissiongPermission &&
2155 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2156 throw new IllegalArgumentException(message);
2161 return new DeviceAdminInfo(mContext, ai);
2162 } catch (XmlPullParserException | IOException e) {
2163 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2169 private JournaledFile makeJournaledFile(int userHandle) {
2170 final String base = userHandle == UserHandle.USER_SYSTEM
2171 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2172 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2173 DEVICE_POLICIES_XML).getAbsolutePath();
2175 Log.v(LOG_TAG, "Opening " + base);
2177 return new JournaledFile(new File(base), new File(base + ".tmp"));
2180 private void saveSettingsLocked(int userHandle) {
2181 DevicePolicyData policy = getUserData(userHandle);
2182 JournaledFile journal = makeJournaledFile(userHandle);
2183 FileOutputStream stream = null;
2185 stream = new FileOutputStream(journal.chooseForWrite(), false);
2186 XmlSerializer out = new FastXmlSerializer();
2187 out.setOutput(stream, StandardCharsets.UTF_8.name());
2188 out.startDocument(null, true);
2190 out.startTag(null, "policies");
2191 if (policy.mRestrictionsProvider != null) {
2192 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2193 policy.mRestrictionsProvider.flattenToString());
2195 if (policy.mUserSetupComplete) {
2196 out.attribute(null, ATTR_SETUP_COMPLETE,
2197 Boolean.toString(true));
2199 if (policy.mDeviceProvisioningConfigApplied) {
2200 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2201 Boolean.toString(true));
2203 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2204 out.attribute(null, ATTR_PROVISIONING_STATE,
2205 Integer.toString(policy.mUserProvisioningState));
2207 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2208 out.attribute(null, ATTR_PERMISSION_POLICY,
2209 Integer.toString(policy.mPermissionPolicy));
2211 if (policy.mDelegatedCertInstallerPackage != null) {
2212 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2213 policy.mDelegatedCertInstallerPackage);
2215 if (policy.mApplicationRestrictionsManagingPackage != null) {
2216 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2217 policy.mApplicationRestrictionsManagingPackage);
2220 final int N = policy.mAdminList.size();
2221 for (int i=0; i<N; i++) {
2222 ActiveAdmin ap = policy.mAdminList.get(i);
2224 out.startTag(null, "admin");
2225 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2227 out.endTag(null, "admin");
2231 if (policy.mPasswordOwner >= 0) {
2232 out.startTag(null, "password-owner");
2233 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2234 out.endTag(null, "password-owner");
2237 if (policy.mFailedPasswordAttempts != 0) {
2238 out.startTag(null, "failed-password-attempts");
2239 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2240 out.endTag(null, "failed-password-attempts");
2243 if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2244 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2245 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2246 || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
2247 out.startTag(null, "active-password");
2248 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2249 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2250 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2251 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2252 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2253 out.attribute(null, "numeric", Integer
2254 .toString(policy.mActivePasswordNumeric));
2255 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2256 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2257 out.endTag(null, "active-password");
2260 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2261 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2262 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2263 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2266 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2267 String component = policy.mLockTaskPackages.get(i);
2268 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2269 out.attribute(null, "name", component);
2270 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2273 if (policy.mStatusBarDisabled) {
2274 out.startTag(null, TAG_STATUS_BAR);
2275 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2276 out.endTag(null, TAG_STATUS_BAR);
2279 if (policy.doNotAskCredentialsOnBoot) {
2280 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2281 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2284 for (String id : policy.mAffiliationIds) {
2285 out.startTag(null, TAG_AFFILIATION_ID);
2286 out.attribute(null, "id", id);
2287 out.endTag(null, TAG_AFFILIATION_ID);
2290 if (policy.mAdminBroadcastPending) {
2291 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2292 out.attribute(null, ATTR_VALUE,
2293 Boolean.toString(policy.mAdminBroadcastPending));
2294 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2297 if (policy.mInitBundle != null) {
2298 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2299 policy.mInitBundle.saveToXml(out);
2300 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2303 out.endTag(null, "policies");
2307 FileUtils.sync(stream);
2310 sendChangedNotification(userHandle);
2311 } catch (XmlPullParserException | IOException e) {
2312 Slog.w(LOG_TAG, "failed writing file", e);
2314 if (stream != null) {
2317 } catch (IOException ex) {
2324 private void sendChangedNotification(int userHandle) {
2325 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2326 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2327 long ident = mInjector.binderClearCallingIdentity();
2329 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2331 mInjector.binderRestoreCallingIdentity(ident);
2335 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2336 JournaledFile journal = makeJournaledFile(userHandle);
2337 FileInputStream stream = null;
2338 File file = journal.chooseForRead();
2340 stream = new FileInputStream(file);
2341 XmlPullParser parser = Xml.newPullParser();
2342 parser.setInput(stream, StandardCharsets.UTF_8.name());
2345 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2346 && type != XmlPullParser.START_TAG) {
2348 String tag = parser.getName();
2349 if (!"policies".equals(tag)) {
2350 throw new XmlPullParserException(
2351 "Settings do not start with policies tag: found " + tag);
2354 // Extract the permission provider component name if available
2355 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2356 if (permissionProvider != null) {
2357 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2359 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2360 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2361 policy.mUserSetupComplete = true;
2363 String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2364 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2365 if (deviceProvisioningConfigApplied != null
2366 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2367 policy.mDeviceProvisioningConfigApplied = true;
2369 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2370 if (!TextUtils.isEmpty(provisioningState)) {
2371 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2373 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2374 if (!TextUtils.isEmpty(permissionPolicy)) {
2375 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2377 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2378 ATTR_DELEGATED_CERT_INSTALLER);
2379 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2380 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2382 type = parser.next();
2383 int outerDepth = parser.getDepth();
2384 policy.mLockTaskPackages.clear();
2385 policy.mAdminList.clear();
2386 policy.mAdminMap.clear();
2387 policy.mAffiliationIds.clear();
2388 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2389 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2390 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2393 tag = parser.getName();
2394 if ("admin".equals(tag)) {
2395 String name = parser.getAttributeValue(null, "name");
2397 DeviceAdminInfo dai = findAdmin(
2398 ComponentName.unflattenFromString(name), userHandle,
2399 /* throwForMissionPermission= */ false);
2401 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2403 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2404 + dai.getActivityInfo().applicationInfo.uid + " for user "
2408 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2409 ap.readFromXml(parser);
2410 policy.mAdminMap.put(ap.info.getComponent(), ap);
2412 } catch (RuntimeException e) {
2413 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2415 } else if ("failed-password-attempts".equals(tag)) {
2416 policy.mFailedPasswordAttempts = Integer.parseInt(
2417 parser.getAttributeValue(null, "value"));
2418 } else if ("password-owner".equals(tag)) {
2419 policy.mPasswordOwner = Integer.parseInt(
2420 parser.getAttributeValue(null, "value"));
2421 } else if ("active-password".equals(tag)) {
2422 policy.mActivePasswordQuality = Integer.parseInt(
2423 parser.getAttributeValue(null, "quality"));
2424 policy.mActivePasswordLength = Integer.parseInt(
2425 parser.getAttributeValue(null, "length"));
2426 policy.mActivePasswordUpperCase = Integer.parseInt(
2427 parser.getAttributeValue(null, "uppercase"));
2428 policy.mActivePasswordLowerCase = Integer.parseInt(
2429 parser.getAttributeValue(null, "lowercase"));
2430 policy.mActivePasswordLetters = Integer.parseInt(
2431 parser.getAttributeValue(null, "letters"));
2432 policy.mActivePasswordNumeric = Integer.parseInt(
2433 parser.getAttributeValue(null, "numeric"));
2434 policy.mActivePasswordSymbols = Integer.parseInt(
2435 parser.getAttributeValue(null, "symbols"));
2436 policy.mActivePasswordNonLetter = Integer.parseInt(
2437 parser.getAttributeValue(null, "nonletter"));
2438 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2439 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2440 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2441 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2442 } else if (TAG_STATUS_BAR.equals(tag)) {
2443 policy.mStatusBarDisabled = Boolean.parseBoolean(
2444 parser.getAttributeValue(null, ATTR_DISABLED));
2445 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2446 policy.doNotAskCredentialsOnBoot = true;
2447 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2448 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2449 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2450 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2451 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2452 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2453 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2455 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2456 XmlUtils.skipCurrentTag(parser);
2459 } catch (FileNotFoundException e) {
2460 // Don't be noisy, this is normal if we haven't defined any policies.
2461 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2462 | IndexOutOfBoundsException e) {
2463 Slog.w(LOG_TAG, "failed parsing " + file, e);
2466 if (stream != null) {
2469 } catch (IOException e) {
2473 // Generate a list of admins from the admin map
2474 policy.mAdminList.addAll(policy.mAdminMap.values());
2476 // Validate that what we stored for the password quality matches
2477 // sufficiently what is currently set. Note that this is only
2478 // a sanity check in case the two get out of sync; this should
2479 // never normally happen.
2480 final long identity = mInjector.binderClearCallingIdentity();
2482 int actualPasswordQuality = mLockPatternUtils.getActivePasswordQuality(userHandle);
2483 if (actualPasswordQuality < policy.mActivePasswordQuality) {
2484 Slog.w(LOG_TAG, "Active password quality 0x"
2485 + Integer.toHexString(policy.mActivePasswordQuality)
2486 + " does not match actual quality 0x"
2487 + Integer.toHexString(actualPasswordQuality));
2488 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2489 policy.mActivePasswordLength = 0;
2490 policy.mActivePasswordUpperCase = 0;
2491 policy.mActivePasswordLowerCase = 0;
2492 policy.mActivePasswordLetters = 0;
2493 policy.mActivePasswordNumeric = 0;
2494 policy.mActivePasswordSymbols = 0;
2495 policy.mActivePasswordNonLetter = 0;
2498 mInjector.binderRestoreCallingIdentity(identity);
2501 validatePasswordOwnerLocked(policy);
2502 updateMaximumTimeToLockLocked(userHandle);
2503 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2504 if (policy.mStatusBarDisabled) {
2505 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2509 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2510 long ident = mInjector.binderClearCallingIdentity();
2512 mInjector.getIActivityManager()
2513 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2514 } catch (RemoteException e) {
2515 // Not gonna happen.
2517 mInjector.binderRestoreCallingIdentity(ident);
2521 private void updateDeviceOwnerLocked() {
2522 long ident = mInjector.binderClearCallingIdentity();
2524 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2525 // user id and also protect all other DAs too.
2526 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2527 if (deviceOwnerComponent != null) {
2528 mInjector.getIActivityManager()
2529 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2531 } catch (RemoteException e) {
2532 // Not gonna happen.
2534 mInjector.binderRestoreCallingIdentity(ident);
2538 static void validateQualityConstant(int quality) {
2540 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2541 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2542 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2543 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2544 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2545 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2546 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2547 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2548 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2551 throw new IllegalArgumentException("Invalid quality constant: 0x"
2552 + Integer.toHexString(quality));
2555 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2556 if (policy.mPasswordOwner >= 0) {
2557 boolean haveOwner = false;
2558 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2559 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2565 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2566 + " no longer active; disabling");
2567 policy.mPasswordOwner = -1;
2573 void systemReady(int phase) {
2578 case SystemService.PHASE_LOCK_SETTINGS_READY:
2579 onLockSettingsReady();
2581 case SystemService.PHASE_BOOT_COMPLETED:
2582 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2587 private void onLockSettingsReady() {
2588 getUserData(UserHandle.USER_SYSTEM);
2592 onStartUser(UserHandle.USER_SYSTEM);
2594 // Register an observer for watching for user setup complete.
2595 new SetupContentObserver(mHandler).register();
2596 // Initialize the user setup state, to handle the upgrade case.
2597 updateUserSetupComplete();
2599 List<String> packageList;
2600 synchronized (this) {
2601 packageList = getKeepUninstalledPackagesLocked();
2603 if (packageList != null) {
2604 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2607 synchronized (this) {
2608 // push the force-ephemeral-users policy to the user manager.
2609 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2610 if (deviceOwner != null) {
2611 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2616 private void ensureDeviceOwnerUserStarted() {
2618 synchronized (this) {
2619 if (!mOwners.hasDeviceOwner()) {
2622 userId = mOwners.getDeviceOwnerUserId();
2625 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2627 if (userId != UserHandle.USER_SYSTEM) {
2629 mInjector.getIActivityManager().startUserInBackground(userId);
2631 // STOPSHIP Prevent the DO user from being killed.
2633 } catch (RemoteException e) {
2634 Slog.w(LOG_TAG, "Exception starting user", e);
2639 private void onStartUser(int userId) {
2640 updateScreenCaptureDisabledInWindowManager(userId,
2641 getScreenCaptureDisabled(null, userId));
2642 pushUserRestrictions(userId);
2645 private void cleanUpOldUsers() {
2646 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2648 Set<Integer> usersWithProfileOwners;
2649 Set<Integer> usersWithData;
2650 synchronized(this) {
2651 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2652 usersWithData = new ArraySet<>();
2653 for (int i = 0; i < mUserData.size(); i++) {
2654 usersWithData.add(mUserData.keyAt(i));
2657 List<UserInfo> allUsers = mUserManager.getUsers();
2659 Set<Integer> deletedUsers = new ArraySet<>();
2660 deletedUsers.addAll(usersWithProfileOwners);
2661 deletedUsers.addAll(usersWithData);
2662 for (UserInfo userInfo : allUsers) {
2663 deletedUsers.remove(userInfo.id);
2665 for (Integer userId : deletedUsers) {
2666 removeUserData(userId);
2670 private void handlePasswordExpirationNotification(int userHandle) {
2671 synchronized (this) {
2672 final long now = System.currentTimeMillis();
2674 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2675 userHandle, /* parent */ false);
2676 final int N = admins.size();
2677 for (int i = 0; i < N; i++) {
2678 ActiveAdmin admin = admins.get(i);
2679 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2680 && admin.passwordExpirationTimeout > 0L
2681 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2682 && admin.passwordExpirationDate > 0L) {
2683 sendAdminCommandLocked(admin,
2684 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2687 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2691 private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2693 protected Void doInBackground(Integer... params) {
2694 int userHandle = params[0];
2696 if (userHandle == UserHandle.USER_ALL) {
2697 for (UserInfo userInfo : mUserManager.getUsers(true)) {
2698 manageNotification(userInfo.getUserHandle());
2701 manageNotification(UserHandle.of(userHandle));
2706 private void manageNotification(UserHandle userHandle) {
2707 if (!mUserManager.isUserUnlocked(userHandle)) {
2711 // Call out to KeyChain to check for CAs which are waiting for approval.
2712 final List<String> pendingCertificates;
2714 pendingCertificates = getInstalledCaCertificates(userHandle);
2715 } catch (RemoteException | RuntimeException e) {
2716 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2720 synchronized (DevicePolicyManagerService.this) {
2721 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2723 // Remove deleted certificates. Flush xml if necessary.
2724 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2725 saveSettingsLocked(userHandle.getIdentifier());
2727 // Trim to approved certificates.
2728 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2731 if (pendingCertificates.isEmpty()) {
2732 mInjector.getNotificationManager().cancelAsUser(
2733 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2737 // Build and show a warning notification
2740 int parentUserId = userHandle.getIdentifier();
2741 if (getProfileOwner(userHandle.getIdentifier()) != null) {
2742 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2743 getProfileOwnerName(userHandle.getIdentifier()));
2744 smallIconId = R.drawable.stat_sys_certificate_info;
2745 parentUserId = getProfileParentId(userHandle.getIdentifier());
2746 } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
2747 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2748 getDeviceOwnerName());
2749 smallIconId = R.drawable.stat_sys_certificate_info;
2751 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2752 smallIconId = android.R.drawable.stat_sys_warning;
2755 final int numberOfCertificates = pendingCertificates.size();
2756 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2757 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2758 dialogIntent.setPackage("com.android.settings");
2759 dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
2760 dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
2761 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2762 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
2763 new UserHandle(parentUserId));
2765 final Context userContext;
2767 final String packageName = mContext.getPackageName();
2768 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
2769 } catch (PackageManager.NameNotFoundException e) {
2770 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2773 final Notification noti = new Notification.Builder(userContext)
2774 .setSmallIcon(smallIconId)
2775 .setContentTitle(mContext.getResources().getQuantityText(
2776 R.plurals.ssl_ca_cert_warning, numberOfCertificates))
2777 .setContentText(contentText)
2778 .setContentIntent(notifyIntent)
2779 .setPriority(Notification.PRIORITY_HIGH)
2781 .setColor(mContext.getColor(
2782 com.android.internal.R.color.system_notification_accent_color))
2785 mInjector.getNotificationManager().notifyAsUser(
2786 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2789 private List<String> getInstalledCaCertificates(UserHandle userHandle)
2790 throws RemoteException, RuntimeException {
2791 KeyChainConnection conn = null;
2793 conn = KeyChain.bindAsUser(mContext, userHandle);
2794 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
2795 List<String> result = new ArrayList<>(aliases.size());
2796 for (int i = 0; i < aliases.size(); i++) {
2797 result.add(aliases.get(i).string);
2800 } catch (InterruptedException e) {
2801 Thread.currentThread().interrupt();
2803 } catch (AssertionError e) {
2804 throw new RuntimeException(e);
2814 * @param adminReceiver The admin to add
2815 * @param refreshing true = update an active admin, no error
2818 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2822 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2825 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2826 Bundle onEnableData) {
2827 mContext.enforceCallingOrSelfPermission(
2828 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2829 enforceFullCrossUsersPermission(userHandle);
2831 DevicePolicyData policy = getUserData(userHandle);
2832 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2833 /* throwForMissionPermission= */ true);
2835 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2837 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2838 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2841 synchronized (this) {
2842 long ident = mInjector.binderClearCallingIdentity();
2844 final ActiveAdmin existingAdmin
2845 = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2846 if (!refreshing && existingAdmin != null) {
2847 throw new IllegalArgumentException("Admin is already added");
2849 if (policy.mRemovingAdmins.contains(adminReceiver)) {
2850 throw new IllegalArgumentException(
2851 "Trying to set an admin which is being removed");
2853 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2854 newAdmin.testOnlyAdmin =
2855 (existingAdmin != null) ? existingAdmin.testOnlyAdmin
2856 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
2857 policy.mAdminMap.put(adminReceiver, newAdmin);
2858 int replaceIndex = -1;
2859 final int N = policy.mAdminList.size();
2860 for (int i=0; i < N; i++) {
2861 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2862 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2867 if (replaceIndex == -1) {
2868 policy.mAdminList.add(newAdmin);
2869 enableIfNecessary(info.getPackageName(), userHandle);
2871 policy.mAdminList.set(replaceIndex, newAdmin);
2873 saveSettingsLocked(userHandle);
2874 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2875 onEnableData, null);
2877 mInjector.binderRestoreCallingIdentity(ident);
2883 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2887 enforceFullCrossUsersPermission(userHandle);
2888 synchronized (this) {
2889 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2894 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2898 enforceFullCrossUsersPermission(userHandle);
2899 synchronized (this) {
2900 DevicePolicyData policyData = getUserData(userHandle);
2901 return policyData.mRemovingAdmins.contains(adminReceiver);
2906 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2910 enforceFullCrossUsersPermission(userHandle);
2911 synchronized (this) {
2912 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2913 if (administrator == null) {
2914 throw new SecurityException("No active admin " + adminReceiver);
2916 return administrator.info.usesPolicy(policyId);
2921 @SuppressWarnings("unchecked")
2922 public List<ComponentName> getActiveAdmins(int userHandle) {
2924 return Collections.EMPTY_LIST;
2927 enforceFullCrossUsersPermission(userHandle);
2928 synchronized (this) {
2929 DevicePolicyData policy = getUserData(userHandle);
2930 final int N = policy.mAdminList.size();
2934 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2935 for (int i=0; i<N; i++) {
2936 res.add(policy.mAdminList.get(i).info.getComponent());
2943 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2947 enforceFullCrossUsersPermission(userHandle);
2948 synchronized (this) {
2949 DevicePolicyData policy = getUserData(userHandle);
2950 final int N = policy.mAdminList.size();
2951 for (int i=0; i<N; i++) {
2952 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2960 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
2964 Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
2965 enforceShell("forceRemoveActiveAdmin");
2966 long ident = mInjector.binderClearCallingIdentity();
2968 synchronized (this) {
2969 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
2970 throw new SecurityException("Attempt to remove non-test admin "
2971 + adminReceiver + " " + userHandle);
2974 // If admin is a device or profile owner tidy that up first.
2975 if (isDeviceOwner(adminReceiver, userHandle)) {
2976 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
2978 if (isProfileOwner(adminReceiver, userHandle)) {
2979 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
2980 userHandle, /* parent */ false);
2981 clearProfileOwnerLocked(admin, userHandle);
2984 // Remove the admin skipping sending the broadcast.
2985 removeAdminArtifacts(adminReceiver, userHandle);
2986 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
2988 mInjector.binderRestoreCallingIdentity(ident);
2993 * Return if a given package has testOnly="true", in which case we'll relax certain rules
2996 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked}
2997 * to check wehter an active admin is test-only or not.
2999 * The system allows this flag to be changed when an app is updated, which is not good
3000 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3001 * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3003 private boolean isPackageTestOnly(String packageName, int userHandle) {
3004 final ApplicationInfo ai;
3006 ai = mIPackageManager.getApplicationInfo(packageName,
3007 (PackageManager.MATCH_DIRECT_BOOT_AWARE
3008 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3009 } catch (RemoteException e) {
3010 throw new IllegalStateException(e);
3013 throw new IllegalStateException("Couldn't find package to remove admin "
3014 + packageName + " " + userHandle);
3016 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3020 * See {@link #isPackageTestOnly}.
3022 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3023 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3024 return (admin != null) && admin.testOnlyAdmin;
3027 private void enforceShell(String method) {
3028 final int callingUid = Binder.getCallingUid();
3029 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3030 throw new SecurityException("Non-shell user attempted to call " + method);
3035 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3039 enforceFullCrossUsersPermission(userHandle);
3040 enforceUserUnlocked(userHandle);
3041 synchronized (this) {
3042 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3043 if (admin == null) {
3046 // Active device/profile owners must remain active admins.
3047 if (isDeviceOwner(adminReceiver, userHandle)
3048 || isProfileOwner(adminReceiver, userHandle)) {
3049 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3053 if (admin.getUid() != mInjector.binderGetCallingUid()) {
3054 mContext.enforceCallingOrSelfPermission(
3055 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3057 long ident = mInjector.binderClearCallingIdentity();
3059 removeActiveAdminLocked(adminReceiver, userHandle);
3061 mInjector.binderRestoreCallingIdentity(ident);
3067 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3068 ComponentName profileOwner = getProfileOwner(userHandle);
3069 // Profile challenge is supported on N or newer release.
3070 return profileOwner != null &&
3071 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3075 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3079 Preconditions.checkNotNull(who, "ComponentName is null");
3080 validateQualityConstant(quality);
3082 synchronized (this) {
3083 ActiveAdmin ap = getActiveAdminForCallerLocked(
3084 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3085 if (ap.passwordQuality != quality) {
3086 ap.passwordQuality = quality;
3087 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3093 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3095 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3097 enforceFullCrossUsersPermission(userHandle);
3098 synchronized (this) {
3099 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3102 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3103 return admin != null ? admin.passwordQuality : mode;
3106 // Return the strictest policy across all participating admins.
3107 List<ActiveAdmin> admins =
3108 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3109 final int N = admins.size();
3110 for (int i = 0; i < N; i++) {
3111 ActiveAdmin admin = admins.get(i);
3112 if (mode < admin.passwordQuality) {
3113 mode = admin.passwordQuality;
3120 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3121 int userHandle, boolean parent) {
3122 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3123 // If this user has a separate challenge, only return its restrictions.
3124 return getUserDataUnchecked(userHandle).mAdminList;
3126 // Return all admins for this user and the profiles that are visible from this
3127 // user that do not use a separate work challenge.
3128 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3129 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3130 DevicePolicyData policy = getUserData(userInfo.id);
3131 if (!userInfo.isManagedProfile()) {
3132 admins.addAll(policy.mAdminList);
3134 // For managed profiles, we always include the policies set on the parent
3135 // profile. Additionally, we include the ones set on the managed profile
3136 // if no separate challenge is in place.
3137 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3138 final int N = policy.mAdminList.size();
3139 for (int i = 0; i < N; i++) {
3140 ActiveAdmin admin = policy.mAdminList.get(i);
3141 if (admin.hasParentActiveAdmin()) {
3142 admins.add(admin.getParentActiveAdmin());
3144 if (!hasSeparateChallenge) {
3154 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3155 long ident = mInjector.binderClearCallingIdentity();
3157 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3159 mInjector.binderRestoreCallingIdentity(ident);
3164 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3168 Preconditions.checkNotNull(who, "ComponentName is null");
3169 synchronized (this) {
3170 ActiveAdmin ap = getActiveAdminForCallerLocked(
3171 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3172 if (ap.minimumPasswordLength != length) {
3173 ap.minimumPasswordLength = length;
3174 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3180 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3184 enforceFullCrossUsersPermission(userHandle);
3185 synchronized (this) {
3189 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3190 return admin != null ? admin.minimumPasswordLength : length;
3193 // Return the strictest policy across all participating admins.
3194 List<ActiveAdmin> admins =
3195 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3196 final int N = admins.size();
3197 for (int i = 0; i < N; i++) {
3198 ActiveAdmin admin = admins.get(i);
3199 if (length < admin.minimumPasswordLength) {
3200 length = admin.minimumPasswordLength;
3208 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3212 Preconditions.checkNotNull(who, "ComponentName is null");
3213 synchronized (this) {
3214 ActiveAdmin ap = getActiveAdminForCallerLocked(
3215 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3216 if (ap.passwordHistoryLength != length) {
3217 ap.passwordHistoryLength = length;
3218 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3224 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3228 enforceFullCrossUsersPermission(userHandle);
3229 synchronized (this) {
3233 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3234 return admin != null ? admin.passwordHistoryLength : length;
3237 // Return the strictest policy across all participating admins.
3238 List<ActiveAdmin> admins =
3239 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3240 final int N = admins.size();
3241 for (int i = 0; i < N; i++) {
3242 ActiveAdmin admin = admins.get(i);
3243 if (length < admin.passwordHistoryLength) {
3244 length = admin.passwordHistoryLength;
3253 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3257 Preconditions.checkNotNull(who, "ComponentName is null");
3258 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3259 final int userHandle = mInjector.userHandleGetCallingUserId();
3260 synchronized (this) {
3261 ActiveAdmin ap = getActiveAdminForCallerLocked(
3262 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3263 // Calling this API automatically bumps the expiration date
3264 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3265 ap.passwordExpirationDate = expiration;
3266 ap.passwordExpirationTimeout = timeout;
3268 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3269 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3270 .format(new Date(expiration)));
3272 saveSettingsLocked(userHandle);
3274 // in case this is the first one, set the alarm on the appropriate user.
3275 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3280 * Return a single admin's expiration cycle time, or the min of all cycle times.
3281 * Returns 0 if not configured.
3284 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3288 enforceFullCrossUsersPermission(userHandle);
3289 synchronized (this) {
3293 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3294 return admin != null ? admin.passwordExpirationTimeout : timeout;
3297 // Return the strictest policy across all participating admins.
3298 List<ActiveAdmin> admins =
3299 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3300 final int N = admins.size();
3301 for (int i = 0; i < N; i++) {
3302 ActiveAdmin admin = admins.get(i);
3303 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3304 && timeout > admin.passwordExpirationTimeout)) {
3305 timeout = admin.passwordExpirationTimeout;
3313 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3314 final int userId = UserHandle.getCallingUserId();
3315 List<String> changedProviders = null;
3317 synchronized (this) {
3318 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3319 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3320 if (activeAdmin.crossProfileWidgetProviders == null) {
3321 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3323 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3324 if (!providers.contains(packageName)) {
3325 providers.add(packageName);
3326 changedProviders = new ArrayList<>(providers);
3327 saveSettingsLocked(userId);
3331 if (changedProviders != null) {
3332 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3340 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3341 final int userId = UserHandle.getCallingUserId();
3342 List<String> changedProviders = null;
3344 synchronized (this) {
3345 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3346 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3347 if (activeAdmin.crossProfileWidgetProviders == null) {
3350 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3351 if (providers.remove(packageName)) {
3352 changedProviders = new ArrayList<>(providers);
3353 saveSettingsLocked(userId);
3357 if (changedProviders != null) {
3358 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3366 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3367 synchronized (this) {
3368 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3369 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3370 if (activeAdmin.crossProfileWidgetProviders == null
3371 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3374 if (mInjector.binderIsCallingUidMyUid()) {
3375 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3377 return activeAdmin.crossProfileWidgetProviders;
3383 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3384 * Returns 0 if not configured.
3386 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3390 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3391 return admin != null ? admin.passwordExpirationDate : timeout;
3394 // Return the strictest policy across all participating admins.
3395 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3396 final int N = admins.size();
3397 for (int i = 0; i < N; i++) {
3398 ActiveAdmin admin = admins.get(i);
3399 if (timeout == 0L || (admin.passwordExpirationDate != 0
3400 && timeout > admin.passwordExpirationDate)) {
3401 timeout = admin.passwordExpirationDate;
3408 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3412 enforceFullCrossUsersPermission(userHandle);
3413 synchronized (this) {
3414 return getPasswordExpirationLocked(who, userHandle, parent);
3419 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3423 Preconditions.checkNotNull(who, "ComponentName is null");
3424 synchronized (this) {
3425 ActiveAdmin ap = getActiveAdminForCallerLocked(
3426 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3427 if (ap.minimumPasswordUpperCase != length) {
3428 ap.minimumPasswordUpperCase = length;
3429 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3435 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3439 enforceFullCrossUsersPermission(userHandle);
3440 synchronized (this) {
3444 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3445 return admin != null ? admin.minimumPasswordUpperCase : length;
3448 // Return the strictest policy across all participating admins.
3449 List<ActiveAdmin> admins =
3450 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3451 final int N = admins.size();
3452 for (int i = 0; i < N; i++) {
3453 ActiveAdmin admin = admins.get(i);
3454 if (length < admin.minimumPasswordUpperCase) {
3455 length = admin.minimumPasswordUpperCase;
3463 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3464 Preconditions.checkNotNull(who, "ComponentName is null");
3465 synchronized (this) {
3466 ActiveAdmin ap = getActiveAdminForCallerLocked(
3467 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3468 if (ap.minimumPasswordLowerCase != length) {
3469 ap.minimumPasswordLowerCase = length;
3470 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3476 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3480 enforceFullCrossUsersPermission(userHandle);
3481 synchronized (this) {
3485 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3486 return admin != null ? admin.minimumPasswordLowerCase : length;
3489 // Return the strictest policy across all participating admins.
3490 List<ActiveAdmin> admins =
3491 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3492 final int N = admins.size();
3493 for (int i = 0; i < N; i++) {
3494 ActiveAdmin admin = admins.get(i);
3495 if (length < admin.minimumPasswordLowerCase) {
3496 length = admin.minimumPasswordLowerCase;
3504 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3508 Preconditions.checkNotNull(who, "ComponentName is null");
3509 synchronized (this) {
3510 ActiveAdmin ap = getActiveAdminForCallerLocked(
3511 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3512 if (ap.minimumPasswordLetters != length) {
3513 ap.minimumPasswordLetters = length;
3514 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3520 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3524 enforceFullCrossUsersPermission(userHandle);
3525 synchronized (this) {
3529 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3530 return admin != null ? admin.minimumPasswordLetters : length;
3533 // Return the strictest policy across all participating admins.
3534 List<ActiveAdmin> admins =
3535 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3536 final int N = admins.size();
3537 for (int i = 0; i < N; i++) {
3538 ActiveAdmin admin = admins.get(i);
3539 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3542 if (length < admin.minimumPasswordLetters) {
3543 length = admin.minimumPasswordLetters;
3551 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3555 Preconditions.checkNotNull(who, "ComponentName is null");
3556 synchronized (this) {
3557 ActiveAdmin ap = getActiveAdminForCallerLocked(
3558 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3559 if (ap.minimumPasswordNumeric != length) {
3560 ap.minimumPasswordNumeric = length;
3561 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3567 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3571 enforceFullCrossUsersPermission(userHandle);
3572 synchronized (this) {
3576 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3577 return admin != null ? admin.minimumPasswordNumeric : length;
3580 // Return the strictest policy across all participating admins.
3581 List<ActiveAdmin> admins =
3582 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3583 final int N = admins.size();
3584 for (int i = 0; i < N; i++) {
3585 ActiveAdmin admin = admins.get(i);
3586 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3589 if (length < admin.minimumPasswordNumeric) {
3590 length = admin.minimumPasswordNumeric;
3598 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3602 Preconditions.checkNotNull(who, "ComponentName is null");
3603 synchronized (this) {
3604 ActiveAdmin ap = getActiveAdminForCallerLocked(
3605 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3606 if (ap.minimumPasswordSymbols != length) {
3607 ap.minimumPasswordSymbols = length;
3608 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3614 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3618 enforceFullCrossUsersPermission(userHandle);
3619 synchronized (this) {
3623 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3624 return admin != null ? admin.minimumPasswordSymbols : length;
3627 // Return the strictest policy across all participating admins.
3628 List<ActiveAdmin> admins =
3629 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3630 final int N = admins.size();
3631 for (int i = 0; i < N; i++) {
3632 ActiveAdmin admin = admins.get(i);
3633 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3636 if (length < admin.minimumPasswordSymbols) {
3637 length = admin.minimumPasswordSymbols;
3645 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3649 Preconditions.checkNotNull(who, "ComponentName is null");
3650 synchronized (this) {
3651 ActiveAdmin ap = getActiveAdminForCallerLocked(
3652 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3653 if (ap.minimumPasswordNonLetter != length) {
3654 ap.minimumPasswordNonLetter = length;
3655 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3661 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3665 enforceFullCrossUsersPermission(userHandle);
3666 synchronized (this) {
3670 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3671 return admin != null ? admin.minimumPasswordNonLetter : length;
3674 // Return the strictest policy across all participating admins.
3675 List<ActiveAdmin> admins =
3676 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3677 final int N = admins.size();
3678 for (int i = 0; i < N; i++) {
3679 ActiveAdmin admin = admins.get(i);
3680 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3683 if (length < admin.minimumPasswordNonLetter) {
3684 length = admin.minimumPasswordNonLetter;
3692 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3696 enforceFullCrossUsersPermission(userHandle);
3698 synchronized (this) {
3699 // This API can only be called by an active device admin,
3700 // so try to retrieve it to check that the caller is one.
3701 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3702 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3703 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3708 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3712 enforceFullCrossUsersPermission(userHandle);
3713 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3715 synchronized (this) {
3716 int targetUser = getProfileParentId(userHandle);
3717 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3718 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3722 private boolean isActivePasswordSufficientForUserLocked(
3723 DevicePolicyData policy, int userHandle, boolean parent) {
3724 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
3725 if (policy.mActivePasswordQuality < requiredPasswordQuality) {
3728 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
3729 && policy.mActivePasswordLength < getPasswordMinimumLength(
3730 null, userHandle, parent)) {
3733 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3736 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3737 null, userHandle, parent)
3738 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3739 null, userHandle, parent)
3740 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3741 null, userHandle, parent)
3742 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3743 null, userHandle, parent)
3744 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3745 null, userHandle, parent)
3746 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3747 null, userHandle, parent);
3751 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3752 enforceFullCrossUsersPermission(userHandle);
3753 synchronized (this) {
3754 if (!isCallerWithSystemUid()) {
3755 // This API can only be called by an active device admin,
3756 // so try to retrieve it to check that the caller is one.
3757 getActiveAdminForCallerLocked(
3758 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3761 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3763 return policy.mFailedPasswordAttempts;
3768 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3772 Preconditions.checkNotNull(who, "ComponentName is null");
3773 synchronized (this) {
3774 // This API can only be called by an active device admin,
3775 // so try to retrieve it to check that the caller is one.
3776 getActiveAdminForCallerLocked(
3777 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3778 ActiveAdmin ap = getActiveAdminForCallerLocked(
3779 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3780 if (ap.maximumFailedPasswordsForWipe != num) {
3781 ap.maximumFailedPasswordsForWipe = num;
3782 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3788 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3792 enforceFullCrossUsersPermission(userHandle);
3793 synchronized (this) {
3794 ActiveAdmin admin = (who != null)
3795 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3796 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3797 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3802 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3804 return UserHandle.USER_NULL;
3806 enforceFullCrossUsersPermission(userHandle);
3807 synchronized (this) {
3808 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3809 userHandle, parent);
3810 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3815 * Returns the admin with the strictest policy on maximum failed passwords for:
3817 * <li>this user if it has a separate profile challenge, or
3818 * <li>this user and all profiles that don't have their own challenge otherwise.
3820 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3821 * the primary profile.
3822 * Returns {@code null} if no participating admin has that policy set.
3824 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3825 int userHandle, boolean parent) {
3827 ActiveAdmin strictestAdmin = null;
3829 // Return the strictest policy across all participating admins.
3830 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3831 final int N = admins.size();
3832 for (int i = 0; i < N; i++) {
3833 ActiveAdmin admin = admins.get(i);
3834 if (admin.maximumFailedPasswordsForWipe ==
3835 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3836 continue; // No max number of failed passwords policy set for this profile.
3839 // We always favor the primary profile if several profiles have the same value set.
3840 int userId = admin.getUserHandle().getIdentifier();
3842 count > admin.maximumFailedPasswordsForWipe ||
3843 (count == admin.maximumFailedPasswordsForWipe &&
3844 getUserInfo(userId).isPrimary())) {
3845 count = admin.maximumFailedPasswordsForWipe;
3846 strictestAdmin = admin;
3849 return strictestAdmin;
3852 private UserInfo getUserInfo(@UserIdInt int userId) {
3853 final long token = mInjector.binderClearCallingIdentity();
3855 return mUserManager.getUserInfo(userId);
3857 mInjector.binderRestoreCallingIdentity(token);
3862 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3866 final int callingUid = mInjector.binderGetCallingUid();
3867 final int userHandle = mInjector.userHandleGetCallingUserId();
3869 String password = passwordOrNull != null ? passwordOrNull : "";
3871 // Password resetting to empty/null is not allowed for managed profiles.
3872 if (TextUtils.isEmpty(password)) {
3873 enforceNotManagedProfile(userHandle, "clear the active password");
3877 synchronized (this) {
3878 // If caller has PO (or DO) it can change the password, so see if that's the case first.
3879 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3880 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3882 if (admin != null) {
3883 preN = getTargetSdk(admin.info.getPackageName(),
3884 userHandle) <= android.os.Build.VERSION_CODES.M;
3886 // Otherwise, make sure the caller has any active admin with the right policy.
3887 admin = getActiveAdminForCallerLocked(null,
3888 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3889 preN = getTargetSdk(admin.info.getPackageName(),
3890 userHandle) <= android.os.Build.VERSION_CODES.M;
3892 // As of N, password resetting to empty/null is not allowed anymore.
3893 // TODO Should we allow DO/PO to set an empty password?
3894 if (TextUtils.isEmpty(password)) {
3896 throw new SecurityException("Cannot call with null password");
3898 Slog.e(LOG_TAG, "Cannot call with null password");
3902 // As of N, password cannot be changed by the admin if it is already set.
3903 if (isLockScreenSecureUnchecked(userHandle)) {
3905 throw new SecurityException("Admin cannot change current password");
3907 Slog.e(LOG_TAG, "Admin cannot change current password");
3912 // Do not allow to reset password when current user has a managed profile
3913 if (!isManagedProfile(userHandle)) {
3914 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3915 if (userInfo.isManagedProfile()) {
3917 throw new IllegalStateException(
3918 "Cannot reset password on user has managed profile");
3920 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
3926 // Do not allow to reset password when user is locked
3927 if (!mUserManager.isUserUnlocked(userHandle)) {
3929 throw new IllegalStateException("Cannot reset password when user is locked");
3931 Slog.e(LOG_TAG, "Cannot reset password when user is locked");
3936 quality = getPasswordQuality(null, userHandle, /* parent */ false);
3937 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
3938 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3940 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
3941 int realQuality = LockPatternUtils.computePasswordQuality(password);
3942 if (realQuality < quality
3943 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3944 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
3945 + Integer.toHexString(realQuality)
3946 + " does not meet required quality 0x"
3947 + Integer.toHexString(quality));
3950 quality = Math.max(realQuality, quality);
3952 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
3953 if (password.length() < length) {
3954 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
3955 + " does not meet required length " + length);
3958 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3965 for (int i = 0; i < password.length(); i++) {
3966 char c = password.charAt(i);
3967 if (c >= 'A' && c <= 'Z') {
3970 } else if (c >= 'a' && c <= 'z') {
3973 } else if (c >= '0' && c <= '9') {
3981 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
3982 if(letters < neededLetters) {
3983 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
3984 + " does not meet required number of letters " + neededLetters);
3987 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
3988 if (numbers < neededNumbers) {
3989 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
3990 + " does not meet required number of numerical digits "
3994 int neededLowerCase = getPasswordMinimumLowerCase(
3995 null, userHandle, /* parent */ false);
3996 if (lowercase < neededLowerCase) {
3997 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
3998 + " does not meet required number of lowercase letters "
4002 int neededUpperCase = getPasswordMinimumUpperCase(
4003 null, userHandle, /* parent */ false);
4004 if (uppercase < neededUpperCase) {
4005 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
4006 + " does not meet required number of uppercase letters "
4010 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4011 if (symbols < neededSymbols) {
4012 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
4013 + " does not meet required number of special symbols " + neededSymbols);
4016 int neededNonLetter = getPasswordMinimumNonLetter(
4017 null, userHandle, /* parent */ false);
4018 if (nonletter < neededNonLetter) {
4019 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
4020 + " does not meet required number of non-letter characters "
4027 DevicePolicyData policy = getUserData(userHandle);
4028 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4029 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4033 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4034 boolean doNotAskCredentialsOnBoot =
4035 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4036 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4037 setDoNotAskCredentialsOnBoot();
4040 // Don't do this with the lock held, because it is going to call
4041 // back in to the service.
4042 final long ident = mInjector.binderClearCallingIdentity();
4044 if (!TextUtils.isEmpty(password)) {
4045 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4047 mLockPatternUtils.clearLock(userHandle);
4049 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4051 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4052 UserHandle.USER_ALL);
4054 synchronized (this) {
4055 int newOwner = requireEntry ? callingUid : -1;
4056 if (policy.mPasswordOwner != newOwner) {
4057 policy.mPasswordOwner = newOwner;
4058 saveSettingsLocked(userHandle);
4062 mInjector.binderRestoreCallingIdentity(ident);
4068 private boolean isLockScreenSecureUnchecked(int userId) {
4069 long ident = mInjector.binderClearCallingIdentity();
4071 return mLockPatternUtils.isSecure(userId);
4073 mInjector.binderRestoreCallingIdentity(ident);
4077 private void setDoNotAskCredentialsOnBoot() {
4078 synchronized (this) {
4079 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4080 if (!policyData.doNotAskCredentialsOnBoot) {
4081 policyData.doNotAskCredentialsOnBoot = true;
4082 saveSettingsLocked(UserHandle.USER_SYSTEM);
4088 public boolean getDoNotAskCredentialsOnBoot() {
4089 mContext.enforceCallingOrSelfPermission(
4090 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4091 synchronized (this) {
4092 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4093 return policyData.doNotAskCredentialsOnBoot;
4098 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4102 Preconditions.checkNotNull(who, "ComponentName is null");
4103 final int userHandle = mInjector.userHandleGetCallingUserId();
4104 synchronized (this) {
4105 ActiveAdmin ap = getActiveAdminForCallerLocked(
4106 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4107 if (ap.maximumTimeToUnlock != timeMs) {
4108 ap.maximumTimeToUnlock = timeMs;
4109 saveSettingsLocked(userHandle);
4110 updateMaximumTimeToLockLocked(userHandle);
4115 void updateMaximumTimeToLockLocked(int userHandle) {
4116 // Calculate the min timeout for all profiles - including the ones with a separate
4117 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4118 // challenge only and keep the screen on. However there is no easy way of doing that at the
4119 // moment so we set the screen off timeout regardless of whether it affects the parent user
4120 // or the profile challenge only.
4121 long timeMs = Long.MAX_VALUE;
4122 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4123 for (int profileId : profileIds) {
4124 DevicePolicyData policy = getUserDataUnchecked(profileId);
4125 final int N = policy.mAdminList.size();
4126 for (int i = 0; i < N; i++) {
4127 ActiveAdmin admin = policy.mAdminList.get(i);
4128 if (admin.maximumTimeToUnlock > 0
4129 && timeMs > admin.maximumTimeToUnlock) {
4130 timeMs = admin.maximumTimeToUnlock;
4132 // If userInfo.id is a managed profile, we also need to look at
4133 // the policies set on the parent.
4134 if (admin.hasParentActiveAdmin()) {
4135 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4136 if (parentAdmin.maximumTimeToUnlock > 0
4137 && timeMs > parentAdmin.maximumTimeToUnlock) {
4138 timeMs = parentAdmin.maximumTimeToUnlock;
4144 // We only store the last maximum time to lock on the parent profile. So if calling from a
4145 // managed profile, retrieve the policy for the parent.
4146 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4147 if (policy.mLastMaximumTimeToLock == timeMs) {
4150 policy.mLastMaximumTimeToLock = timeMs;
4152 final long ident = mInjector.binderClearCallingIdentity();
4154 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4155 // Make sure KEEP_SCREEN_ON is disabled, since that
4156 // would allow bypassing of the maximum time to lock.
4157 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4160 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4161 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4163 mInjector.binderRestoreCallingIdentity(ident);
4168 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4172 enforceFullCrossUsersPermission(userHandle);
4173 synchronized (this) {
4175 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4176 return admin != null ? admin.maximumTimeToUnlock : 0;
4178 // Return the strictest policy across all participating admins.
4179 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4180 userHandle, parent);
4181 return getMaximumTimeToLockPolicyFromAdmins(admins);
4186 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4190 enforceFullCrossUsersPermission(userHandle);
4191 synchronized (this) {
4192 // All admins for this user.
4193 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4194 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4195 DevicePolicyData policy = getUserData(userInfo.id);
4196 admins.addAll(policy.mAdminList);
4197 // If it is a managed profile, it may have parent active admins
4198 if (userInfo.isManagedProfile()) {
4199 for (ActiveAdmin admin : policy.mAdminList) {
4200 if (admin.hasParentActiveAdmin()) {
4201 admins.add(admin.getParentActiveAdmin());
4206 return getMaximumTimeToLockPolicyFromAdmins(admins);
4210 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4212 final int N = admins.size();
4213 for (int i = 0; i < N; i++) {
4214 ActiveAdmin admin = admins.get(i);
4216 time = admin.maximumTimeToUnlock;
4217 } else if (admin.maximumTimeToUnlock != 0
4218 && time > admin.maximumTimeToUnlock) {
4219 time = admin.maximumTimeToUnlock;
4226 public void lockNow(boolean parent) {
4230 synchronized (this) {
4231 // This API can only be called by an active device admin,
4232 // so try to retrieve it to check that the caller is one.
4233 getActiveAdminForCallerLocked(
4234 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4236 int userToLock = mInjector.userHandleGetCallingUserId();
4238 // Unless this is a managed profile with work challenge enabled, lock all users.
4239 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4240 userToLock = UserHandle.USER_ALL;
4242 final long ident = mInjector.binderClearCallingIdentity();
4244 mLockPatternUtils.requireStrongAuth(
4245 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4246 if (userToLock == UserHandle.USER_ALL) {
4247 // Power off the display
4248 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4249 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4250 mInjector.getIWindowManager().lockNow(null);
4252 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4254 } catch (RemoteException e) {
4256 mInjector.binderRestoreCallingIdentity(ident);
4262 public void enforceCanManageCaCerts(ComponentName who) {
4264 if (!isCallerDelegatedCertInstaller()) {
4265 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4268 synchronized (this) {
4269 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4274 private void enforceCanManageInstalledKeys(ComponentName who) {
4276 if (!isCallerDelegatedCertInstaller()) {
4277 throw new SecurityException("who == null, but caller is not cert installer");
4280 synchronized (this) {
4281 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4286 private boolean isCallerDelegatedCertInstaller() {
4287 final int callingUid = mInjector.binderGetCallingUid();
4288 final int userHandle = UserHandle.getUserId(callingUid);
4289 synchronized (this) {
4290 final DevicePolicyData policy = getUserData(userHandle);
4291 if (policy.mDelegatedCertInstallerPackage == null) {
4296 int uid = mContext.getPackageManager().getPackageUidAsUser(
4297 policy.mDelegatedCertInstallerPackage, userHandle);
4298 return uid == callingUid;
4299 } catch (NameNotFoundException e) {
4306 public boolean approveCaCert(String alias, int userId, boolean approval) {
4307 enforceManageUsers();
4308 synchronized (this) {
4309 Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4310 boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4314 saveSettingsLocked(userId);
4316 new MonitoringCertNotificationTask().execute(userId);
4321 public boolean isCaCertApproved(String alias, int userId) {
4322 enforceManageUsers();
4323 synchronized (this) {
4324 return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4328 private void removeCaApprovalsIfNeeded(int userId) {
4329 for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4330 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4331 if (userInfo.isManagedProfile()){
4332 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4335 synchronized (this) {
4336 getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4337 saveSettingsLocked(userInfo.id);
4340 new MonitoringCertNotificationTask().execute(userInfo.id);
4346 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4347 enforceCanManageCaCerts(admin);
4351 X509Certificate cert = parseCert(certBuffer);
4352 pemCert = Credentials.convertToPem(cert);
4353 } catch (CertificateException ce) {
4354 Log.e(LOG_TAG, "Problem converting cert", ce);
4356 } catch (IOException ioe) {
4357 Log.e(LOG_TAG, "Problem reading cert", ioe);
4361 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4362 final long id = mInjector.binderClearCallingIdentity();
4364 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4366 keyChainConnection.getService().installCaCertificate(pemCert);
4368 } catch (RemoteException e) {
4369 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4371 keyChainConnection.close();
4373 } catch (InterruptedException e1) {
4374 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4375 Thread.currentThread().interrupt();
4377 mInjector.binderRestoreCallingIdentity(id);
4382 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4383 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4384 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4389 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4390 enforceCanManageCaCerts(admin);
4392 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4393 final long id = mInjector.binderClearCallingIdentity();
4395 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4397 for (int i = 0 ; i < aliases.length; i++) {
4398 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4400 } catch (RemoteException e) {
4401 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4403 keyChainConnection.close();
4405 } catch (InterruptedException ie) {
4406 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4407 Thread.currentThread().interrupt();
4409 mInjector.binderRestoreCallingIdentity(id);
4414 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4415 String alias, boolean requestAccess) {
4416 enforceCanManageInstalledKeys(who);
4418 final int callingUid = mInjector.binderGetCallingUid();
4419 final long id = mInjector.binderClearCallingIdentity();
4421 final KeyChainConnection keyChainConnection =
4422 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4424 IKeyChainService keyChain = keyChainConnection.getService();
4425 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4428 if (requestAccess) {
4429 keyChain.setGrant(callingUid, alias, true);
4432 } catch (RemoteException e) {
4433 Log.e(LOG_TAG, "Installing certificate", e);
4435 keyChainConnection.close();
4437 } catch (InterruptedException e) {
4438 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4439 Thread.currentThread().interrupt();
4441 mInjector.binderRestoreCallingIdentity(id);
4447 public boolean removeKeyPair(ComponentName who, String alias) {
4448 enforceCanManageInstalledKeys(who);
4450 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4451 final long id = Binder.clearCallingIdentity();
4453 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4455 IKeyChainService keyChain = keyChainConnection.getService();
4456 return keyChain.removeKeyPair(alias);
4457 } catch (RemoteException e) {
4458 Log.e(LOG_TAG, "Removing keypair", e);
4460 keyChainConnection.close();
4462 } catch (InterruptedException e) {
4463 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4464 Thread.currentThread().interrupt();
4466 Binder.restoreCallingIdentity(id);
4472 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4473 final IBinder response) {
4474 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4475 if (!isCallerWithSystemUid()) {
4479 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4480 // If there is a profile owner, redirect to that; otherwise query the device owner.
4481 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4482 if (aliasChooser == null && caller.isSystem()) {
4483 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4484 if (deviceOwnerAdmin != null) {
4485 aliasChooser = deviceOwnerAdmin.info.getComponent();
4488 if (aliasChooser == null) {
4489 sendPrivateKeyAliasResponse(null, response);
4493 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4494 intent.setComponent(aliasChooser);
4495 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4496 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4497 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4498 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4499 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4501 final long id = mInjector.binderClearCallingIdentity();
4503 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4505 public void onReceive(Context context, Intent intent) {
4506 final String chosenAlias = getResultData();
4507 sendPrivateKeyAliasResponse(chosenAlias, response);
4509 }, null, Activity.RESULT_OK, null, null);
4511 mInjector.binderRestoreCallingIdentity(id);
4515 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4516 final IKeyChainAliasCallback keyChainAliasResponse =
4517 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4518 new AsyncTask<Void, Void, Void>() {
4520 protected Void doInBackground(Void... unused) {
4522 keyChainAliasResponse.alias(alias);
4523 } catch (Exception e) {
4524 // Catch everything (not just RemoteException): caller could throw a
4525 // RuntimeException back across processes.
4526 Log.e(LOG_TAG, "error while responding to callback", e);
4534 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4535 throws SecurityException {
4536 int userHandle = UserHandle.getCallingUserId();
4537 synchronized (this) {
4538 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4539 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4540 if (installerPackage != null &&
4541 !isPackageInstalledForUser(installerPackage, userHandle)) {
4542 throw new IllegalArgumentException("Package " + installerPackage
4543 + " is not installed on the current user");
4546 DevicePolicyData policy = getUserData(userHandle);
4547 policy.mDelegatedCertInstallerPackage = installerPackage;
4548 saveSettingsLocked(userHandle);
4553 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4554 int userHandle = UserHandle.getCallingUserId();
4555 synchronized (this) {
4556 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4557 DevicePolicyData policy = getUserData(userHandle);
4558 return policy.mDelegatedCertInstallerPackage;
4563 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4564 * not installed and therefore not available.
4566 * @throws SecurityException if the caller is not a profile or device owner.
4567 * @throws UnsupportedOperationException if the package does not support being set as always-on.
4570 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4571 throws SecurityException {
4572 synchronized (this) {
4573 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4576 final int userId = mInjector.userHandleGetCallingUserId();
4577 final long token = mInjector.binderClearCallingIdentity();
4579 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4582 ConnectivityManager connectivityManager = (ConnectivityManager)
4583 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4584 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4585 throw new UnsupportedOperationException();
4588 mInjector.binderRestoreCallingIdentity(token);
4594 public String getAlwaysOnVpnPackage(ComponentName admin)
4595 throws SecurityException {
4596 synchronized (this) {
4597 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4600 final int userId = mInjector.userHandleGetCallingUserId();
4601 final long token = mInjector.binderClearCallingIdentity();
4603 ConnectivityManager connectivityManager = (ConnectivityManager)
4604 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4605 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4607 mInjector.binderRestoreCallingIdentity(token);
4611 private void wipeDataLocked(boolean wipeExtRequested, String reason) {
4612 if (wipeExtRequested) {
4613 StorageManager sm = (StorageManager) mContext.getSystemService(
4614 Context.STORAGE_SERVICE);
4615 sm.wipeAdoptableDisks();
4618 RecoverySystem.rebootWipeUserData(mContext, reason);
4619 } catch (IOException | SecurityException e) {
4620 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4625 public void wipeData(int flags) {
4629 final int userHandle = mInjector.userHandleGetCallingUserId();
4630 enforceFullCrossUsersPermission(userHandle);
4631 synchronized (this) {
4632 // This API can only be called by an active device admin,
4633 // so try to retrieve it to check that the caller is one.
4634 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4635 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4637 final String source = admin.info.getComponent().flattenToShortString();
4639 long ident = mInjector.binderClearCallingIdentity();
4641 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4642 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4643 throw new SecurityException(
4644 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4646 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4647 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4648 if (manager != null) {
4652 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4653 wipeDeviceOrUserLocked(wipeExtRequested, userHandle,
4654 "DevicePolicyManager.wipeData() from " + source);
4656 mInjector.binderRestoreCallingIdentity(ident);
4661 private void wipeDeviceOrUserLocked(boolean wipeExtRequested, final int userHandle, String reason) {
4662 if (userHandle == UserHandle.USER_SYSTEM) {
4663 wipeDataLocked(wipeExtRequested, reason);
4665 mHandler.post(new Runnable() {
4669 IActivityManager am = mInjector.getIActivityManager();
4670 if (am.getCurrentUser().id == userHandle) {
4671 am.switchUser(UserHandle.USER_SYSTEM);
4674 boolean isManagedProfile = isManagedProfile(userHandle);
4675 if (!mUserManager.removeUser(userHandle)) {
4676 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4677 } else if (isManagedProfile) {
4678 sendWipeProfileNotification();
4680 } catch (RemoteException re) {
4688 private void sendWipeProfileNotification() {
4689 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4690 Notification notification = new Notification.Builder(mContext)
4691 .setSmallIcon(android.R.drawable.stat_sys_warning)
4692 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4693 .setContentText(contentText)
4694 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4695 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4697 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4700 private void clearWipeProfileNotification() {
4701 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4705 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4709 enforceFullCrossUsersPermission(userHandle);
4710 mContext.enforceCallingOrSelfPermission(
4711 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4713 synchronized (this) {
4714 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4715 if (admin == null) {
4716 result.sendResult(null);
4719 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4720 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4721 intent.setComponent(admin.info.getComponent());
4722 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4723 null, new BroadcastReceiver() {
4725 public void onReceive(Context context, Intent intent) {
4726 result.sendResult(getResultExtras(false));
4728 }, null, Activity.RESULT_OK, null, null);
4733 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4734 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4738 enforceFullCrossUsersPermission(userHandle);
4740 // Managed Profile password can only be changed when it has a separate challenge.
4741 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4742 enforceNotManagedProfile(userHandle, "set the active password");
4745 mContext.enforceCallingOrSelfPermission(
4746 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4747 validateQualityConstant(quality);
4749 DevicePolicyData policy = getUserData(userHandle);
4751 long ident = mInjector.binderClearCallingIdentity();
4753 synchronized (this) {
4754 policy.mActivePasswordQuality = quality;
4755 policy.mActivePasswordLength = length;
4756 policy.mActivePasswordLetters = letters;
4757 policy.mActivePasswordLowerCase = lowercase;
4758 policy.mActivePasswordUpperCase = uppercase;
4759 policy.mActivePasswordNumeric = numbers;
4760 policy.mActivePasswordSymbols = symbols;
4761 policy.mActivePasswordNonLetter = nonletter;
4762 policy.mFailedPasswordAttempts = 0;
4763 saveSettingsLocked(userHandle);
4764 updatePasswordExpirationsLocked(userHandle);
4765 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
4767 // Send a broadcast to each profile using this password as its primary unlock.
4768 sendAdminCommandForLockscreenPoliciesLocked(
4769 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4770 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
4772 removeCaApprovalsIfNeeded(userHandle);
4774 mInjector.binderRestoreCallingIdentity(ident);
4779 * Called any time the device password is updated. Resets all password expiration clocks.
4781 private void updatePasswordExpirationsLocked(int userHandle) {
4782 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4783 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4784 userHandle, /* parent */ false);
4785 final int N = admins.size();
4786 for (int i = 0; i < N; i++) {
4787 ActiveAdmin admin = admins.get(i);
4788 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4789 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4790 long timeout = admin.passwordExpirationTimeout;
4791 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4792 admin.passwordExpirationDate = expiration;
4795 for (int affectedUserId : affectedUserIds) {
4796 saveSettingsLocked(affectedUserId);
4801 public void reportFailedPasswordAttempt(int userHandle) {
4802 enforceFullCrossUsersPermission(userHandle);
4803 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4804 enforceNotManagedProfile(userHandle,
4805 "report failed password attempt if separate profile challenge is not in place");
4807 mContext.enforceCallingOrSelfPermission(
4808 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4810 final long ident = mInjector.binderClearCallingIdentity();
4812 boolean wipeData = false;
4814 synchronized (this) {
4815 DevicePolicyData policy = getUserData(userHandle);
4816 policy.mFailedPasswordAttempts++;
4817 saveSettingsLocked(userHandle);
4819 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4820 userHandle, /* parent */ false);
4821 int max = strictestAdmin != null
4822 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4823 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4824 // Wipe the user/profile associated with the policy that was violated. This
4825 // is not necessarily calling user: if the policy that fired was from a
4826 // managed profile rather than the main user profile, we wipe former only.
4828 identifier = strictestAdmin.getUserHandle().getIdentifier();
4831 sendAdminCommandForLockscreenPoliciesLocked(
4832 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
4833 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4837 // Call without holding lock.
4838 wipeDeviceOrUserLocked(false, identifier,
4839 "reportFailedPasswordAttempt()");
4842 mInjector.binderRestoreCallingIdentity(ident);
4845 if (mInjector.securityLogIsLoggingEnabled()) {
4846 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4847 /*method strength*/ 1);
4852 public void reportSuccessfulPasswordAttempt(int userHandle) {
4853 enforceFullCrossUsersPermission(userHandle);
4854 mContext.enforceCallingOrSelfPermission(
4855 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4857 synchronized (this) {
4858 DevicePolicyData policy = getUserData(userHandle);
4859 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
4860 long ident = mInjector.binderClearCallingIdentity();
4862 policy.mFailedPasswordAttempts = 0;
4863 policy.mPasswordOwner = -1;
4864 saveSettingsLocked(userHandle);
4866 sendAdminCommandForLockscreenPoliciesLocked(
4867 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
4868 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4871 mInjector.binderRestoreCallingIdentity(ident);
4876 if (mInjector.securityLogIsLoggingEnabled()) {
4877 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4878 /*method strength*/ 1);
4883 public void reportFailedFingerprintAttempt(int userHandle) {
4884 enforceFullCrossUsersPermission(userHandle);
4885 mContext.enforceCallingOrSelfPermission(
4886 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4887 if (mInjector.securityLogIsLoggingEnabled()) {
4888 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4889 /*method strength*/ 0);
4894 public void reportSuccessfulFingerprintAttempt(int userHandle) {
4895 enforceFullCrossUsersPermission(userHandle);
4896 mContext.enforceCallingOrSelfPermission(
4897 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4898 if (mInjector.securityLogIsLoggingEnabled()) {
4899 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4900 /*method strength*/ 0);
4905 public void reportKeyguardDismissed(int userHandle) {
4906 enforceFullCrossUsersPermission(userHandle);
4907 mContext.enforceCallingOrSelfPermission(
4908 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4910 if (mInjector.securityLogIsLoggingEnabled()) {
4911 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
4916 public void reportKeyguardSecured(int userHandle) {
4917 enforceFullCrossUsersPermission(userHandle);
4918 mContext.enforceCallingOrSelfPermission(
4919 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4921 if (mInjector.securityLogIsLoggingEnabled()) {
4922 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
4927 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
4928 String exclusionList) {
4932 synchronized(this) {
4933 Preconditions.checkNotNull(who, "ComponentName is null");
4935 // Only check if system user has set global proxy. We don't allow other users to set it.
4936 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4937 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4938 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
4940 // Scan through active admins and find if anyone has already
4941 // set the global proxy.
4942 Set<ComponentName> compSet = policy.mAdminMap.keySet();
4943 for (ComponentName component : compSet) {
4944 ActiveAdmin ap = policy.mAdminMap.get(component);
4945 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
4946 // Another admin already sets the global proxy
4947 // Return it to the caller.
4952 // If the user is not system, don't set the global proxy. Fail silently.
4953 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
4954 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
4955 + UserHandle.getCallingUserId() + " is not permitted.");
4958 if (proxySpec == null) {
4959 admin.specifiesGlobalProxy = false;
4960 admin.globalProxySpec = null;
4961 admin.globalProxyExclusionList = null;
4964 admin.specifiesGlobalProxy = true;
4965 admin.globalProxySpec = proxySpec;
4966 admin.globalProxyExclusionList = exclusionList;
4969 // Reset the global proxy accordingly
4970 // Do this using system permissions, as apps cannot write to secure settings
4971 long origId = mInjector.binderClearCallingIdentity();
4973 resetGlobalProxyLocked(policy);
4975 mInjector.binderRestoreCallingIdentity(origId);
4982 public ComponentName getGlobalProxyAdmin(int userHandle) {
4986 enforceFullCrossUsersPermission(userHandle);
4987 synchronized(this) {
4988 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4989 // Scan through active admins and find if anyone has already
4990 // set the global proxy.
4991 final int N = policy.mAdminList.size();
4992 for (int i = 0; i < N; i++) {
4993 ActiveAdmin ap = policy.mAdminList.get(i);
4994 if (ap.specifiesGlobalProxy) {
4995 // Device admin sets the global proxy
4996 // Return it to the caller.
4997 return ap.info.getComponent();
5001 // No device admin sets the global proxy.
5006 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5007 synchronized (this) {
5008 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5010 long token = mInjector.binderClearCallingIdentity();
5012 ConnectivityManager connectivityManager = (ConnectivityManager)
5013 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5014 connectivityManager.setGlobalProxy(proxyInfo);
5016 mInjector.binderRestoreCallingIdentity(token);
5020 private void resetGlobalProxyLocked(DevicePolicyData policy) {
5021 final int N = policy.mAdminList.size();
5022 for (int i = 0; i < N; i++) {
5023 ActiveAdmin ap = policy.mAdminList.get(i);
5024 if (ap.specifiesGlobalProxy) {
5025 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5029 // No device admins defining global proxies - reset global proxy settings to none
5030 saveGlobalProxyLocked(null, null);
5033 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5034 if (exclusionList == null) {
5037 if (proxySpec == null) {
5040 // Remove white spaces
5041 proxySpec = proxySpec.trim();
5042 String data[] = proxySpec.split(":");
5043 int proxyPort = 8080;
5044 if (data.length > 1) {
5046 proxyPort = Integer.parseInt(data[1]);
5047 } catch (NumberFormatException e) {}
5049 exclusionList = exclusionList.trim();
5051 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5052 if (!proxyProperties.isValid()) {
5053 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5056 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5057 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5058 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5063 * Set the storage encryption request for a single admin. Returns the new total request
5064 * status (for all admins).
5067 public int setStorageEncryption(ComponentName who, boolean encrypt) {
5069 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5071 Preconditions.checkNotNull(who, "ComponentName is null");
5072 final int userHandle = UserHandle.getCallingUserId();
5073 synchronized (this) {
5074 // Check for permissions
5075 // Only system user can set storage encryption
5076 if (userHandle != UserHandle.USER_SYSTEM) {
5077 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5078 + UserHandle.getCallingUserId() + " is not permitted.");
5082 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5083 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5085 // Quick exit: If the filesystem does not support encryption, we can exit early.
5086 if (!isEncryptionSupported()) {
5087 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5090 // (1) Record the value for the admin so it's sticky
5091 if (ap.encryptionRequested != encrypt) {
5092 ap.encryptionRequested = encrypt;
5093 saveSettingsLocked(userHandle);
5096 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5097 // (2) Compute "max" for all admins
5098 boolean newRequested = false;
5099 final int N = policy.mAdminList.size();
5100 for (int i = 0; i < N; i++) {
5101 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5104 // Notify OS of new request
5105 setEncryptionRequested(newRequested);
5107 // Return the new global request status
5109 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5110 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5115 * Get the current storage encryption request status for a given admin, or aggregate of all
5119 public boolean getStorageEncryption(ComponentName who, int userHandle) {
5123 enforceFullCrossUsersPermission(userHandle);
5124 synchronized (this) {
5125 // Check for permissions if a particular caller is specified
5127 // When checking for a single caller, status is based on caller's request
5128 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5129 return ap != null ? ap.encryptionRequested : false;
5132 // If no particular caller is specified, return the aggregate set of requests.
5133 // This is short circuited by returning true on the first hit.
5134 DevicePolicyData policy = getUserData(userHandle);
5135 final int N = policy.mAdminList.size();
5136 for (int i = 0; i < N; i++) {
5137 if (policy.mAdminList.get(i).encryptionRequested) {
5146 * Get the current encryption status of the device.
5149 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5151 // Ok to return current status.
5153 enforceFullCrossUsersPermission(userHandle);
5155 // It's not critical here, but let's make sure the package name is correct, in case
5156 // we start using it for different purposes.
5157 ensureCallerPackage(callerPackage);
5159 final ApplicationInfo ai;
5161 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5162 } catch (RemoteException e) {
5163 throw new SecurityException(e);
5166 boolean legacyApp = false;
5167 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5171 final int rawStatus = getEncryptionStatus();
5172 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5173 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5179 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
5181 private boolean isEncryptionSupported() {
5182 // Note, this can be implemented as
5183 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5184 // But is provided as a separate internal method if there's a faster way to do a
5185 // simple check for supported-or-not.
5186 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5190 * Hook to low-levels: Reporting the current status of encryption.
5191 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5192 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5193 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5194 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5195 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5197 private int getEncryptionStatus() {
5198 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5199 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5200 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5201 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5202 } else if (mInjector.storageManagerIsEncrypted()) {
5203 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5204 } else if (mInjector.storageManagerIsEncryptable()) {
5205 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5207 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5212 * Hook to low-levels: If needed, record the new admin setting for encryption.
5214 private void setEncryptionRequested(boolean encrypt) {
5218 * Set whether the screen capture is disabled for the user managed by the specified admin.
5221 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5225 Preconditions.checkNotNull(who, "ComponentName is null");
5226 final int userHandle = UserHandle.getCallingUserId();
5227 synchronized (this) {
5228 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5229 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5230 if (ap.disableScreenCapture != disabled) {
5231 ap.disableScreenCapture = disabled;
5232 saveSettingsLocked(userHandle);
5233 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5239 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5240 * active admin (if given admin is null).
5243 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5247 synchronized (this) {
5249 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5250 return (admin != null) ? admin.disableScreenCapture : false;
5253 DevicePolicyData policy = getUserData(userHandle);
5254 final int N = policy.mAdminList.size();
5255 for (int i = 0; i < N; i++) {
5256 ActiveAdmin admin = policy.mAdminList.get(i);
5257 if (admin.disableScreenCapture) {
5265 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5266 final boolean disabled) {
5267 mHandler.post(new Runnable() {
5271 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5272 } catch (RemoteException e) {
5273 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5280 * Set whether auto time is required by the specified admin (must be device owner).
5283 public void setAutoTimeRequired(ComponentName who, boolean required) {
5287 Preconditions.checkNotNull(who, "ComponentName is null");
5288 final int userHandle = UserHandle.getCallingUserId();
5289 synchronized (this) {
5290 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5291 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5292 if (admin.requireAutoTime != required) {
5293 admin.requireAutoTime = required;
5294 saveSettingsLocked(userHandle);
5298 // Turn AUTO_TIME on in settings if it is required
5300 long ident = mInjector.binderClearCallingIdentity();
5302 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5304 mInjector.binderRestoreCallingIdentity(ident);
5310 * Returns whether or not auto time is required by the device owner.
5313 public boolean getAutoTimeRequired() {
5317 synchronized (this) {
5318 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5319 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5324 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5328 Preconditions.checkNotNull(who, "ComponentName is null");
5329 // Allow setting this policy to true only if there is a split system user.
5330 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5331 throw new UnsupportedOperationException(
5332 "Cannot force ephemeral users on systems without split system user.");
5334 boolean removeAllUsers = false;
5335 synchronized (this) {
5336 final ActiveAdmin deviceOwner =
5337 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5338 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5339 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5340 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5341 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5342 removeAllUsers = forceEphemeralUsers;
5345 if (removeAllUsers) {
5346 long identitity = mInjector.binderClearCallingIdentity();
5348 mUserManagerInternal.removeAllUsers();
5350 mInjector.binderRestoreCallingIdentity(identitity);
5356 public boolean getForceEphemeralUsers(ComponentName who) {
5360 Preconditions.checkNotNull(who, "ComponentName is null");
5361 synchronized (this) {
5362 final ActiveAdmin deviceOwner =
5363 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5364 return deviceOwner.forceEphemeralUsers;
5368 private boolean isDeviceOwnerManagedSingleUserDevice() {
5369 synchronized (this) {
5370 if (!mOwners.hasDeviceOwner()) {
5374 final long callingIdentity = mInjector.binderClearCallingIdentity();
5376 if (mInjector.userManagerIsSplitSystemUser()) {
5377 // In split system user mode, only allow the case where the device owner is managing
5378 // the only non-system user of the device
5379 return (mUserManager.getUserCount() == 2
5380 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5382 return mUserManager.getUserCount() == 1;
5385 mInjector.binderRestoreCallingIdentity(callingIdentity);
5389 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5390 synchronized (this) {
5391 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5393 if (!isDeviceOwnerManagedSingleUserDevice()) {
5394 throw new SecurityException(
5395 "There should only be one user, managed by Device Owner");
5400 public boolean requestBugreport(ComponentName who) {
5404 Preconditions.checkNotNull(who, "ComponentName is null");
5405 ensureDeviceOwnerManagingSingleUser(who);
5407 if (mRemoteBugreportServiceIsActive.get()
5408 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5409 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5413 final long callingIdentity = mInjector.binderClearCallingIdentity();
5415 ActivityManagerNative.getDefault().requestBugReport(
5416 ActivityManager.BUGREPORT_OPTION_REMOTE);
5418 mRemoteBugreportServiceIsActive.set(true);
5419 mRemoteBugreportSharingAccepted.set(false);
5420 registerRemoteBugreportReceivers();
5421 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5422 RemoteBugreportUtils.buildNotification(mContext,
5423 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5424 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5425 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5427 } catch (RemoteException re) {
5428 // should never happen
5429 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5432 mInjector.binderRestoreCallingIdentity(callingIdentity);
5436 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5437 Intent intent = new Intent(action);
5438 intent.setComponent(mOwners.getDeviceOwnerComponent());
5439 if (extras != null) {
5440 intent.putExtras(extras);
5442 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5445 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5446 return mOwners.getDeviceOwnerRemoteBugreportUri();
5449 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5450 String bugreportHash) {
5451 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5454 private void registerRemoteBugreportReceivers() {
5456 IntentFilter filterFinished = new IntentFilter(
5457 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5458 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5459 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5460 } catch (IntentFilter.MalformedMimeTypeException e) {
5461 // should never happen, as setting a constant
5462 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5464 IntentFilter filterConsent = new IntentFilter();
5465 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5466 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5467 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5470 private void onBugreportFinished(Intent intent) {
5471 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5472 mRemoteBugreportServiceIsActive.set(false);
5473 Uri bugreportUri = intent.getData();
5474 String bugreportUriString = null;
5475 if (bugreportUri != null) {
5476 bugreportUriString = bugreportUri.toString();
5478 String bugreportHash = intent.getStringExtra(
5479 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5480 if (mRemoteBugreportSharingAccepted.get()) {
5481 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5482 mInjector.getNotificationManager().cancel(LOG_TAG,
5483 RemoteBugreportUtils.NOTIFICATION_ID);
5485 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5486 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5487 RemoteBugreportUtils.buildNotification(mContext,
5488 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5491 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5494 private void onBugreportFailed() {
5495 mRemoteBugreportServiceIsActive.set(false);
5496 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5497 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5498 mRemoteBugreportSharingAccepted.set(false);
5499 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5500 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5501 Bundle extras = new Bundle();
5502 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5503 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5504 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5505 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5506 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5509 private void onBugreportSharingAccepted() {
5510 mRemoteBugreportSharingAccepted.set(true);
5511 String bugreportUriString = null;
5512 String bugreportHash = null;
5513 synchronized (this) {
5514 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5515 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5517 if (bugreportUriString != null) {
5518 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5519 } else if (mRemoteBugreportServiceIsActive.get()) {
5520 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5521 RemoteBugreportUtils.buildNotification(mContext,
5522 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5527 private void onBugreportSharingDeclined() {
5528 if (mRemoteBugreportServiceIsActive.get()) {
5529 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5530 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5531 mRemoteBugreportServiceIsActive.set(false);
5532 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5533 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5535 mRemoteBugreportSharingAccepted.set(false);
5536 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5537 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5540 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5541 String bugreportHash) {
5542 ParcelFileDescriptor pfd = null;
5544 if (bugreportUriString == null) {
5545 throw new FileNotFoundException();
5547 Uri bugreportUri = Uri.parse(bugreportUriString);
5548 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5550 synchronized (this) {
5551 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5552 intent.setComponent(mOwners.getDeviceOwnerComponent());
5553 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5554 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5555 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
5556 bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5557 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5559 } catch (FileNotFoundException e) {
5560 Bundle extras = new Bundle();
5561 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5562 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5563 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5569 } catch (IOException ex) {
5572 mRemoteBugreportSharingAccepted.set(false);
5573 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5578 * Disables all device cameras according to the specified admin.
5581 public void setCameraDisabled(ComponentName who, boolean disabled) {
5585 Preconditions.checkNotNull(who, "ComponentName is null");
5586 final int userHandle = mInjector.userHandleGetCallingUserId();
5587 synchronized (this) {
5588 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5589 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5590 if (ap.disableCamera != disabled) {
5591 ap.disableCamera = disabled;
5592 saveSettingsLocked(userHandle);
5595 // Tell the user manager that the restrictions have changed.
5596 pushUserRestrictions(userHandle);
5600 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5604 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5605 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5608 private boolean getCameraDisabled(ComponentName who, int userHandle,
5609 boolean mergeDeviceOwnerRestriction) {
5613 synchronized (this) {
5615 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5616 return (admin != null) ? admin.disableCamera : false;
5618 // First, see if DO has set it. If so, it's device-wide.
5619 if (mergeDeviceOwnerRestriction) {
5620 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5621 if (deviceOwner != null && deviceOwner.disableCamera) {
5626 // Then check each device admin on the user.
5627 DevicePolicyData policy = getUserData(userHandle);
5628 // Determine whether or not the device camera is disabled for any active admins.
5629 final int N = policy.mAdminList.size();
5630 for (int i = 0; i < N; i++) {
5631 ActiveAdmin admin = policy.mAdminList.get(i);
5632 if (admin.disableCamera) {
5641 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5645 Preconditions.checkNotNull(who, "ComponentName is null");
5646 final int userHandle = mInjector.userHandleGetCallingUserId();
5647 if (isManagedProfile(userHandle)) {
5649 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5651 which = which & PROFILE_KEYGUARD_FEATURES;
5654 synchronized (this) {
5655 ActiveAdmin ap = getActiveAdminForCallerLocked(
5656 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5657 if (ap.disabledKeyguardFeatures != which) {
5658 ap.disabledKeyguardFeatures = which;
5659 saveSettingsLocked(userHandle);
5665 * Gets the disabled state for features in keyguard for the given admin,
5666 * or the aggregate of all active admins if who is null.
5669 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5673 enforceFullCrossUsersPermission(userHandle);
5674 final long ident = mInjector.binderClearCallingIdentity();
5676 synchronized (this) {
5678 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5679 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5682 final List<ActiveAdmin> admins;
5683 if (!parent && isManagedProfile(userHandle)) {
5684 // If we are being asked about a managed profile, just return keyguard features
5685 // disabled by admins in the profile.
5686 admins = getUserDataUnchecked(userHandle).mAdminList;
5688 // Otherwise return those set by admins in the user and its profiles.
5689 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5692 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5693 final int N = admins.size();
5694 for (int i = 0; i < N; i++) {
5695 ActiveAdmin admin = admins.get(i);
5696 int userId = admin.getUserHandle().getIdentifier();
5697 boolean isRequestedUser = !parent && (userId == userHandle);
5698 if (isRequestedUser || !isManagedProfile(userId)) {
5699 // If we are being asked explicitly about this user
5700 // return all disabled features even if its a managed profile.
5701 which |= admin.disabledKeyguardFeatures;
5703 // Otherwise a managed profile is only allowed to disable
5704 // some features on the parent user.
5705 which |= (admin.disabledKeyguardFeatures
5706 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5712 mInjector.binderRestoreCallingIdentity(ident);
5717 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5721 Preconditions.checkNotNull(who, "ComponentName is null");
5722 Preconditions.checkNotNull(packageList, "packageList is null");
5723 final int userHandle = UserHandle.getCallingUserId();
5724 synchronized (this) {
5725 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5726 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5727 admin.keepUninstalledPackages = packageList;
5728 saveSettingsLocked(userHandle);
5729 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5734 public List<String> getKeepUninstalledPackages(ComponentName who) {
5735 Preconditions.checkNotNull(who, "ComponentName is null");
5739 // TODO In split system user mode, allow apps on user 0 to query the list
5740 synchronized (this) {
5741 // Check if this is the device owner who is calling
5742 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5743 return getKeepUninstalledPackagesLocked();
5747 private List<String> getKeepUninstalledPackagesLocked() {
5748 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5749 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5753 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5758 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5759 throw new IllegalArgumentException("Invalid component " + admin
5760 + " for device owner");
5762 synchronized (this) {
5763 enforceCanSetDeviceOwnerLocked(admin, userId);
5764 if (getActiveAdminUncheckedLocked(admin, userId) == null
5765 || getUserData(userId).mRemovingAdmins.contains(admin)) {
5766 throw new IllegalArgumentException("Not active admin: " + admin);
5769 // Shutting down backup manager service permanently.
5770 long ident = mInjector.binderClearCallingIdentity();
5772 if (mInjector.getIBackupManager() != null) {
5773 mInjector.getIBackupManager()
5774 .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5776 } catch (RemoteException e) {
5777 throw new IllegalStateException("Failed deactivating backup service.", e);
5779 mInjector.binderRestoreCallingIdentity(ident);
5782 mOwners.setDeviceOwner(admin, ownerName, userId);
5783 mOwners.writeDeviceOwner();
5784 updateDeviceOwnerLocked();
5785 setDeviceOwnerSystemPropertyLocked();
5786 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5788 ident = mInjector.binderClearCallingIdentity();
5790 // TODO Send to system too?
5791 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5793 mInjector.binderRestoreCallingIdentity(ident);
5795 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
5800 public boolean isDeviceOwner(ComponentName who, int userId) {
5801 synchronized (this) {
5802 return mOwners.hasDeviceOwner()
5803 && mOwners.getDeviceOwnerUserId() == userId
5804 && mOwners.getDeviceOwnerComponent().equals(who);
5808 public boolean isProfileOwner(ComponentName who, int userId) {
5809 final ComponentName profileOwner = getProfileOwner(userId);
5810 return who != null && who.equals(profileOwner);
5814 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5818 if (!callingUserOnly) {
5819 enforceManageUsers();
5821 synchronized (this) {
5822 if (!mOwners.hasDeviceOwner()) {
5825 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
5826 mOwners.getDeviceOwnerUserId()) {
5829 return mOwners.getDeviceOwnerComponent();
5834 public int getDeviceOwnerUserId() {
5836 return UserHandle.USER_NULL;
5838 enforceManageUsers();
5839 synchronized (this) {
5840 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
5845 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
5849 public String getDeviceOwnerName() {
5853 enforceManageUsers();
5854 synchronized (this) {
5855 if (!mOwners.hasDeviceOwner()) {
5858 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
5859 // Should setDeviceOwner/ProfileOwner still take a name?
5860 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
5861 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
5865 // Returns the active device owner or null if there is no device owner.
5867 ActiveAdmin getDeviceOwnerAdminLocked() {
5868 ComponentName component = mOwners.getDeviceOwnerComponent();
5869 if (component == null) {
5873 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
5874 final int n = policy.mAdminList.size();
5875 for (int i = 0; i < n; i++) {
5876 ActiveAdmin admin = policy.mAdminList.get(i);
5877 if (component.equals(admin.info.getComponent())) {
5881 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
5886 public void clearDeviceOwner(String packageName) {
5887 Preconditions.checkNotNull(packageName, "packageName is null");
5888 final int callingUid = mInjector.binderGetCallingUid();
5890 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
5891 UserHandle.getUserId(callingUid));
5892 if (uid != callingUid) {
5893 throw new SecurityException("Invalid packageName");
5895 } catch (NameNotFoundException e) {
5896 throw new SecurityException(e);
5898 synchronized (this) {
5899 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
5900 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
5901 if (!mOwners.hasDeviceOwner()
5902 || !deviceOwnerComponent.getPackageName().equals(packageName)
5903 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
5904 throw new SecurityException(
5905 "clearDeviceOwner can only be called by the device owner");
5907 enforceUserUnlocked(deviceOwnerUserId);
5909 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
5910 long ident = mInjector.binderClearCallingIdentity();
5912 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
5913 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
5915 mInjector.binderRestoreCallingIdentity(ident);
5917 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
5921 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
5922 if (admin != null) {
5923 admin.disableCamera = false;
5924 admin.userRestrictions = null;
5925 admin.forceEphemeralUsers = false;
5926 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
5928 clearUserPoliciesLocked(userId);
5930 mOwners.clearDeviceOwner();
5931 mOwners.writeDeviceOwner();
5932 updateDeviceOwnerLocked();
5933 disableSecurityLoggingIfNotCompliant();
5935 if (mInjector.getIBackupManager() != null) {
5936 // Reactivate backup service.
5937 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
5939 } catch (RemoteException e) {
5940 throw new IllegalStateException("Failed reactivating backup service.", e);
5945 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
5950 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
5951 throw new IllegalArgumentException("Component " + who
5952 + " not installed for userId:" + userHandle);
5954 synchronized (this) {
5955 enforceCanSetProfileOwnerLocked(who, userHandle);
5957 if (getActiveAdminUncheckedLocked(who, userHandle) == null
5958 || getUserData(userHandle).mRemovingAdmins.contains(who)) {
5959 throw new IllegalArgumentException("Not active admin: " + who);
5962 mOwners.setProfileOwner(who, ownerName, userHandle);
5963 mOwners.writeProfileOwner(userHandle);
5964 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
5970 public void clearProfileOwner(ComponentName who) {
5974 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
5975 final int userId = callingUser.getIdentifier();
5976 enforceNotManagedProfile(userId, "clear profile owner");
5977 enforceUserUnlocked(userId);
5978 // Check if this is the profile owner who is calling
5979 final ActiveAdmin admin =
5980 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5981 synchronized (this) {
5982 final long ident = mInjector.binderClearCallingIdentity();
5984 clearProfileOwnerLocked(admin, userId);
5985 removeActiveAdminLocked(who, userId);
5987 mInjector.binderRestoreCallingIdentity(ident);
5989 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
5993 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
5994 if (admin != null) {
5995 admin.disableCamera = false;
5996 admin.userRestrictions = null;
5998 clearUserPoliciesLocked(userId);
5999 mOwners.removeProfileOwner(userId);
6000 mOwners.writeProfileOwner(userId);
6004 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6005 Preconditions.checkNotNull(who, "ComponentName is null");
6010 synchronized (this) {
6011 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6012 long token = mInjector.binderClearCallingIdentity();
6014 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6016 mInjector.binderRestoreCallingIdentity(token);
6022 public CharSequence getDeviceOwnerLockScreenInfo() {
6023 return mLockPatternUtils.getDeviceOwnerInfo();
6026 private void clearUserPoliciesLocked(int userId) {
6027 // Reset some of the user-specific policies
6028 DevicePolicyData policy = getUserData(userId);
6029 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6030 policy.mDelegatedCertInstallerPackage = null;
6031 policy.mApplicationRestrictionsManagingPackage = null;
6032 policy.mStatusBarDisabled = false;
6033 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6034 saveSettingsLocked(userId);
6037 mIPackageManager.updatePermissionFlagsForAllApps(
6038 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6039 0 /* flagValues */, userId);
6040 pushUserRestrictions(userId);
6041 } catch (RemoteException re) {
6042 // Shouldn't happen.
6047 public boolean hasUserSetupCompleted() {
6048 return hasUserSetupCompleted(UserHandle.getCallingUserId());
6051 private boolean hasUserSetupCompleted(int userHandle) {
6055 return getUserData(userHandle).mUserSetupComplete;
6059 public int getUserProvisioningState() {
6061 return DevicePolicyManager.STATE_USER_UNMANAGED;
6063 int userHandle = mInjector.userHandleGetCallingUserId();
6064 return getUserProvisioningState(userHandle);
6067 private int getUserProvisioningState(int userHandle) {
6068 return getUserData(userHandle).mUserProvisioningState;
6072 public void setUserProvisioningState(int newState, int userHandle) {
6077 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6078 && getManagedUserId(userHandle) == -1) {
6079 // No managed device, user or profile, so setting provisioning state makes no sense.
6080 throw new IllegalStateException("Not allowed to change provisioning state unless a "
6081 + "device or profile owner is set.");
6084 synchronized (this) {
6085 boolean transitionCheckNeeded = true;
6087 // Calling identity/permission checks.
6088 final int callingUid = mInjector.binderGetCallingUid();
6089 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6090 // ADB shell can only move directly from un-managed to finalized as part of directly
6091 // setting profile-owner or device-owner.
6092 if (getUserProvisioningState(userHandle) !=
6093 DevicePolicyManager.STATE_USER_UNMANAGED
6094 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6095 throw new IllegalStateException("Not allowed to change provisioning state "
6096 + "unless current provisioning state is unmanaged, and new state is "
6099 transitionCheckNeeded = false;
6101 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6102 enforceCanManageProfileAndDeviceOwners();
6105 final DevicePolicyData policyData = getUserData(userHandle);
6106 if (transitionCheckNeeded) {
6107 // Optional state transition check for non-ADB case.
6108 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6110 policyData.mUserProvisioningState = newState;
6111 saveSettingsLocked(userHandle);
6115 private void checkUserProvisioningStateTransition(int currentState, int newState) {
6116 // Valid transitions for normal use-cases.
6117 switch (currentState) {
6118 case DevicePolicyManager.STATE_USER_UNMANAGED:
6119 // Can move to any state from unmanaged (except itself as an edge case)..
6120 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6124 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6125 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6126 // Can only move to finalized from these states.
6127 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6131 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6132 // Current user has a managed-profile, but current user is not managed, so
6133 // rather than moving to finalized state, go back to unmanaged once
6134 // profile provisioning is complete.
6135 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6139 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6140 // Cannot transition out of finalized.
6144 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6145 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6146 + "from state [" + currentState + "]");
6150 public void setProfileEnabled(ComponentName who) {
6154 Preconditions.checkNotNull(who, "ComponentName is null");
6155 synchronized (this) {
6156 // Check if this is the profile owner who is calling
6157 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6158 final int userId = UserHandle.getCallingUserId();
6159 enforceManagedProfile(userId, "enable the profile");
6161 long id = mInjector.binderClearCallingIdentity();
6163 mUserManager.setUserEnabled(userId);
6164 UserInfo parent = mUserManager.getProfileParent(userId);
6165 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6166 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6167 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6168 Intent.FLAG_RECEIVER_FOREGROUND);
6169 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6171 mInjector.binderRestoreCallingIdentity(id);
6177 public void setProfileName(ComponentName who, String profileName) {
6178 Preconditions.checkNotNull(who, "ComponentName is null");
6179 int userId = UserHandle.getCallingUserId();
6180 // Check if this is the profile owner (includes device owner).
6181 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6183 long id = mInjector.binderClearCallingIdentity();
6185 mUserManager.setUserName(userId, profileName);
6187 mInjector.binderRestoreCallingIdentity(id);
6192 public ComponentName getProfileOwner(int userHandle) {
6197 synchronized (this) {
6198 return mOwners.getProfileOwnerComponent(userHandle);
6202 // Returns the active profile owner for this user or null if the current user has no
6205 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6206 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6207 if (profileOwner == null) {
6210 DevicePolicyData policy = getUserData(userHandle);
6211 final int n = policy.mAdminList.size();
6212 for (int i = 0; i < n; i++) {
6213 ActiveAdmin admin = policy.mAdminList.get(i);
6214 if (profileOwner.equals(admin.info.getComponent())) {
6222 public String getProfileOwnerName(int userHandle) {
6226 enforceManageUsers();
6227 ComponentName profileOwner = getProfileOwner(userHandle);
6228 if (profileOwner == null) {
6231 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6235 * Canonical name for a given package.
6237 private String getApplicationLabel(String packageName, int userHandle) {
6238 long token = mInjector.binderClearCallingIdentity();
6240 final Context userContext;
6242 UserHandle handle = new UserHandle(userHandle);
6243 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6244 } catch (PackageManager.NameNotFoundException nnfe) {
6245 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6248 ApplicationInfo appInfo = userContext.getApplicationInfo();
6249 CharSequence result = null;
6250 if (appInfo != null) {
6251 PackageManager pm = userContext.getPackageManager();
6252 result = pm.getApplicationLabel(appInfo);
6254 return result != null ? result.toString() : null;
6256 mInjector.binderRestoreCallingIdentity(token);
6261 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6263 * The profile owner can only be set before the user setup phase has completed,
6266 * - adb if there are no accounts. (But see {@link #hasIncompatibleAccountsLocked})
6268 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle) {
6269 UserInfo info = getUserInfo(userHandle);
6271 // User doesn't exist.
6272 throw new IllegalArgumentException(
6273 "Attempted to set profile owner for invalid userId: " + userHandle);
6275 if (info.isGuest()) {
6276 throw new IllegalStateException("Cannot set a profile owner on a guest");
6278 if (mOwners.hasProfileOwner(userHandle)) {
6279 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6280 + "is already set.");
6282 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6283 throw new IllegalStateException("Trying to set the profile owner, but the user "
6284 + "already has a device owner.");
6286 int callingUid = mInjector.binderGetCallingUid();
6287 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6288 if (hasUserSetupCompleted(userHandle)
6289 && hasIncompatibleAccountsLocked(userHandle, owner)) {
6290 throw new IllegalStateException("Not allowed to set the profile owner because "
6291 + "there are already some accounts on the profile");
6295 enforceCanManageProfileAndDeviceOwners();
6296 if (hasUserSetupCompleted(userHandle) && !isCallerWithSystemUid()) {
6297 throw new IllegalStateException("Cannot set the profile owner on a user which is "
6298 + "already set-up");
6303 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6306 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId) {
6307 int callingUid = mInjector.binderGetCallingUid();
6308 boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6310 enforceCanManageProfileAndDeviceOwners();
6313 final int code = checkSetDeviceOwnerPreConditionLocked(owner, userId, isAdb);
6317 case CODE_HAS_DEVICE_OWNER:
6318 throw new IllegalStateException(
6319 "Trying to set the device owner, but device owner is already set.");
6320 case CODE_USER_HAS_PROFILE_OWNER:
6321 throw new IllegalStateException("Trying to set the device owner, but the user "
6322 + "already has a profile owner.");
6323 case CODE_USER_NOT_RUNNING:
6324 throw new IllegalStateException("User not running: " + userId);
6325 case CODE_NOT_SYSTEM_USER:
6326 throw new IllegalStateException("User is not system user");
6327 case CODE_USER_SETUP_COMPLETED:
6328 throw new IllegalStateException(
6329 "Cannot set the device owner if the device is already set-up");
6330 case CODE_NONSYSTEM_USER_EXISTS:
6331 throw new IllegalStateException("Not allowed to set the device owner because there "
6332 + "are already several users on the device");
6333 case CODE_ACCOUNTS_NOT_EMPTY:
6334 throw new IllegalStateException("Not allowed to set the device owner because there "
6335 + "are already some accounts on the device");
6337 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6341 private void enforceUserUnlocked(int userId) {
6342 // Since we're doing this operation on behalf of an app, we only
6343 // want to use the actual "unlocked" state.
6344 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6345 "User must be running and unlocked");
6348 private void enforceManageUsers() {
6349 final int callingUid = mInjector.binderGetCallingUid();
6350 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6351 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6355 private void enforceFullCrossUsersPermission(int userHandle) {
6356 enforceSystemUserOrPermission(userHandle,
6357 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6360 private void enforceCrossUsersPermission(int userHandle) {
6361 enforceSystemUserOrPermission(userHandle,
6362 android.Manifest.permission.INTERACT_ACROSS_USERS);
6365 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6366 if (userHandle < 0) {
6367 throw new IllegalArgumentException("Invalid userId " + userHandle);
6369 final int callingUid = mInjector.binderGetCallingUid();
6370 if (userHandle == UserHandle.getUserId(callingUid)) {
6373 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6374 mContext.enforceCallingOrSelfPermission(permission,
6375 "Must be system or have " + permission + " permission");
6379 private void enforceManagedProfile(int userHandle, String message) {
6380 if(!isManagedProfile(userHandle)) {
6381 throw new SecurityException("You can not " + message + " outside a managed profile.");
6385 private void enforceNotManagedProfile(int userHandle, String message) {
6386 if(isManagedProfile(userHandle)) {
6387 throw new SecurityException("You can not " + message + " for a managed profile.");
6391 private void ensureCallerPackage(@Nullable String packageName) {
6392 if (packageName == null) {
6393 Preconditions.checkState(isCallerWithSystemUid(),
6394 "Only caller can omit package name");
6396 final int callingUid = mInjector.binderGetCallingUid();
6397 final int userId = mInjector.userHandleGetCallingUserId();
6399 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6400 packageName, 0, userId);
6401 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6402 } catch (RemoteException e) {
6408 private boolean isCallerWithSystemUid() {
6409 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6412 private int getProfileParentId(int userHandle) {
6413 final long ident = mInjector.binderClearCallingIdentity();
6415 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6416 return parentUser != null ? parentUser.id : userHandle;
6418 mInjector.binderRestoreCallingIdentity(ident);
6422 private int getCredentialOwner(int userHandle, boolean parent) {
6423 final long ident = mInjector.binderClearCallingIdentity();
6426 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6427 if (parentProfile != null) {
6428 userHandle = parentProfile.id;
6431 return mUserManager.getCredentialOwnerProfile(userHandle);
6433 mInjector.binderRestoreCallingIdentity(ident);
6437 private boolean isManagedProfile(int userHandle) {
6438 return getUserInfo(userHandle).isManagedProfile();
6441 private void enableIfNecessary(String packageName, int userId) {
6443 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6444 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6446 if (ai.enabledSetting
6447 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6448 mIPackageManager.setApplicationEnabledSetting(packageName,
6449 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6450 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6452 } catch (RemoteException e) {
6457 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6458 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6459 != PackageManager.PERMISSION_GRANTED) {
6461 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6462 + mInjector.binderGetCallingPid()
6463 + ", uid=" + mInjector.binderGetCallingUid());
6467 synchronized (this) {
6468 pw.println("Current Device Policy Manager state:");
6469 mOwners.dump(" ", pw);
6470 int userCount = mUserData.size();
6471 for (int u = 0; u < userCount; u++) {
6472 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6474 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6475 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6476 final int N = policy.mAdminList.size();
6477 for (int i=0; i<N; i++) {
6478 ActiveAdmin ap = policy.mAdminList.get(i);
6480 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6485 if (!policy.mRemovingAdmins.isEmpty()) {
6486 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6487 + policy.mRemovingAdmins);
6491 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6494 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6498 private String getEncryptionStatusName(int encryptionStatus) {
6499 switch (encryptionStatus) {
6500 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6502 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6503 return "block default key";
6504 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6506 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6508 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6509 return "unsupported";
6510 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6511 return "activating";
6518 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6519 ComponentName activity) {
6520 Preconditions.checkNotNull(who, "ComponentName is null");
6521 final int userHandle = UserHandle.getCallingUserId();
6522 synchronized (this) {
6523 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6525 long id = mInjector.binderClearCallingIdentity();
6527 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6528 } catch (RemoteException re) {
6531 mInjector.binderRestoreCallingIdentity(id);
6537 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6538 Preconditions.checkNotNull(who, "ComponentName is null");
6539 final int userHandle = UserHandle.getCallingUserId();
6540 synchronized (this) {
6541 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6543 long id = mInjector.binderClearCallingIdentity();
6545 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6546 } catch (RemoteException re) {
6549 mInjector.binderRestoreCallingIdentity(id);
6555 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6556 String packageName) {
6557 Preconditions.checkNotNull(admin, "ComponentName is null");
6559 final int userHandle = mInjector.userHandleGetCallingUserId();
6560 synchronized (this) {
6561 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6562 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6565 DevicePolicyData policy = getUserData(userHandle);
6566 policy.mApplicationRestrictionsManagingPackage = packageName;
6567 saveSettingsLocked(userHandle);
6573 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6574 Preconditions.checkNotNull(admin, "ComponentName is null");
6576 final int userHandle = mInjector.userHandleGetCallingUserId();
6577 synchronized (this) {
6578 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6579 DevicePolicyData policy = getUserData(userHandle);
6580 return policy.mApplicationRestrictionsManagingPackage;
6585 public boolean isCallerApplicationRestrictionsManagingPackage() {
6586 final int callingUid = mInjector.binderGetCallingUid();
6587 final int userHandle = UserHandle.getUserId(callingUid);
6588 synchronized (this) {
6589 final DevicePolicyData policy = getUserData(userHandle);
6590 if (policy.mApplicationRestrictionsManagingPackage == null) {
6595 int uid = mContext.getPackageManager().getPackageUidAsUser(
6596 policy.mApplicationRestrictionsManagingPackage, userHandle);
6597 return uid == callingUid;
6598 } catch (NameNotFoundException e) {
6604 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6606 synchronized (this) {
6607 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6609 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6610 throw new SecurityException(
6611 "No admin component given, and caller cannot manage application restrictions "
6612 + "for other apps.");
6617 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6618 enforceCanManageApplicationRestrictions(who);
6620 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6621 final long id = mInjector.binderClearCallingIdentity();
6623 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6625 mInjector.binderRestoreCallingIdentity(id);
6630 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6631 PersistableBundle args, boolean parent) {
6635 Preconditions.checkNotNull(admin, "admin is null");
6636 Preconditions.checkNotNull(agent, "agent is null");
6637 final int userHandle = UserHandle.getCallingUserId();
6638 synchronized (this) {
6639 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6640 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6641 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6642 saveSettingsLocked(userHandle);
6647 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6648 ComponentName agent, int userHandle, boolean parent) {
6652 Preconditions.checkNotNull(agent, "agent null");
6653 enforceFullCrossUsersPermission(userHandle);
6655 synchronized (this) {
6656 final String componentName = agent.flattenToString();
6657 if (admin != null) {
6658 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6659 if (ap == null) return null;
6660 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6661 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6662 List<PersistableBundle> result = new ArrayList<>();
6663 result.add(trustAgentInfo.options);
6667 // Return strictest policy for this user and profiles that are visible from this user.
6668 List<PersistableBundle> result = null;
6669 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6670 // of the options. If any admin doesn't have options, discard options for the rest
6672 List<ActiveAdmin> admins =
6673 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6674 boolean allAdminsHaveOptions = true;
6675 final int N = admins.size();
6676 for (int i = 0; i < N; i++) {
6677 final ActiveAdmin active = admins.get(i);
6679 final boolean disablesTrust = (active.disabledKeyguardFeatures
6680 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6681 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6682 if (info != null && info.options != null && !info.options.isEmpty()) {
6683 if (disablesTrust) {
6684 if (result == null) {
6685 result = new ArrayList<>();
6687 result.add(info.options);
6689 Log.w(LOG_TAG, "Ignoring admin " + active.info
6690 + " because it has trust options but doesn't declare "
6691 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6693 } else if (disablesTrust) {
6694 allAdminsHaveOptions = false;
6698 return allAdminsHaveOptions ? result : null;
6703 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6704 Preconditions.checkNotNull(who, "ComponentName is null");
6705 synchronized (this) {
6706 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6708 int userHandle = UserHandle.getCallingUserId();
6709 DevicePolicyData userData = getUserData(userHandle);
6710 userData.mRestrictionsProvider = permissionProvider;
6711 saveSettingsLocked(userHandle);
6716 public ComponentName getRestrictionsProvider(int userHandle) {
6717 synchronized (this) {
6718 if (!isCallerWithSystemUid()) {
6719 throw new SecurityException("Only the system can query the permission provider");
6721 DevicePolicyData userData = getUserData(userHandle);
6722 return userData != null ? userData.mRestrictionsProvider : null;
6727 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6728 Preconditions.checkNotNull(who, "ComponentName is null");
6729 int callingUserId = UserHandle.getCallingUserId();
6730 synchronized (this) {
6731 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6733 long id = mInjector.binderClearCallingIdentity();
6735 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6736 if (parent == null) {
6737 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6741 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6742 mIPackageManager.addCrossProfileIntentFilter(
6743 filter, who.getPackageName(), callingUserId, parent.id, 0);
6745 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6746 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6747 parent.id, callingUserId, 0);
6749 } catch (RemoteException re) {
6752 mInjector.binderRestoreCallingIdentity(id);
6758 public void clearCrossProfileIntentFilters(ComponentName who) {
6759 Preconditions.checkNotNull(who, "ComponentName is null");
6760 int callingUserId = UserHandle.getCallingUserId();
6761 synchronized (this) {
6762 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6763 long id = mInjector.binderClearCallingIdentity();
6765 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6766 if (parent == null) {
6767 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6771 // Removing those that go from the managed profile to the parent.
6772 mIPackageManager.clearCrossProfileIntentFilters(
6773 callingUserId, who.getPackageName());
6774 // And those that go from the parent to the managed profile.
6775 // If we want to support multiple managed profiles, we will have to only remove
6776 // those that have callingUserId as their target.
6777 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6778 } catch (RemoteException re) {
6781 mInjector.binderRestoreCallingIdentity(id);
6787 * @return true if all packages in enabledPackages are either in the list
6788 * permittedList or are a system app.
6790 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6791 List<String> permittedList, int userIdToCheck) {
6792 long id = mInjector.binderClearCallingIdentity();
6794 // If we have an enabled packages list for a managed profile the packages
6795 // we should check are installed for the parent user.
6796 UserInfo user = getUserInfo(userIdToCheck);
6797 if (user.isManagedProfile()) {
6798 userIdToCheck = user.profileGroupId;
6801 for (String enabledPackage : enabledPackages) {
6802 boolean systemService = false;
6804 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
6805 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
6806 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6807 } catch (RemoteException e) {
6808 Log.i(LOG_TAG, "Can't talk to package managed", e);
6810 if (!systemService && !permittedList.contains(enabledPackage)) {
6815 mInjector.binderRestoreCallingIdentity(id);
6820 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
6821 // Not using AccessibilityManager.getInstance because that guesses
6822 // at the user you require based on callingUid and caches for a given
6824 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
6825 IAccessibilityManager service = iBinder == null
6826 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
6827 return new AccessibilityManager(mContext, service, userId);
6831 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
6835 Preconditions.checkNotNull(who, "ComponentName is null");
6837 if (packageList != null) {
6838 int userId = UserHandle.getCallingUserId();
6839 List<AccessibilityServiceInfo> enabledServices = null;
6840 long id = mInjector.binderClearCallingIdentity();
6842 UserInfo user = getUserInfo(userId);
6843 if (user.isManagedProfile()) {
6844 userId = user.profileGroupId;
6846 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
6847 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
6848 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
6850 mInjector.binderRestoreCallingIdentity(id);
6853 if (enabledServices != null) {
6854 List<String> enabledPackages = new ArrayList<String>();
6855 for (AccessibilityServiceInfo service : enabledServices) {
6856 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
6858 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6860 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
6861 + "because it contains already enabled accesibility services.");
6867 synchronized (this) {
6868 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6869 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6870 admin.permittedAccessiblityServices = packageList;
6871 saveSettingsLocked(UserHandle.getCallingUserId());
6877 public List getPermittedAccessibilityServices(ComponentName who) {
6881 Preconditions.checkNotNull(who, "ComponentName is null");
6883 synchronized (this) {
6884 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6885 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6886 return admin.permittedAccessiblityServices;
6891 public List getPermittedAccessibilityServicesForUser(int userId) {
6895 synchronized (this) {
6896 List<String> result = null;
6897 // If we have multiple profiles we return the intersection of the
6898 // permitted lists. This can happen in cases where we have a device
6899 // and profile owner.
6900 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
6901 for (int profileId : profileIds) {
6902 // Just loop though all admins, only device or profiles
6903 // owners can have permitted lists set.
6904 DevicePolicyData policy = getUserDataUnchecked(profileId);
6905 final int N = policy.mAdminList.size();
6906 for (int j = 0; j < N; j++) {
6907 ActiveAdmin admin = policy.mAdminList.get(j);
6908 List<String> fromAdmin = admin.permittedAccessiblityServices;
6909 if (fromAdmin != null) {
6910 if (result == null) {
6911 result = new ArrayList<>(fromAdmin);
6913 result.retainAll(fromAdmin);
6919 // If we have a permitted list add all system accessibility services.
6920 if (result != null) {
6921 long id = mInjector.binderClearCallingIdentity();
6923 UserInfo user = getUserInfo(userId);
6924 if (user.isManagedProfile()) {
6925 userId = user.profileGroupId;
6927 AccessibilityManager accessibilityManager =
6928 getAccessibilityManagerForUser(userId);
6929 List<AccessibilityServiceInfo> installedServices =
6930 accessibilityManager.getInstalledAccessibilityServiceList();
6932 if (installedServices != null) {
6933 for (AccessibilityServiceInfo service : installedServices) {
6934 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
6935 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
6936 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6937 result.add(serviceInfo.packageName);
6942 mInjector.binderRestoreCallingIdentity(id);
6951 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
6956 Preconditions.checkNotNull(who, "ComponentName is null");
6957 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
6958 if (!isCallerWithSystemUid()){
6959 throw new SecurityException(
6960 "Only the system can query if an accessibility service is disabled by admin");
6962 synchronized (this) {
6963 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6964 if (admin == null) {
6967 if (admin.permittedAccessiblityServices == null) {
6970 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
6971 admin.permittedAccessiblityServices, userHandle);
6975 private boolean checkCallerIsCurrentUserOrProfile() {
6976 int callingUserId = UserHandle.getCallingUserId();
6977 long token = mInjector.binderClearCallingIdentity();
6979 UserInfo currentUser;
6980 UserInfo callingUser = getUserInfo(callingUserId);
6982 currentUser = mInjector.getIActivityManager().getCurrentUser();
6983 } catch (RemoteException e) {
6984 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
6988 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
6989 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
6990 + "of a user that isn't the foreground user.");
6993 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
6994 Slog.e(LOG_TAG, "Cannot set permitted input methods "
6995 + "of a user that isn't the foreground user.");
6999 mInjector.binderRestoreCallingIdentity(token);
7005 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7009 Preconditions.checkNotNull(who, "ComponentName is null");
7011 // TODO When InputMethodManager supports per user calls remove
7012 // this restriction.
7013 if (!checkCallerIsCurrentUserOrProfile()) {
7017 if (packageList != null) {
7018 // InputMethodManager fetches input methods for current user.
7019 // So this can only be set when calling user is the current user
7020 // or parent is current user in case of managed profiles.
7021 InputMethodManager inputMethodManager =
7022 mContext.getSystemService(InputMethodManager.class);
7023 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7025 if (enabledImes != null) {
7026 List<String> enabledPackages = new ArrayList<String>();
7027 for (InputMethodInfo ime : enabledImes) {
7028 enabledPackages.add(ime.getPackageName());
7030 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7031 mInjector.binderGetCallingUserHandle().getIdentifier())) {
7032 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7033 + "because it contains already enabled input method.");
7039 synchronized (this) {
7040 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7041 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7042 admin.permittedInputMethods = packageList;
7043 saveSettingsLocked(UserHandle.getCallingUserId());
7049 public List getPermittedInputMethods(ComponentName who) {
7053 Preconditions.checkNotNull(who, "ComponentName is null");
7055 synchronized (this) {
7056 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7057 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7058 return admin.permittedInputMethods;
7063 public List getPermittedInputMethodsForCurrentUser() {
7064 UserInfo currentUser;
7066 currentUser = mInjector.getIActivityManager().getCurrentUser();
7067 } catch (RemoteException e) {
7068 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7069 // Activity managed is dead, just allow all IMEs
7073 int userId = currentUser.id;
7074 synchronized (this) {
7075 List<String> result = null;
7076 // If we have multiple profiles we return the intersection of the
7077 // permitted lists. This can happen in cases where we have a device
7078 // and profile owner.
7079 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7080 for (int profileId : profileIds) {
7081 // Just loop though all admins, only device or profiles
7082 // owners can have permitted lists set.
7083 DevicePolicyData policy = getUserDataUnchecked(profileId);
7084 final int N = policy.mAdminList.size();
7085 for (int j = 0; j < N; j++) {
7086 ActiveAdmin admin = policy.mAdminList.get(j);
7087 List<String> fromAdmin = admin.permittedInputMethods;
7088 if (fromAdmin != null) {
7089 if (result == null) {
7090 result = new ArrayList<String>(fromAdmin);
7092 result.retainAll(fromAdmin);
7098 // If we have a permitted list add all system input methods.
7099 if (result != null) {
7100 InputMethodManager inputMethodManager =
7101 mContext.getSystemService(InputMethodManager.class);
7102 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7103 long id = mInjector.binderClearCallingIdentity();
7106 for (InputMethodInfo ime : imes) {
7107 ServiceInfo serviceInfo = ime.getServiceInfo();
7108 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7109 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7110 result.add(serviceInfo.packageName);
7115 mInjector.binderRestoreCallingIdentity(id);
7123 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7128 Preconditions.checkNotNull(who, "ComponentName is null");
7129 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7130 if (!isCallerWithSystemUid()) {
7131 throw new SecurityException(
7132 "Only the system can query if an input method is disabled by admin");
7134 synchronized (this) {
7135 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7136 if (admin == null) {
7139 if (admin.permittedInputMethods == null) {
7142 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7143 admin.permittedInputMethods, userHandle);
7147 private void sendAdminEnabledBroadcastLocked(int userHandle) {
7148 DevicePolicyData policyData = getUserData(userHandle);
7149 if (policyData.mAdminBroadcastPending) {
7150 // Send the initialization data to profile owner and delete the data
7151 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7152 if (admin != null) {
7153 PersistableBundle initBundle = policyData.mInitBundle;
7154 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7155 initBundle == null ? null : new Bundle(initBundle), null);
7157 policyData.mInitBundle = null;
7158 policyData.mAdminBroadcastPending = false;
7159 saveSettingsLocked(userHandle);
7164 public UserHandle createAndManageUser(ComponentName admin, String name,
7165 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7166 Preconditions.checkNotNull(admin, "admin is null");
7167 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7168 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7169 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7170 + admin + " are not in the same package");
7172 // Only allow the system user to use this method
7173 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7174 throw new SecurityException("createAndManageUser was called from non-system user");
7176 if (!mInjector.userManagerIsSplitSystemUser()
7177 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7178 throw new IllegalArgumentException(
7179 "Ephemeral users are only supported on systems with a split system user.");
7182 UserHandle user = null;
7183 synchronized (this) {
7184 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7186 final long id = mInjector.binderClearCallingIdentity();
7188 int userInfoFlags = 0;
7189 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7190 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7192 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7194 if (userInfo != null) {
7195 user = userInfo.getUserHandle();
7198 mInjector.binderRestoreCallingIdentity(id);
7205 final long id = mInjector.binderClearCallingIdentity();
7207 final String adminPkg = admin.getPackageName();
7209 final int userHandle = user.getIdentifier();
7211 // Install the profile owner if not present.
7212 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7213 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7215 } catch (RemoteException e) {
7216 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7217 + "removing created user", e);
7218 mUserManager.removeUser(user.getIdentifier());
7222 setActiveAdmin(profileOwner, true, userHandle);
7223 // User is not started yet, the broadcast by setActiveAdmin will not be received.
7224 // So we store adminExtras for broadcasting when the user starts for first time.
7225 synchronized(this) {
7226 DevicePolicyData policyData = getUserData(userHandle);
7227 policyData.mInitBundle = adminExtras;
7228 policyData.mAdminBroadcastPending = true;
7229 saveSettingsLocked(userHandle);
7231 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7232 setProfileOwner(profileOwner, ownerName, userHandle);
7234 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7235 Settings.Secure.putIntForUser(mContext.getContentResolver(),
7236 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7241 mInjector.binderRestoreCallingIdentity(id);
7246 public boolean removeUser(ComponentName who, UserHandle userHandle) {
7247 Preconditions.checkNotNull(who, "ComponentName is null");
7248 synchronized (this) {
7249 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7251 long id = mInjector.binderClearCallingIdentity();
7253 return mUserManager.removeUser(userHandle.getIdentifier());
7255 mInjector.binderRestoreCallingIdentity(id);
7261 public boolean switchUser(ComponentName who, UserHandle userHandle) {
7262 Preconditions.checkNotNull(who, "ComponentName is null");
7263 synchronized (this) {
7264 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7266 long id = mInjector.binderClearCallingIdentity();
7268 int userId = UserHandle.USER_SYSTEM;
7269 if (userHandle != null) {
7270 userId = userHandle.getIdentifier();
7272 return mInjector.getIActivityManager().switchUser(userId);
7273 } catch (RemoteException e) {
7274 Log.e(LOG_TAG, "Couldn't switch user", e);
7277 mInjector.binderRestoreCallingIdentity(id);
7283 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7284 enforceCanManageApplicationRestrictions(who);
7286 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7287 final long id = mInjector.binderClearCallingIdentity();
7289 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7290 // if no restrictions were saved, mUserManager.getApplicationRestrictions
7291 // returns null, but DPM method should return an empty Bundle as per JavaDoc
7292 return bundle != null ? bundle : Bundle.EMPTY;
7294 mInjector.binderRestoreCallingIdentity(id);
7299 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7300 boolean suspended) {
7301 Preconditions.checkNotNull(who, "ComponentName is null");
7302 int callingUserId = UserHandle.getCallingUserId();
7303 synchronized (this) {
7304 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7306 long id = mInjector.binderClearCallingIdentity();
7308 return mIPackageManager.setPackagesSuspendedAsUser(
7309 packageNames, suspended, callingUserId);
7310 } catch (RemoteException re) {
7311 // Shouldn't happen.
7312 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7314 mInjector.binderRestoreCallingIdentity(id);
7316 return packageNames;
7321 public boolean isPackageSuspended(ComponentName who, String packageName) {
7322 Preconditions.checkNotNull(who, "ComponentName is null");
7323 int callingUserId = UserHandle.getCallingUserId();
7324 synchronized (this) {
7325 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7327 long id = mInjector.binderClearCallingIdentity();
7329 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7330 } catch (RemoteException re) {
7331 // Shouldn't happen.
7332 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7334 mInjector.binderRestoreCallingIdentity(id);
7341 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7342 Preconditions.checkNotNull(who, "ComponentName is null");
7343 if (!UserRestrictionsUtils.isValidRestriction(key)) {
7347 final int userHandle = mInjector.userHandleGetCallingUserId();
7348 synchronized (this) {
7349 ActiveAdmin activeAdmin =
7350 getActiveAdminForCallerLocked(who,
7351 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7352 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7353 if (isDeviceOwner) {
7354 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7355 throw new SecurityException("Device owner cannot set user restriction " + key);
7357 } else { // profile owner
7358 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7359 throw new SecurityException("Profile owner cannot set user restriction " + key);
7363 // Save the restriction to ActiveAdmin.
7364 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7365 saveSettingsLocked(userHandle);
7367 pushUserRestrictions(userHandle);
7369 sendChangedNotification(userHandle);
7373 private void pushUserRestrictions(int userId) {
7374 synchronized (this) {
7375 final Bundle global;
7376 final Bundle local = new Bundle();
7377 if (mOwners.isDeviceOwnerUserId(userId)) {
7378 global = new Bundle();
7380 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7381 if (deviceOwner == null) {
7382 return; // Shouldn't happen.
7385 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7387 // DO can disable camera globally.
7388 if (deviceOwner.disableCamera) {
7389 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7394 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7395 if (profileOwner != null) {
7396 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7399 // Also merge in *local* camera restriction.
7400 if (getCameraDisabled(/* who= */ null,
7401 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7402 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7404 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7409 public Bundle getUserRestrictions(ComponentName who) {
7413 Preconditions.checkNotNull(who, "ComponentName is null");
7414 synchronized (this) {
7415 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7416 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7417 return activeAdmin.userRestrictions;
7422 public boolean setApplicationHidden(ComponentName who, String packageName,
7424 Preconditions.checkNotNull(who, "ComponentName is null");
7425 int callingUserId = UserHandle.getCallingUserId();
7426 synchronized (this) {
7427 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7429 long id = mInjector.binderClearCallingIdentity();
7431 return mIPackageManager.setApplicationHiddenSettingAsUser(
7432 packageName, hidden, callingUserId);
7433 } catch (RemoteException re) {
7435 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7437 mInjector.binderRestoreCallingIdentity(id);
7444 public boolean isApplicationHidden(ComponentName who, String packageName) {
7445 Preconditions.checkNotNull(who, "ComponentName is null");
7446 int callingUserId = UserHandle.getCallingUserId();
7447 synchronized (this) {
7448 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7450 long id = mInjector.binderClearCallingIdentity();
7452 return mIPackageManager.getApplicationHiddenSettingAsUser(
7453 packageName, callingUserId);
7454 } catch (RemoteException re) {
7456 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7458 mInjector.binderRestoreCallingIdentity(id);
7465 public void enableSystemApp(ComponentName who, String packageName) {
7466 Preconditions.checkNotNull(who, "ComponentName is null");
7467 synchronized (this) {
7468 // This API can only be called by an active device admin,
7469 // so try to retrieve it to check that the caller is one.
7470 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7472 int userId = UserHandle.getCallingUserId();
7473 long id = mInjector.binderClearCallingIdentity();
7477 Slog.v(LOG_TAG, "installing " + packageName + " for "
7481 int parentUserId = getProfileParentId(userId);
7482 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7483 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7487 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7489 } catch (RemoteException re) {
7491 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7493 mInjector.binderRestoreCallingIdentity(id);
7499 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7500 Preconditions.checkNotNull(who, "ComponentName is null");
7501 synchronized (this) {
7502 // This API can only be called by an active device admin,
7503 // so try to retrieve it to check that the caller is one.
7504 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7506 int userId = UserHandle.getCallingUserId();
7507 long id = mInjector.binderClearCallingIdentity();
7510 int parentUserId = getProfileParentId(userId);
7511 List<ResolveInfo> activitiesToEnable = mIPackageManager
7512 .queryIntentActivities(intent,
7513 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7514 PackageManager.MATCH_DIRECT_BOOT_AWARE
7515 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7520 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7522 int numberOfAppsInstalled = 0;
7523 if (activitiesToEnable != null) {
7524 for (ResolveInfo info : activitiesToEnable) {
7525 if (info.activityInfo != null) {
7526 String packageName = info.activityInfo.packageName;
7527 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7528 numberOfAppsInstalled++;
7529 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7531 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7537 return numberOfAppsInstalled;
7538 } catch (RemoteException e) {
7540 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7543 mInjector.binderRestoreCallingIdentity(id);
7548 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7549 throws RemoteException {
7550 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7552 if (appInfo == null) {
7553 throw new IllegalArgumentException("The application " + packageName +
7554 " is not present on this device");
7556 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7560 public void setAccountManagementDisabled(ComponentName who, String accountType,
7565 Preconditions.checkNotNull(who, "ComponentName is null");
7566 synchronized (this) {
7567 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7568 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7570 ap.accountTypesWithManagementDisabled.add(accountType);
7572 ap.accountTypesWithManagementDisabled.remove(accountType);
7574 saveSettingsLocked(UserHandle.getCallingUserId());
7579 public String[] getAccountTypesWithManagementDisabled() {
7580 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7584 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7585 enforceFullCrossUsersPermission(userId);
7589 synchronized (this) {
7590 DevicePolicyData policy = getUserData(userId);
7591 final int N = policy.mAdminList.size();
7592 ArraySet<String> resultSet = new ArraySet<>();
7593 for (int i = 0; i < N; i++) {
7594 ActiveAdmin admin = policy.mAdminList.get(i);
7595 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7597 return resultSet.toArray(new String[resultSet.size()]);
7602 public void setUninstallBlocked(ComponentName who, String packageName,
7603 boolean uninstallBlocked) {
7604 Preconditions.checkNotNull(who, "ComponentName is null");
7605 final int userId = UserHandle.getCallingUserId();
7606 synchronized (this) {
7607 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7609 long id = mInjector.binderClearCallingIdentity();
7611 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7612 } catch (RemoteException re) {
7613 // Shouldn't happen.
7614 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7616 mInjector.binderRestoreCallingIdentity(id);
7622 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7623 // This function should return true if and only if the package is blocked by
7624 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7625 // when the package is a system app, or when it is an active device admin.
7626 final int userId = UserHandle.getCallingUserId();
7628 synchronized (this) {
7630 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7633 long id = mInjector.binderClearCallingIdentity();
7635 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7636 } catch (RemoteException re) {
7637 // Shouldn't happen.
7638 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7640 mInjector.binderRestoreCallingIdentity(id);
7647 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7651 Preconditions.checkNotNull(who, "ComponentName is null");
7652 synchronized (this) {
7653 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7654 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7655 if (admin.disableCallerId != disabled) {
7656 admin.disableCallerId = disabled;
7657 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7663 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7667 Preconditions.checkNotNull(who, "ComponentName is null");
7668 synchronized (this) {
7669 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7670 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7671 return admin.disableCallerId;
7676 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7677 enforceCrossUsersPermission(userId);
7678 synchronized (this) {
7679 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7680 return (admin != null) ? admin.disableCallerId : false;
7685 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7689 Preconditions.checkNotNull(who, "ComponentName is null");
7690 synchronized (this) {
7691 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7692 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7693 if (admin.disableContactsSearch != disabled) {
7694 admin.disableContactsSearch = disabled;
7695 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7701 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7705 Preconditions.checkNotNull(who, "ComponentName is null");
7706 synchronized (this) {
7707 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7708 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7709 return admin.disableContactsSearch;
7714 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7715 enforceCrossUsersPermission(userId);
7716 synchronized (this) {
7717 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7718 return (admin != null) ? admin.disableContactsSearch : false;
7723 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7724 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7725 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7726 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7727 final int callingUserId = UserHandle.getCallingUserId();
7729 final long ident = mInjector.binderClearCallingIdentity();
7731 synchronized (this) {
7732 final int managedUserId = getManagedUserId(callingUserId);
7733 if (managedUserId < 0) {
7736 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7739 "Cross-profile contacts access disabled for user " + managedUserId);
7743 ContactsInternal.startQuickContactWithErrorToastForUser(
7744 mContext, intent, new UserHandle(managedUserId));
7747 mInjector.binderRestoreCallingIdentity(ident);
7752 * @return true if cross-profile QuickContact is disabled
7754 private boolean isCrossProfileQuickContactDisabled(int userId) {
7755 return getCrossProfileCallerIdDisabledForUser(userId)
7756 && getCrossProfileContactsSearchDisabledForUser(userId);
7760 * @return the user ID of the managed user that is linked to the current user, if any.
7763 public int getManagedUserId(int callingUserId) {
7765 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7768 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7769 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7770 continue; // Caller user self, or not a managed profile. Skip.
7773 Log.v(LOG_TAG, "Managed user=" + ui.id);
7778 Log.v(LOG_TAG, "Managed user not found.");
7784 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7788 Preconditions.checkNotNull(who, "ComponentName is null");
7789 synchronized (this) {
7790 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7791 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7792 if (admin.disableBluetoothContactSharing != disabled) {
7793 admin.disableBluetoothContactSharing = disabled;
7794 saveSettingsLocked(UserHandle.getCallingUserId());
7800 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
7804 Preconditions.checkNotNull(who, "ComponentName is null");
7805 synchronized (this) {
7806 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7807 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7808 return admin.disableBluetoothContactSharing;
7813 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
7814 // TODO: Should there be a check to make sure this relationship is
7815 // within a profile group?
7816 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
7817 synchronized (this) {
7818 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7819 return (admin != null) ? admin.disableBluetoothContactSharing : false;
7824 * Sets which packages may enter lock task mode.
7826 * <p>This function can only be called by the device owner or alternatively by the profile owner
7827 * in case the user is affiliated.
7829 * @param packages The list of packages allowed to enter lock task mode.
7832 public void setLockTaskPackages(ComponentName who, String[] packages)
7833 throws SecurityException {
7834 Preconditions.checkNotNull(who, "ComponentName is null");
7835 synchronized (this) {
7836 ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
7837 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
7838 ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
7839 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
7840 if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
7841 int userHandle = mInjector.userHandleGetCallingUserId();
7842 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
7844 throw new SecurityException("Admin " + who +
7845 " is neither the device owner or affiliated user's profile owner.");
7850 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
7851 DevicePolicyData policy = getUserData(userHandle);
7852 policy.mLockTaskPackages = packages;
7854 // Store the settings persistently.
7855 saveSettingsLocked(userHandle);
7856 updateLockTaskPackagesLocked(packages, userHandle);
7860 * This function returns the list of components allowed to start the task lock mode.
7863 public String[] getLockTaskPackages(ComponentName who) {
7864 Preconditions.checkNotNull(who, "ComponentName is null");
7865 synchronized (this) {
7866 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7867 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
7868 final List<String> packages = getLockTaskPackagesLocked(userHandle);
7869 return packages.toArray(new String[packages.size()]);
7873 private List<String> getLockTaskPackagesLocked(int userHandle) {
7874 final DevicePolicyData policy = getUserData(userHandle);
7875 return policy.mLockTaskPackages;
7879 * This function lets the caller know whether the given package is allowed to start the
7881 * @param pkg The package to check
7884 public boolean isLockTaskPermitted(String pkg) {
7885 // Get current user's devicepolicy
7886 int uid = mInjector.binderGetCallingUid();
7887 int userHandle = UserHandle.getUserId(uid);
7888 DevicePolicyData policy = getUserData(userHandle);
7889 synchronized (this) {
7890 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
7891 String lockTaskPackage = policy.mLockTaskPackages.get(i);
7893 // If the given package equals one of the packages stored our list,
7894 // we allow this package to start lock task mode.
7895 if (lockTaskPackage.equals(pkg)) {
7904 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
7905 if (!isCallerWithSystemUid()) {
7906 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
7908 synchronized (this) {
7909 final DevicePolicyData policy = getUserData(userHandle);
7910 Bundle adminExtras = new Bundle();
7911 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
7912 for (ActiveAdmin admin : policy.mAdminList) {
7913 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
7914 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
7915 if (ownsDevice || ownsProfile) {
7917 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
7920 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
7928 public void setGlobalSetting(ComponentName who, String setting, String value) {
7929 Preconditions.checkNotNull(who, "ComponentName is null");
7931 synchronized (this) {
7932 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7934 // Some settings are no supported any more. However we do not want to throw a
7935 // SecurityException to avoid breaking apps.
7936 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
7937 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
7941 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
7942 throw new SecurityException(String.format(
7943 "Permission denial: device owners cannot update %1$s", setting));
7946 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
7947 // ignore if it contradicts an existing policy
7948 long timeMs = getMaximumTimeToLock(
7949 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
7950 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
7955 long id = mInjector.binderClearCallingIdentity();
7957 mInjector.settingsGlobalPutString(setting, value);
7959 mInjector.binderRestoreCallingIdentity(id);
7965 public void setSecureSetting(ComponentName who, String setting, String value) {
7966 Preconditions.checkNotNull(who, "ComponentName is null");
7967 int callingUserId = mInjector.userHandleGetCallingUserId();
7969 synchronized (this) {
7970 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7972 if (isDeviceOwner(who, callingUserId)) {
7973 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
7974 throw new SecurityException(String.format(
7975 "Permission denial: Device owners cannot update %1$s", setting));
7977 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
7978 throw new SecurityException(String.format(
7979 "Permission denial: Profile owners cannot update %1$s", setting));
7982 long id = mInjector.binderClearCallingIdentity();
7984 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
7986 mInjector.binderRestoreCallingIdentity(id);
7992 public void setMasterVolumeMuted(ComponentName who, boolean on) {
7993 Preconditions.checkNotNull(who, "ComponentName is null");
7994 synchronized (this) {
7995 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7996 setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
8001 public boolean isMasterVolumeMuted(ComponentName who) {
8002 Preconditions.checkNotNull(who, "ComponentName is null");
8003 synchronized (this) {
8004 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8006 AudioManager audioManager =
8007 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
8008 return audioManager.isMasterMute();
8013 public void setUserIcon(ComponentName who, Bitmap icon) {
8014 synchronized (this) {
8015 Preconditions.checkNotNull(who, "ComponentName is null");
8016 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8018 int userId = UserHandle.getCallingUserId();
8019 long id = mInjector.binderClearCallingIdentity();
8021 mUserManagerInternal.setUserIcon(userId, icon);
8023 mInjector.binderRestoreCallingIdentity(id);
8029 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8030 Preconditions.checkNotNull(who, "ComponentName is null");
8031 synchronized (this) {
8032 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8034 final int userId = UserHandle.getCallingUserId();
8036 long ident = mInjector.binderClearCallingIdentity();
8038 // disallow disabling the keyguard if a password is currently set
8039 if (disabled && mLockPatternUtils.isSecure(userId)) {
8042 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8044 mInjector.binderRestoreCallingIdentity(ident);
8050 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8051 int userId = UserHandle.getCallingUserId();
8052 synchronized (this) {
8053 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8054 DevicePolicyData policy = getUserData(userId);
8055 if (policy.mStatusBarDisabled != disabled) {
8056 if (!setStatusBarDisabledInternal(disabled, userId)) {
8059 policy.mStatusBarDisabled = disabled;
8060 saveSettingsLocked(userId);
8066 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8067 long ident = mInjector.binderClearCallingIdentity();
8069 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8070 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8071 if (statusBarService != null) {
8072 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8073 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8074 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8075 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8078 } catch (RemoteException e) {
8079 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8081 mInjector.binderRestoreCallingIdentity(ident);
8087 * We need to update the internal state of whether a user has completed setup once. After
8088 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
8089 * as we don't trust any apps that might try to reset it.
8091 * Unfortunately, we don't know which user's setup state was changed, so we write all of
8094 void updateUserSetupComplete() {
8095 List<UserInfo> users = mUserManager.getUsers(true);
8096 final int N = users.size();
8097 for (int i = 0; i < N; i++) {
8098 int userHandle = users.get(i).id;
8099 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8101 DevicePolicyData policy = getUserData(userHandle);
8102 if (!policy.mUserSetupComplete) {
8103 policy.mUserSetupComplete = true;
8104 synchronized (this) {
8105 saveSettingsLocked(userHandle);
8112 private class SetupContentObserver extends ContentObserver {
8114 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8115 Settings.Secure.USER_SETUP_COMPLETE);
8116 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8117 Settings.Global.DEVICE_PROVISIONED);
8119 public SetupContentObserver(Handler handler) {
8124 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8125 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8129 public void onChange(boolean selfChange, Uri uri) {
8130 if (mUserSetupComplete.equals(uri)) {
8131 updateUserSetupComplete();
8132 } else if (mDeviceProvisioned.equals(uri)) {
8133 synchronized (DevicePolicyManagerService.this) {
8134 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8135 // is delayed until device is marked as provisioned.
8136 setDeviceOwnerSystemPropertyLocked();
8143 final class LocalService extends DevicePolicyManagerInternal {
8144 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8147 public List<String> getCrossProfileWidgetProviders(int profileId) {
8148 synchronized (DevicePolicyManagerService.this) {
8149 if (mOwners == null) {
8150 return Collections.emptyList();
8152 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8153 if (ownerComponent == null) {
8154 return Collections.emptyList();
8157 DevicePolicyData policy = getUserDataUnchecked(profileId);
8158 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8160 if (admin == null || admin.crossProfileWidgetProviders == null
8161 || admin.crossProfileWidgetProviders.isEmpty()) {
8162 return Collections.emptyList();
8165 return admin.crossProfileWidgetProviders;
8170 public void addOnCrossProfileWidgetProvidersChangeListener(
8171 OnCrossProfileWidgetProvidersChangeListener listener) {
8172 synchronized (DevicePolicyManagerService.this) {
8173 if (mWidgetProviderListeners == null) {
8174 mWidgetProviderListeners = new ArrayList<>();
8176 if (!mWidgetProviderListeners.contains(listener)) {
8177 mWidgetProviderListeners.add(listener);
8183 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8184 synchronized(DevicePolicyManagerService.this) {
8185 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8189 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8190 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8191 synchronized (DevicePolicyManagerService.this) {
8192 listeners = new ArrayList<>(mWidgetProviderListeners);
8194 final int listenerCount = listeners.size();
8195 for (int i = 0; i < listenerCount; i++) {
8196 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8197 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8202 public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
8203 Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8204 intent.putExtra(Intent.EXTRA_USER_ID, userId);
8205 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8207 // This method is called from AM with its lock held, so don't take the DPMS lock.
8210 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8211 if (profileOwner != null) {
8212 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
8216 final Pair<Integer, ComponentName> deviceOwner =
8217 mOwners.getDeviceOwnerUserIdAndComponent();
8218 if (deviceOwner != null && deviceOwner.first == userId) {
8219 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
8223 // We're not specifying the device admin because there isn't one.
8229 * Returns true if specified admin is allowed to limit passwords and has a
8230 * {@code passwordQuality} of at least {@code minPasswordQuality}
8232 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8233 if (admin.passwordQuality < minPasswordQuality) {
8236 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8240 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8241 if (policy != null && !policy.isValid()) {
8242 throw new IllegalArgumentException("Invalid system update policy.");
8244 synchronized (this) {
8245 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8246 if (policy == null) {
8247 mOwners.clearSystemUpdatePolicy();
8249 mOwners.setSystemUpdatePolicy(policy);
8251 mOwners.writeDeviceOwner();
8253 mContext.sendBroadcastAsUser(
8254 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8259 public SystemUpdatePolicy getSystemUpdatePolicy() {
8260 if (UserManager.isDeviceInDemoMode(mContext)) {
8261 // Pretending to have an automatic update policy when the device is in retail demo
8262 // mode. This will allow the device to download and install an ota without
8263 // any user interaction.
8264 return SystemUpdatePolicy.createAutomaticInstallPolicy();
8266 synchronized (this) {
8267 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
8268 if (policy != null && !policy.isValid()) {
8269 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8277 * Checks if the caller of the method is the device owner app.
8279 * @param callerUid UID of the caller.
8280 * @return true if the caller is the device owner app
8283 boolean isCallerDeviceOwner(int callerUid) {
8284 synchronized (this) {
8285 if (!mOwners.hasDeviceOwner()) {
8288 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8291 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8293 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8295 for (String pkg : pkgs) {
8296 if (deviceOwnerPackageName.equals(pkg)) {
8306 public void notifyPendingSystemUpdate(long updateReceivedTime) {
8307 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8308 "Only the system update service can broadcast update information");
8310 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8311 Slog.w(LOG_TAG, "Only the system update service in the system user " +
8312 "can broadcast update information.");
8315 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8316 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8317 updateReceivedTime);
8319 synchronized (this) {
8320 final String deviceOwnerPackage =
8321 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8323 if (deviceOwnerPackage == null) {
8326 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8328 ActivityInfo[] receivers = null;
8330 receivers = mContext.getPackageManager().getPackageInfo(
8331 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8332 } catch (NameNotFoundException e) {
8333 Log.e(LOG_TAG, "Cannot find device owner package", e);
8335 if (receivers != null) {
8336 long ident = mInjector.binderClearCallingIdentity();
8338 for (int i = 0; i < receivers.length; i++) {
8339 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8340 intent.setComponent(new ComponentName(deviceOwnerPackage,
8341 receivers[i].name));
8342 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8346 mInjector.binderRestoreCallingIdentity(ident);
8353 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8354 int userId = UserHandle.getCallingUserId();
8355 synchronized (this) {
8356 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8357 DevicePolicyData userPolicy = getUserData(userId);
8358 if (userPolicy.mPermissionPolicy != policy) {
8359 userPolicy.mPermissionPolicy = policy;
8360 saveSettingsLocked(userId);
8366 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8367 int userId = UserHandle.getCallingUserId();
8368 synchronized (this) {
8369 DevicePolicyData userPolicy = getUserData(userId);
8370 return userPolicy.mPermissionPolicy;
8375 public boolean setPermissionGrantState(ComponentName admin, String packageName,
8376 String permission, int grantState) throws RemoteException {
8377 UserHandle user = mInjector.binderGetCallingUserHandle();
8378 synchronized (this) {
8379 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8380 long ident = mInjector.binderClearCallingIdentity();
8382 if (getTargetSdk(packageName, user.getIdentifier())
8383 < android.os.Build.VERSION_CODES.M) {
8386 final PackageManager packageManager = mContext.getPackageManager();
8387 switch (grantState) {
8388 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8389 packageManager.grantRuntimePermission(packageName, permission, user);
8390 packageManager.updatePermissionFlags(permission, packageName,
8391 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8392 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8395 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8396 packageManager.revokeRuntimePermission(packageName,
8398 packageManager.updatePermissionFlags(permission, packageName,
8399 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8400 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8403 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8404 packageManager.updatePermissionFlags(permission, packageName,
8405 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8409 } catch (SecurityException se) {
8412 mInjector.binderRestoreCallingIdentity(ident);
8418 public int getPermissionGrantState(ComponentName admin, String packageName,
8419 String permission) throws RemoteException {
8420 PackageManager packageManager = mContext.getPackageManager();
8422 UserHandle user = mInjector.binderGetCallingUserHandle();
8423 synchronized (this) {
8424 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8425 long ident = mInjector.binderClearCallingIdentity();
8427 int granted = mIPackageManager.checkPermission(permission,
8428 packageName, user.getIdentifier());
8429 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8430 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8431 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8432 // Not controlled by policy
8433 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8435 // Policy controlled so return result based on permission grant state
8436 return granted == PackageManager.PERMISSION_GRANTED
8437 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8438 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8441 mInjector.binderRestoreCallingIdentity(ident);
8446 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8448 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8450 return (pi != null) && (pi.applicationInfo.flags != 0);
8451 } catch (RemoteException re) {
8452 throw new RuntimeException("Package manager has died", re);
8457 public boolean isProvisioningAllowed(String action) {
8462 final int callingUserId = mInjector.userHandleGetCallingUserId();
8463 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8464 if (!hasFeatureManagedUsers()) {
8467 synchronized (this) {
8468 if (mOwners.hasDeviceOwner()) {
8469 if (!mInjector.userManagerIsSplitSystemUser()) {
8470 // Only split-system-user systems support managed-profiles in combination with
8474 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8475 // Only system device-owner supports managed-profiles. Non-system device-owner
8479 if (callingUserId == UserHandle.USER_SYSTEM) {
8480 // Managed-profiles cannot be setup on the system user, only regular users.
8485 if (getProfileOwner(callingUserId) != null) {
8486 // Managed user cannot have a managed profile.
8489 final long ident = mInjector.binderClearCallingIdentity();
8491 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8495 mInjector.binderRestoreCallingIdentity(ident);
8498 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8499 return isDeviceOwnerProvisioningAllowed(callingUserId);
8500 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8501 if (!hasFeatureManagedUsers()) {
8504 if (!mInjector.userManagerIsSplitSystemUser()) {
8505 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8508 if (callingUserId == UserHandle.USER_SYSTEM) {
8509 // System user cannot be a managed user.
8512 if (hasUserSetupCompleted(callingUserId)) {
8516 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8517 if (!mInjector.userManagerIsSplitSystemUser()) {
8518 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8521 return isDeviceOwnerProvisioningAllowed(callingUserId);
8523 throw new IllegalArgumentException("Unknown provisioning action " + action);
8527 * The device owner can only be set before the setup phase of the primary user has completed,
8528 * except for adb command if no accounts or additional users are present on the device.
8530 private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreConditionLocked(
8531 @Nullable ComponentName owner, int deviceOwnerUserId, boolean isAdb) {
8532 if (mOwners.hasDeviceOwner()) {
8533 return CODE_HAS_DEVICE_OWNER;
8535 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8536 return CODE_USER_HAS_PROFILE_OWNER;
8538 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8539 return CODE_USER_NOT_RUNNING;
8542 // if shell command runs after user setup completed check device status. Otherwise, OK.
8543 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8544 if (!mInjector.userManagerIsSplitSystemUser()) {
8545 if (mUserManager.getUserCount() > 1) {
8546 return CODE_NONSYSTEM_USER_EXISTS;
8548 if (hasIncompatibleAccountsLocked(UserHandle.USER_SYSTEM, owner)) {
8549 return CODE_ACCOUNTS_NOT_EMPTY;
8552 // STOPSHIP Do proper check in split user mode
8557 if (!mInjector.userManagerIsSplitSystemUser()) {
8558 // In non-split user mode, DO has to be user 0
8559 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8560 return CODE_NOT_SYSTEM_USER;
8562 // In non-split user mode, only provision DO before setup wizard completes
8563 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8564 return CODE_USER_SETUP_COMPLETED;
8567 // STOPSHIP Do proper check in split user mode
8573 private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8574 synchronized (this) {
8575 return CODE_OK == checkSetDeviceOwnerPreConditionLocked(
8576 /* owner unknown */ null, deviceOwnerUserId, /* isAdb */ false);
8580 private boolean hasFeatureManagedUsers() {
8582 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8583 } catch (RemoteException e) {
8589 public String getWifiMacAddress(ComponentName admin) {
8590 // Make sure caller has DO.
8591 synchronized (this) {
8592 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8595 final long ident = mInjector.binderClearCallingIdentity();
8597 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8598 if (wifiInfo == null) {
8601 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8603 mInjector.binderRestoreCallingIdentity(ident);
8608 * Returns the target sdk version number that the given packageName was built for
8609 * in the given user.
8611 private int getTargetSdk(String packageName, int userId) {
8612 final ApplicationInfo ai;
8614 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8615 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8616 return targetSdkVersion;
8617 } catch (RemoteException e) {
8624 public boolean isManagedProfile(ComponentName admin) {
8625 synchronized (this) {
8626 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8628 final int callingUserId = mInjector.userHandleGetCallingUserId();
8629 final UserInfo user = getUserInfo(callingUserId);
8630 return user != null && user.isManagedProfile();
8634 public boolean isSystemOnlyUser(ComponentName admin) {
8635 synchronized (this) {
8636 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8638 final int callingUserId = mInjector.userHandleGetCallingUserId();
8639 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8643 public void reboot(ComponentName admin) {
8644 Preconditions.checkNotNull(admin);
8645 // Make sure caller has DO.
8646 synchronized (this) {
8647 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8649 long ident = mInjector.binderClearCallingIdentity();
8651 // Make sure there are no ongoing calls on the device.
8652 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8653 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8655 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8657 mInjector.binderRestoreCallingIdentity(ident);
8662 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8666 Preconditions.checkNotNull(who, "ComponentName is null");
8667 final int userHandle = mInjector.userHandleGetCallingUserId();
8668 synchronized (this) {
8669 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8670 mInjector.binderGetCallingUid());
8671 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8672 admin.shortSupportMessage = message;
8673 saveSettingsLocked(userHandle);
8679 public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8683 Preconditions.checkNotNull(who, "ComponentName is null");
8684 synchronized (this) {
8685 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8686 mInjector.binderGetCallingUid());
8687 return admin.shortSupportMessage;
8692 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8696 Preconditions.checkNotNull(who, "ComponentName is null");
8697 final int userHandle = mInjector.userHandleGetCallingUserId();
8698 synchronized (this) {
8699 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8700 mInjector.binderGetCallingUid());
8701 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8702 admin.longSupportMessage = message;
8703 saveSettingsLocked(userHandle);
8709 public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8713 Preconditions.checkNotNull(who, "ComponentName is null");
8714 synchronized (this) {
8715 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8716 mInjector.binderGetCallingUid());
8717 return admin.longSupportMessage;
8722 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8726 Preconditions.checkNotNull(who, "ComponentName is null");
8727 if (!isCallerWithSystemUid()) {
8728 throw new SecurityException("Only the system can query support message for user");
8730 synchronized (this) {
8731 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8732 if (admin != null) {
8733 return admin.shortSupportMessage;
8740 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8744 Preconditions.checkNotNull(who, "ComponentName is null");
8745 if (!isCallerWithSystemUid()) {
8746 throw new SecurityException("Only the system can query support message for user");
8748 synchronized (this) {
8749 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8750 if (admin != null) {
8751 return admin.longSupportMessage;
8758 public void setOrganizationColor(@NonNull ComponentName who, int color) {
8762 Preconditions.checkNotNull(who, "ComponentName is null");
8763 final int userHandle = mInjector.userHandleGetCallingUserId();
8764 enforceManagedProfile(userHandle, "set organization color");
8765 synchronized (this) {
8766 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8767 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8768 admin.organizationColor = color;
8769 saveSettingsLocked(userHandle);
8774 public void setOrganizationColorForUser(int color, int userId) {
8778 enforceFullCrossUsersPermission(userId);
8779 enforceManageUsers();
8780 enforceManagedProfile(userId, "set organization color");
8781 synchronized (this) {
8782 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8783 admin.organizationColor = color;
8784 saveSettingsLocked(userId);
8789 public int getOrganizationColor(@NonNull ComponentName who) {
8791 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8793 Preconditions.checkNotNull(who, "ComponentName is null");
8794 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
8795 synchronized (this) {
8796 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8797 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8798 return admin.organizationColor;
8803 public int getOrganizationColorForUser(int userHandle) {
8805 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8807 enforceFullCrossUsersPermission(userHandle);
8808 enforceManagedProfile(userHandle, "get organization color");
8809 synchronized (this) {
8810 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8811 return (profileOwner != null)
8812 ? profileOwner.organizationColor
8813 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
8818 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
8822 Preconditions.checkNotNull(who, "ComponentName is null");
8823 final int userHandle = mInjector.userHandleGetCallingUserId();
8824 enforceManagedProfile(userHandle, "set organization name");
8825 synchronized (this) {
8826 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8827 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8828 if (!TextUtils.equals(admin.organizationName, text)) {
8829 admin.organizationName = (text == null || text.length() == 0)
8830 ? null : text.toString();
8831 saveSettingsLocked(userHandle);
8837 public CharSequence getOrganizationName(@NonNull ComponentName who) {
8841 Preconditions.checkNotNull(who, "ComponentName is null");
8842 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
8843 synchronized(this) {
8844 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8845 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8846 return admin.organizationName;
8851 public CharSequence getOrganizationNameForUser(int userHandle) {
8855 enforceFullCrossUsersPermission(userHandle);
8856 enforceManagedProfile(userHandle, "get organization name");
8857 synchronized (this) {
8858 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8859 return (profileOwner != null)
8860 ? profileOwner.organizationName
8866 public void setAffiliationIds(ComponentName admin, List<String> ids) {
8867 final Set<String> affiliationIds = new ArraySet<String>(ids);
8868 final int callingUserId = mInjector.userHandleGetCallingUserId();
8870 synchronized (this) {
8871 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8872 getUserData(callingUserId).mAffiliationIds = affiliationIds;
8873 saveSettingsLocked(callingUserId);
8874 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
8875 // Affiliation ids specified by the device owner are additionally stored in
8876 // UserHandle.USER_SYSTEM's DevicePolicyData.
8877 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
8878 saveSettingsLocked(UserHandle.USER_SYSTEM);
8884 public boolean isAffiliatedUser() {
8885 final int callingUserId = mInjector.userHandleGetCallingUserId();
8887 synchronized (this) {
8888 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
8889 // The user that the DO is installed on is always affiliated.
8892 final ComponentName profileOwner = getProfileOwner(callingUserId);
8893 if (profileOwner == null
8894 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
8897 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
8898 final Set<String> deviceAffiliationIds =
8899 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
8900 for (String id : userAffiliationIds) {
8901 if (deviceAffiliationIds.contains(id)) {
8909 private synchronized void disableSecurityLoggingIfNotCompliant() {
8910 if (!isDeviceOwnerManagedSingleUserDevice()) {
8911 mInjector.securityLogSetLoggingEnabledProperty(false);
8912 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user device.");
8917 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
8918 Preconditions.checkNotNull(admin);
8919 ensureDeviceOwnerManagingSingleUser(admin);
8921 synchronized (this) {
8922 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
8925 mInjector.securityLogSetLoggingEnabledProperty(enabled);
8927 mSecurityLogMonitor.start();
8929 mSecurityLogMonitor.stop();
8935 public boolean isSecurityLoggingEnabled(ComponentName admin) {
8936 Preconditions.checkNotNull(admin);
8937 synchronized (this) {
8938 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8939 return mInjector.securityLogGetLoggingEnabledProperty();
8944 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
8945 Preconditions.checkNotNull(admin);
8946 ensureDeviceOwnerManagingSingleUser(admin);
8948 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
8952 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
8954 SecurityLog.readPreviousEvents(output);
8955 return new ParceledListSlice<SecurityEvent>(output);
8956 } catch (IOException e) {
8957 Slog.w(LOG_TAG, "Fail to read previous events" , e);
8958 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
8963 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
8964 Preconditions.checkNotNull(admin);
8965 ensureDeviceOwnerManagingSingleUser(admin);
8967 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
8968 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
8971 private void enforceCanManageDeviceAdmin() {
8972 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
8976 private void enforceCanManageProfileAndDeviceOwners() {
8977 mContext.enforceCallingOrSelfPermission(
8978 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
8982 public boolean isUninstallInQueue(final String packageName) {
8983 enforceCanManageDeviceAdmin();
8984 final int userId = mInjector.userHandleGetCallingUserId();
8985 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8986 synchronized (this) {
8987 return mPackagesToRemove.contains(packageUserPair);
8992 public void uninstallPackageWithActiveAdmins(final String packageName) {
8993 enforceCanManageDeviceAdmin();
8994 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
8996 final int userId = mInjector.userHandleGetCallingUserId();
8998 enforceUserUnlocked(userId);
9000 final ComponentName profileOwner = getProfileOwner(userId);
9001 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
9002 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
9005 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
9006 if (getDeviceOwnerUserId() == userId && deviceOwner != null
9007 && packageName.equals(deviceOwner.getPackageName())) {
9008 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
9011 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9012 synchronized (this) {
9013 mPackagesToRemove.add(packageUserPair);
9016 // All active admins on the user.
9017 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
9019 // Active admins in the target package.
9020 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
9021 if (allActiveAdmins != null) {
9022 for (ComponentName activeAdmin : allActiveAdmins) {
9023 if (packageName.equals(activeAdmin.getPackageName())) {
9024 packageActiveAdmins.add(activeAdmin);
9025 removeActiveAdmin(activeAdmin, userId);
9029 if (packageActiveAdmins.size() == 0) {
9030 startUninstallIntent(packageName, userId);
9032 mHandler.postDelayed(new Runnable() {
9035 for (ComponentName activeAdmin : packageActiveAdmins) {
9036 removeAdminArtifacts(activeAdmin, userId);
9038 startUninstallIntent(packageName, userId);
9040 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9045 public boolean isDeviceProvisioned() {
9046 return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9049 private void removePackageIfRequired(final String packageName, final int userId) {
9050 if (!packageHasActiveAdmins(packageName, userId)) {
9051 // Will not do anything if uninstall was not requested or was already started.
9052 startUninstallIntent(packageName, userId);
9056 private void startUninstallIntent(final String packageName, final int userId) {
9057 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9058 synchronized (this) {
9059 if (!mPackagesToRemove.contains(packageUserPair)) {
9060 // Do nothing if uninstall was not requested or was already started.
9063 mPackagesToRemove.remove(packageUserPair);
9066 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9067 // Package does not exist. Nothing to do.
9070 } catch (RemoteException re) {
9071 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9074 try { // force stop the package before uninstalling
9075 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9076 } catch (RemoteException re) {
9077 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9079 final Uri packageURI = Uri.parse("package:" + packageName);
9080 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9081 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9082 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9086 * Removes the admin from the policy. Ideally called after the admin's
9087 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9089 * @param adminReceiver The admin to remove
9090 * @param userHandle The user for which this admin has to be removed.
9092 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9093 synchronized (this) {
9094 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9095 if (admin == null) {
9098 final DevicePolicyData policy = getUserData(userHandle);
9099 final boolean doProxyCleanup = admin.info.usesPolicy(
9100 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9101 policy.mAdminList.remove(admin);
9102 policy.mAdminMap.remove(adminReceiver);
9103 validatePasswordOwnerLocked(policy);
9104 if (doProxyCleanup) {
9105 resetGlobalProxyLocked(policy);
9107 saveSettingsLocked(userHandle);
9108 updateMaximumTimeToLockLocked(userHandle);
9109 policy.mRemovingAdmins.remove(adminReceiver);
9111 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
9113 // The removed admin might have disabled camera, so update user
9115 pushUserRestrictions(userHandle);
9119 public void setDeviceProvisioningConfigApplied() {
9120 enforceManageUsers();
9121 synchronized (this) {
9122 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9123 policy.mDeviceProvisioningConfigApplied = true;
9124 saveSettingsLocked(UserHandle.USER_SYSTEM);
9129 public boolean isDeviceProvisioningConfigApplied() {
9130 enforceManageUsers();
9131 synchronized (this) {
9132 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9133 return policy.mDeviceProvisioningConfigApplied;
9138 * Return true if a given user has any accounts that'll prevent installing a device or profile
9139 * owner {@code owner}.
9140 * - If the user has no accounts, then return false.
9141 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
9142 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
9143 * ..._DISALLOWED, return true.
9144 * - Otherwise return false.
9146 private boolean hasIncompatibleAccountsLocked(int userId, @Nullable ComponentName owner) {
9147 final long token = mInjector.binderClearCallingIdentity();
9149 final AccountManager am = AccountManager.get(mContext);
9150 final Account accounts[] = am.getAccountsAsUser(userId);
9151 if (accounts.length == 0) {
9154 final String[] feature_allow =
9155 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
9156 final String[] feature_disallow =
9157 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
9159 // Even if we find incompatible accounts along the way, we still check all accounts
9161 boolean compatible = true;
9162 for (Account account : accounts) {
9163 if (hasAccountFeatures(am, account, feature_disallow)) {
9164 Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
9167 if (!hasAccountFeatures(am, account, feature_allow)) {
9168 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
9173 Log.w(LOG_TAG, "All accounts are compatible");
9175 Log.e(LOG_TAG, "Found incompatible accounts");
9178 // Then check if the owner is test-only.
9180 if (owner == null) {
9181 // Owner is unknown. Suppose it's not test-only
9183 log = "Only test-only device/profile owner can be installed with accounts";
9184 } else if (isAdminTestOnlyLocked(owner, userId)) {
9186 log = "Installing test-only owner " + owner;
9188 log = "Can't install test-only owner " + owner + " with incompatible accounts";
9192 log = "Can't install non test-only owner " + owner + " with accounts";
9195 Log.w(LOG_TAG, log);
9197 Log.e(LOG_TAG, log);
9201 mInjector.binderRestoreCallingIdentity(token);
9205 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
9207 return am.hasFeatures(account, features, null, null).getResult();
9208 } catch (Exception e) {
9209 Log.w(LOG_TAG, "Failed to get account feature", e);