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.content.BroadcastReceiver;
58 import android.content.ComponentName;
59 import android.content.Context;
60 import android.content.Intent;
61 import android.content.IntentFilter;
62 import android.content.pm.ActivityInfo;
63 import android.content.pm.ApplicationInfo;
64 import android.content.pm.IPackageManager;
65 import android.content.pm.PackageInfo;
66 import android.content.pm.PackageManager;
67 import android.content.pm.PackageManager.NameNotFoundException;
68 import android.content.pm.PackageManagerInternal;
69 import android.content.pm.ParceledListSlice;
70 import android.content.pm.ResolveInfo;
71 import android.content.pm.ServiceInfo;
72 import android.content.pm.UserInfo;
73 import android.database.ContentObserver;
74 import android.graphics.Bitmap;
75 import android.graphics.Color;
76 import android.media.AudioManager;
77 import android.media.IAudioService;
78 import android.net.ConnectivityManager;
79 import android.net.ProxyInfo;
80 import android.net.Uri;
81 import android.net.wifi.WifiInfo;
82 import android.net.wifi.WifiManager;
83 import android.os.AsyncTask;
84 import android.os.Binder;
85 import android.os.Build;
86 import android.os.Bundle;
87 import android.os.Environment;
88 import android.os.FileUtils;
89 import android.os.Handler;
90 import android.os.IBinder;
91 import android.os.Looper;
92 import android.os.ParcelFileDescriptor;
93 import android.os.PersistableBundle;
94 import android.os.PowerManager;
95 import android.os.PowerManagerInternal;
96 import android.os.Process;
97 import android.os.RecoverySystem;
98 import android.os.RemoteCallback;
99 import android.os.RemoteException;
100 import android.os.ServiceManager;
101 import android.os.SystemClock;
102 import android.os.SystemProperties;
103 import android.os.UserHandle;
104 import android.os.UserManager;
105 import android.os.UserManagerInternal;
106 import android.os.storage.StorageManager;
107 import android.provider.ContactsContract.QuickContact;
108 import android.provider.ContactsInternal;
109 import android.provider.Settings;
110 import android.security.Credentials;
111 import android.security.IKeyChainAliasCallback;
112 import android.security.IKeyChainService;
113 import android.security.KeyChain;
114 import android.security.KeyChain.KeyChainConnection;
115 import android.service.persistentdata.PersistentDataBlockManager;
116 import android.telephony.TelephonyManager;
117 import android.text.TextUtils;
118 import android.util.ArrayMap;
119 import android.util.ArraySet;
120 import android.util.Log;
121 import android.util.Pair;
122 import android.util.Slog;
123 import android.util.SparseArray;
124 import android.util.Xml;
125 import android.view.IWindowManager;
126 import android.view.accessibility.AccessibilityManager;
127 import android.view.accessibility.IAccessibilityManager;
128 import android.view.inputmethod.InputMethodInfo;
129 import android.view.inputmethod.InputMethodManager;
131 import com.android.internal.R;
132 import com.android.internal.annotations.VisibleForTesting;
133 import com.android.internal.statusbar.IStatusBarService;
134 import com.android.internal.util.FastXmlSerializer;
135 import com.android.internal.util.JournaledFile;
136 import com.android.internal.util.ParcelableString;
137 import com.android.internal.util.Preconditions;
138 import com.android.internal.util.XmlUtils;
139 import com.android.internal.widget.LockPatternUtils;
140 import com.android.server.LocalServices;
141 import com.android.server.SystemService;
142 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
143 import com.android.server.pm.UserRestrictionsUtils;
144 import com.google.android.collect.Sets;
146 import org.xmlpull.v1.XmlPullParser;
147 import org.xmlpull.v1.XmlPullParserException;
148 import org.xmlpull.v1.XmlSerializer;
150 import java.io.ByteArrayInputStream;
152 import java.io.FileDescriptor;
153 import java.io.FileInputStream;
154 import java.io.FileNotFoundException;
155 import java.io.FileOutputStream;
156 import java.io.IOException;
157 import java.io.PrintWriter;
158 import java.lang.annotation.Retention;
159 import java.lang.annotation.RetentionPolicy;
160 import java.nio.charset.StandardCharsets;
161 import java.security.cert.CertificateException;
162 import java.security.cert.CertificateFactory;
163 import java.security.cert.X509Certificate;
164 import java.text.DateFormat;
165 import java.util.ArrayList;
166 import java.util.Arrays;
167 import java.util.Collections;
168 import java.util.Date;
169 import java.util.List;
170 import java.util.Map.Entry;
171 import java.util.Set;
172 import java.util.concurrent.atomic.AtomicBoolean;
175 * Implementation of the device policy APIs.
177 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
179 private static final String LOG_TAG = "DevicePolicyManagerService";
181 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
183 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
185 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
187 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
189 private static final String TAG_STATUS_BAR = "statusbar";
191 private static final String ATTR_DISABLED = "disabled";
193 private static final String ATTR_NAME = "name";
195 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
196 "do-not-ask-credentials-on-boot";
198 private static final String TAG_AFFILIATION_ID = "affiliation-id";
200 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
202 private static final String ATTR_VALUE = "value";
204 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
206 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
208 private static final long MS_PER_DAY = 86400 * 1000;
210 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
212 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
213 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
215 private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
216 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
218 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
219 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
220 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
221 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
222 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
223 "device-provisioning-config-applied";
225 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
226 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
227 = "application-restrictions-manager";
230 * System property whose value is either "true" or "false", indicating whether
232 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
234 private static final int STATUS_BAR_DISABLE_MASK =
235 StatusBarManager.DISABLE_EXPAND |
236 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
237 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
238 StatusBarManager.DISABLE_SEARCH;
240 private static final int STATUS_BAR_DISABLE2_MASK =
241 StatusBarManager.DISABLE2_QUICK_SETTINGS;
243 private static final Set<String> SECURE_SETTINGS_WHITELIST;
244 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
245 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
246 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
248 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
249 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
250 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
251 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
253 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
254 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
255 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
257 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
258 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
259 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
260 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
261 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
262 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
263 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
264 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
265 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
267 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
268 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
269 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
270 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
271 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
272 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
276 * Keyguard features that when set on a managed profile that doesn't have its own challenge will
277 * affect the profile's parent user. These can also be set on the managed profile's parent DPM
280 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
281 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
282 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
285 * Keyguard features that when set on a profile affect the profile content or challenge only.
286 * These cannot be set on the managed profile's parent DPM instance
288 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
289 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
291 /** Keyguard features that are allowed to be set on a managed profile */
292 private static final int PROFILE_KEYGUARD_FEATURES =
293 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
295 private static final int CODE_OK = 0;
296 private static final int CODE_HAS_DEVICE_OWNER = 1;
297 private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
298 private static final int CODE_USER_NOT_RUNNING = 3;
299 private static final int CODE_USER_SETUP_COMPLETED = 4;
300 private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
301 private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
302 private static final int CODE_NOT_SYSTEM_USER = 7;
304 @Retention(RetentionPolicy.SOURCE)
305 @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
306 CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
307 private @interface DeviceOwnerPreConditionCode {}
309 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
311 final Context mContext;
312 final Injector mInjector;
313 final IPackageManager mIPackageManager;
314 final UserManager mUserManager;
315 final UserManagerInternal mUserManagerInternal;
316 final TelephonyManager mTelephonyManager;
317 private final LockPatternUtils mLockPatternUtils;
320 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
321 * is requested for user u.
323 private final Set<Pair<String, Integer>> mPackagesToRemove =
324 new ArraySet<Pair<String, Integer>>();
326 final LocalService mLocalService;
328 // Stores and loads state on device and profile owners.
330 final Owners mOwners;
332 private final Binder mToken = new Binder();
335 * Whether or not device admin feature is supported. If it isn't return defaults for all
340 private final SecurityLogMonitor mSecurityLogMonitor;
342 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
343 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
345 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
348 if(mRemoteBugreportServiceIsActive.get()) {
354 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
357 public void onReceive(Context context, Intent intent) {
358 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
359 && mRemoteBugreportServiceIsActive.get()) {
360 onBugreportFinished(intent);
365 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
368 public void onReceive(Context context, Intent intent) {
369 String action = intent.getAction();
370 mInjector.getNotificationManager().cancel(LOG_TAG,
371 RemoteBugreportUtils.NOTIFICATION_ID);
372 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
373 onBugreportSharingAccepted();
374 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
375 onBugreportSharingDeclined();
377 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
381 public static final class Lifecycle extends SystemService {
382 private DevicePolicyManagerService mService;
384 public Lifecycle(Context context) {
386 mService = new DevicePolicyManagerService(context);
390 public void onStart() {
391 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
395 public void onBootPhase(int phase) {
396 mService.systemReady(phase);
400 public void onStartUser(int userHandle) {
401 mService.onStartUser(userHandle);
405 public static class DevicePolicyData {
406 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
407 int mActivePasswordLength = 0;
408 int mActivePasswordUpperCase = 0;
409 int mActivePasswordLowerCase = 0;
410 int mActivePasswordLetters = 0;
411 int mActivePasswordNumeric = 0;
412 int mActivePasswordSymbols = 0;
413 int mActivePasswordNonLetter = 0;
414 int mFailedPasswordAttempts = 0;
417 int mPasswordOwner = -1;
418 long mLastMaximumTimeToLock = -1;
419 boolean mUserSetupComplete = false;
420 int mUserProvisioningState;
421 int mPermissionPolicy;
423 boolean mDeviceProvisioningConfigApplied = false;
425 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
426 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
427 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
429 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
431 // This is the list of component allowed to start lock task mode.
432 List<String> mLockTaskPackages = new ArrayList<>();
434 boolean mStatusBarDisabled = false;
436 ComponentName mRestrictionsProvider;
438 String mDelegatedCertInstallerPackage;
440 boolean doNotAskCredentialsOnBoot = false;
442 String mApplicationRestrictionsManagingPackage;
444 Set<String> mAffiliationIds = new ArraySet<>();
446 // Used for initialization of users created by createAndManageUsers.
447 boolean mAdminBroadcastPending = false;
448 PersistableBundle mInitBundle = null;
450 public DevicePolicyData(int userHandle) {
451 mUserHandle = userHandle;
455 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
457 final Handler mHandler;
459 BroadcastReceiver mReceiver = new BroadcastReceiver() {
461 public void onReceive(Context context, Intent intent) {
462 final String action = intent.getAction();
463 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
466 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
467 && userHandle == mOwners.getDeviceOwnerUserId()
468 && getDeviceOwnerRemoteBugreportUri() != null) {
469 IntentFilter filterConsent = new IntentFilter();
470 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
471 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
472 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
473 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
474 RemoteBugreportUtils.NOTIFICATION_ID,
475 RemoteBugreportUtils.buildNotification(mContext,
476 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
479 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
480 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
482 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
483 + action + " for user " + userHandle);
485 mHandler.post(new Runnable() {
488 handlePasswordExpirationNotification(userHandle);
492 if (Intent.ACTION_USER_UNLOCKED.equals(action)
493 || Intent.ACTION_USER_STARTED.equals(action)
494 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
495 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
496 new MonitoringCertNotificationTask().execute(userId);
498 if (Intent.ACTION_USER_ADDED.equals(action)) {
499 disableSecurityLoggingIfNotCompliant();
500 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
501 disableSecurityLoggingIfNotCompliant();
502 removeUserData(userHandle);
503 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
504 synchronized (DevicePolicyManagerService.this) {
505 // Reset the policy data
506 mUserData.remove(userHandle);
507 sendAdminEnabledBroadcastLocked(userHandle);
509 handlePackagesChanged(null /* check all admins */, userHandle);
510 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
511 handlePackagesChanged(null /* check all admins */, userHandle);
512 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
513 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
514 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
515 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
516 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
517 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
518 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
519 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
520 clearWipeProfileNotification();
525 static class ActiveAdmin {
526 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
527 private static final String TAG_DISABLE_CAMERA = "disable-camera";
528 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
529 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
530 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
531 = "disable-bt-contacts-sharing";
532 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
533 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
534 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
535 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
536 private static final String TAG_ACCOUNT_TYPE = "account-type";
537 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
538 = "permitted-accessiblity-services";
539 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
540 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
541 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
542 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
543 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
544 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
545 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
546 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
547 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
548 private static final String TAG_PERMITTED_IMES = "permitted-imes";
549 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
550 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
551 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
552 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
553 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
554 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
555 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
556 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
557 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
558 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
559 private static final String ATTR_VALUE = "value";
560 private static final String TAG_PASSWORD_QUALITY = "password-quality";
561 private static final String TAG_POLICIES = "policies";
562 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
563 "cross-profile-widget-providers";
564 private static final String TAG_PROVIDER = "provider";
565 private static final String TAG_PACKAGE_LIST_ITEM = "item";
566 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
567 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
568 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
569 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
570 private static final String TAG_PARENT_ADMIN = "parent-admin";
571 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
572 private static final String TAG_ORGANIZATION_NAME = "organization-name";
574 final DeviceAdminInfo info;
576 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
578 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
579 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
581 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
582 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
584 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
585 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
587 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
588 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
590 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
591 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
593 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
594 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
596 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
597 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
599 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
600 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
602 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
603 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
605 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
606 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
608 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
609 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
611 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
612 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
614 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
616 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
618 boolean encryptionRequested = false;
619 boolean disableCamera = false;
620 boolean disableCallerId = false;
621 boolean disableContactsSearch = false;
622 boolean disableBluetoothContactSharing = true;
623 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
624 boolean requireAutoTime = false; // Can only be set by a device owner.
625 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
627 ActiveAdmin parentAdmin;
628 final boolean isParent;
630 static class TrustAgentInfo {
631 public PersistableBundle options;
632 TrustAgentInfo(PersistableBundle bundle) {
637 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
639 // The list of permitted accessibility services package namesas set by a profile
640 // or device owner. Null means all accessibility services are allowed, empty means
641 // none except system services are allowed.
642 List<String> permittedAccessiblityServices;
644 // The list of permitted input methods package names as set by a profile or device owner.
645 // Null means all input methods are allowed, empty means none except system imes are
647 List<String> permittedInputMethods;
649 // List of package names to keep cached.
650 List<String> keepUninstalledPackages;
652 // TODO: review implementation decisions with frameworks team
653 boolean specifiesGlobalProxy = false;
654 String globalProxySpec = null;
655 String globalProxyExclusionList = null;
657 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
659 List<String> crossProfileWidgetProviders;
661 Bundle userRestrictions;
663 // Support text provided by the admin to display to the user.
664 CharSequence shortSupportMessage = null;
665 CharSequence longSupportMessage = null;
667 // Background color of confirm credentials screen. Default: teal.
668 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
669 int organizationColor = DEF_ORGANIZATION_COLOR;
671 // Default title of confirm credentials screen
672 String organizationName = null;
674 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
679 ActiveAdmin getParentActiveAdmin() {
680 Preconditions.checkState(!isParent);
682 if (parentAdmin == null) {
683 parentAdmin = new ActiveAdmin(info, /* parent */ true);
688 boolean hasParentActiveAdmin() {
689 return parentAdmin != null;
692 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
694 public UserHandle getUserHandle() {
695 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
698 void writeToXml(XmlSerializer out)
699 throws IllegalArgumentException, IllegalStateException, IOException {
700 out.startTag(null, TAG_POLICIES);
701 info.writePoliciesToXml(out);
702 out.endTag(null, TAG_POLICIES);
703 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
704 out.startTag(null, TAG_PASSWORD_QUALITY);
705 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
706 out.endTag(null, TAG_PASSWORD_QUALITY);
707 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
708 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
709 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
710 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
712 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
713 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
714 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
715 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
717 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
718 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
719 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
720 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
722 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
723 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
724 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
725 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
727 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
728 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
729 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
730 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
732 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
733 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
734 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
735 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
737 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
738 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
739 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
740 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
742 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
743 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
744 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
745 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
748 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
749 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
750 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
751 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
753 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
754 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
755 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
756 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
758 if (specifiesGlobalProxy) {
759 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
760 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
761 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
762 if (globalProxySpec != null) {
763 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
764 out.attribute(null, ATTR_VALUE, globalProxySpec);
765 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
767 if (globalProxyExclusionList != null) {
768 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
769 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
770 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
773 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
774 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
775 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
776 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
778 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
779 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
780 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
781 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
783 if (encryptionRequested) {
784 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
785 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
786 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
789 out.startTag(null, TAG_DISABLE_CAMERA);
790 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
791 out.endTag(null, TAG_DISABLE_CAMERA);
793 if (disableCallerId) {
794 out.startTag(null, TAG_DISABLE_CALLER_ID);
795 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
796 out.endTag(null, TAG_DISABLE_CALLER_ID);
798 if (disableContactsSearch) {
799 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
800 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
801 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
803 if (!disableBluetoothContactSharing) {
804 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
805 out.attribute(null, ATTR_VALUE,
806 Boolean.toString(disableBluetoothContactSharing));
807 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
809 if (disableScreenCapture) {
810 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
811 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
812 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
814 if (requireAutoTime) {
815 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
816 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
817 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
819 if (forceEphemeralUsers) {
820 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
821 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
822 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
824 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
825 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
826 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
827 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
829 if (!accountTypesWithManagementDisabled.isEmpty()) {
830 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
831 for (String ac : accountTypesWithManagementDisabled) {
832 out.startTag(null, TAG_ACCOUNT_TYPE);
833 out.attribute(null, ATTR_VALUE, ac);
834 out.endTag(null, TAG_ACCOUNT_TYPE);
836 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
838 if (!trustAgentInfos.isEmpty()) {
839 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
840 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
841 for (Entry<String, TrustAgentInfo> entry : set) {
842 TrustAgentInfo trustAgentInfo = entry.getValue();
843 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
844 out.attribute(null, ATTR_VALUE, entry.getKey());
845 if (trustAgentInfo.options != null) {
846 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
848 trustAgentInfo.options.saveToXml(out);
849 } catch (XmlPullParserException e) {
850 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
852 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
854 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
856 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
858 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
859 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
860 final int providerCount = crossProfileWidgetProviders.size();
861 for (int i = 0; i < providerCount; i++) {
862 String provider = crossProfileWidgetProviders.get(i);
863 out.startTag(null, TAG_PROVIDER);
864 out.attribute(null, ATTR_VALUE, provider);
865 out.endTag(null, TAG_PROVIDER);
867 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
869 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
870 permittedAccessiblityServices);
871 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
872 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
873 if (hasUserRestrictions()) {
874 UserRestrictionsUtils.writeRestrictions(
875 out, userRestrictions, TAG_USER_RESTRICTIONS);
877 if (!TextUtils.isEmpty(shortSupportMessage)) {
878 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
879 out.text(shortSupportMessage.toString());
880 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
882 if (!TextUtils.isEmpty(longSupportMessage)) {
883 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
884 out.text(longSupportMessage.toString());
885 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
887 if (parentAdmin != null) {
888 out.startTag(null, TAG_PARENT_ADMIN);
889 parentAdmin.writeToXml(out);
890 out.endTag(null, TAG_PARENT_ADMIN);
892 if (organizationColor != DEF_ORGANIZATION_COLOR) {
893 out.startTag(null, TAG_ORGANIZATION_COLOR);
894 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
895 out.endTag(null, TAG_ORGANIZATION_COLOR);
897 if (organizationName != null) {
898 out.startTag(null, TAG_ORGANIZATION_NAME);
899 out.text(organizationName);
900 out.endTag(null, TAG_ORGANIZATION_NAME);
904 void writePackageListToXml(XmlSerializer out, String outerTag,
905 List<String> packageList)
906 throws IllegalArgumentException, IllegalStateException, IOException {
907 if (packageList == null) {
911 out.startTag(null, outerTag);
912 for (String packageName : packageList) {
913 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
914 out.attribute(null, ATTR_VALUE, packageName);
915 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
917 out.endTag(null, outerTag);
920 void readFromXml(XmlPullParser parser)
921 throws XmlPullParserException, IOException {
922 int outerDepth = parser.getDepth();
924 while ((type=parser.next()) != END_DOCUMENT
925 && (type != END_TAG || parser.getDepth() > outerDepth)) {
926 if (type == END_TAG || type == TEXT) {
929 String tag = parser.getName();
930 if (TAG_POLICIES.equals(tag)) {
931 info.readPoliciesFromXml(parser);
932 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
933 passwordQuality = Integer.parseInt(
934 parser.getAttributeValue(null, ATTR_VALUE));
935 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
936 minimumPasswordLength = Integer.parseInt(
937 parser.getAttributeValue(null, ATTR_VALUE));
938 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
939 passwordHistoryLength = Integer.parseInt(
940 parser.getAttributeValue(null, ATTR_VALUE));
941 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
942 minimumPasswordUpperCase = Integer.parseInt(
943 parser.getAttributeValue(null, ATTR_VALUE));
944 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
945 minimumPasswordLowerCase = Integer.parseInt(
946 parser.getAttributeValue(null, ATTR_VALUE));
947 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
948 minimumPasswordLetters = Integer.parseInt(
949 parser.getAttributeValue(null, ATTR_VALUE));
950 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
951 minimumPasswordNumeric = Integer.parseInt(
952 parser.getAttributeValue(null, ATTR_VALUE));
953 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
954 minimumPasswordSymbols = Integer.parseInt(
955 parser.getAttributeValue(null, ATTR_VALUE));
956 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
957 minimumPasswordNonLetter = Integer.parseInt(
958 parser.getAttributeValue(null, ATTR_VALUE));
959 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
960 maximumTimeToUnlock = Long.parseLong(
961 parser.getAttributeValue(null, ATTR_VALUE));
962 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
963 maximumFailedPasswordsForWipe = Integer.parseInt(
964 parser.getAttributeValue(null, ATTR_VALUE));
965 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
966 specifiesGlobalProxy = Boolean.parseBoolean(
967 parser.getAttributeValue(null, ATTR_VALUE));
968 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
970 parser.getAttributeValue(null, ATTR_VALUE);
971 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
972 globalProxyExclusionList =
973 parser.getAttributeValue(null, ATTR_VALUE);
974 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
975 passwordExpirationTimeout = Long.parseLong(
976 parser.getAttributeValue(null, ATTR_VALUE));
977 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
978 passwordExpirationDate = Long.parseLong(
979 parser.getAttributeValue(null, ATTR_VALUE));
980 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
981 encryptionRequested = Boolean.parseBoolean(
982 parser.getAttributeValue(null, ATTR_VALUE));
983 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
984 disableCamera = Boolean.parseBoolean(
985 parser.getAttributeValue(null, ATTR_VALUE));
986 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
987 disableCallerId = Boolean.parseBoolean(
988 parser.getAttributeValue(null, ATTR_VALUE));
989 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
990 disableContactsSearch = Boolean.parseBoolean(
991 parser.getAttributeValue(null, ATTR_VALUE));
992 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
993 disableBluetoothContactSharing = Boolean.parseBoolean(parser
994 .getAttributeValue(null, ATTR_VALUE));
995 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
996 disableScreenCapture = Boolean.parseBoolean(
997 parser.getAttributeValue(null, ATTR_VALUE));
998 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
999 requireAutoTime = Boolean.parseBoolean(
1000 parser.getAttributeValue(null, ATTR_VALUE));
1001 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1002 forceEphemeralUsers = Boolean.parseBoolean(
1003 parser.getAttributeValue(null, ATTR_VALUE));
1004 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1005 disabledKeyguardFeatures = Integer.parseInt(
1006 parser.getAttributeValue(null, ATTR_VALUE));
1007 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1008 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
1009 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1010 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1011 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1012 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
1013 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1014 permittedAccessiblityServices = readPackageList(parser, tag);
1015 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1016 permittedInputMethods = readPackageList(parser, tag);
1017 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1018 keepUninstalledPackages = readPackageList(parser, tag);
1019 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1020 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
1021 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1022 type = parser.next();
1023 if (type == XmlPullParser.TEXT) {
1024 shortSupportMessage = parser.getText();
1026 Log.w(LOG_TAG, "Missing text when loading short support message");
1028 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1029 type = parser.next();
1030 if (type == XmlPullParser.TEXT) {
1031 longSupportMessage = parser.getText();
1033 Log.w(LOG_TAG, "Missing text when loading long support message");
1035 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1036 Preconditions.checkState(!isParent);
1038 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1039 parentAdmin.readFromXml(parser);
1040 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1041 organizationColor = Integer.parseInt(
1042 parser.getAttributeValue(null, ATTR_VALUE));
1043 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1044 type = parser.next();
1045 if (type == XmlPullParser.TEXT) {
1046 organizationName = parser.getText();
1048 Log.w(LOG_TAG, "Missing text when loading organization name");
1051 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1052 XmlUtils.skipCurrentTag(parser);
1057 private List<String> readPackageList(XmlPullParser parser,
1058 String tag) throws XmlPullParserException, IOException {
1059 List<String> result = new ArrayList<String>();
1060 int outerDepth = parser.getDepth();
1062 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1063 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1064 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1067 String outerTag = parser.getName();
1068 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1069 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1070 if (packageName != null) {
1071 result.add(packageName);
1073 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1076 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1082 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1083 throws XmlPullParserException, IOException {
1084 int outerDepthDAM = parser.getDepth();
1086 Set<String> result = new ArraySet<>();
1087 while ((typeDAM=parser.next()) != END_DOCUMENT
1088 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1089 if (typeDAM == END_TAG || typeDAM == TEXT) {
1092 String tagDAM = parser.getName();
1093 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1094 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1096 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1102 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1103 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1104 int outerDepthDAM = parser.getDepth();
1106 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1107 while ((typeDAM=parser.next()) != END_DOCUMENT
1108 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1109 if (typeDAM == END_TAG || typeDAM == TEXT) {
1112 String tagDAM = parser.getName();
1113 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1114 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1115 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1116 result.put(component, trustAgentInfo);
1118 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1124 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1125 throws XmlPullParserException, IOException {
1126 int outerDepthDAM = parser.getDepth();
1128 TrustAgentInfo result = new TrustAgentInfo(null);
1129 while ((typeDAM=parser.next()) != END_DOCUMENT
1130 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1131 if (typeDAM == END_TAG || typeDAM == TEXT) {
1134 String tagDAM = parser.getName();
1135 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1136 result.options = PersistableBundle.restoreFromXml(parser);
1138 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1144 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1145 throws XmlPullParserException, IOException {
1146 int outerDepthDAM = parser.getDepth();
1148 ArrayList<String> result = null;
1149 while ((typeDAM=parser.next()) != END_DOCUMENT
1150 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1151 if (typeDAM == END_TAG || typeDAM == TEXT) {
1154 String tagDAM = parser.getName();
1155 if (TAG_PROVIDER.equals(tagDAM)) {
1156 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1157 if (result == null) {
1158 result = new ArrayList<>();
1160 result.add(provider);
1162 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1168 boolean hasUserRestrictions() {
1169 return userRestrictions != null && userRestrictions.size() > 0;
1172 Bundle ensureUserRestrictions() {
1173 if (userRestrictions == null) {
1174 userRestrictions = new Bundle();
1176 return userRestrictions;
1179 void dump(String prefix, PrintWriter pw) {
1180 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1181 pw.print(prefix); pw.println("policies:");
1182 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1184 for (int i=0; i<pols.size(); i++) {
1185 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1188 pw.print(prefix); pw.print("passwordQuality=0x");
1189 pw.println(Integer.toHexString(passwordQuality));
1190 pw.print(prefix); pw.print("minimumPasswordLength=");
1191 pw.println(minimumPasswordLength);
1192 pw.print(prefix); pw.print("passwordHistoryLength=");
1193 pw.println(passwordHistoryLength);
1194 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1195 pw.println(minimumPasswordUpperCase);
1196 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1197 pw.println(minimumPasswordLowerCase);
1198 pw.print(prefix); pw.print("minimumPasswordLetters=");
1199 pw.println(minimumPasswordLetters);
1200 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1201 pw.println(minimumPasswordNumeric);
1202 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1203 pw.println(minimumPasswordSymbols);
1204 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1205 pw.println(minimumPasswordNonLetter);
1206 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1207 pw.println(maximumTimeToUnlock);
1208 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1209 pw.println(maximumFailedPasswordsForWipe);
1210 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1211 pw.println(specifiesGlobalProxy);
1212 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1213 pw.println(passwordExpirationTimeout);
1214 pw.print(prefix); pw.print("passwordExpirationDate=");
1215 pw.println(passwordExpirationDate);
1216 if (globalProxySpec != null) {
1217 pw.print(prefix); pw.print("globalProxySpec=");
1218 pw.println(globalProxySpec);
1220 if (globalProxyExclusionList != null) {
1221 pw.print(prefix); pw.print("globalProxyEclusionList=");
1222 pw.println(globalProxyExclusionList);
1224 pw.print(prefix); pw.print("encryptionRequested=");
1225 pw.println(encryptionRequested);
1226 pw.print(prefix); pw.print("disableCamera=");
1227 pw.println(disableCamera);
1228 pw.print(prefix); pw.print("disableCallerId=");
1229 pw.println(disableCallerId);
1230 pw.print(prefix); pw.print("disableContactsSearch=");
1231 pw.println(disableContactsSearch);
1232 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1233 pw.println(disableBluetoothContactSharing);
1234 pw.print(prefix); pw.print("disableScreenCapture=");
1235 pw.println(disableScreenCapture);
1236 pw.print(prefix); pw.print("requireAutoTime=");
1237 pw.println(requireAutoTime);
1238 pw.print(prefix); pw.print("forceEphemeralUsers=");
1239 pw.println(forceEphemeralUsers);
1240 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1241 pw.println(disabledKeyguardFeatures);
1242 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1243 pw.println(crossProfileWidgetProviders);
1244 if (permittedAccessiblityServices != null) {
1245 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1246 pw.println(permittedAccessiblityServices);
1248 if (permittedInputMethods != null) {
1249 pw.print(prefix); pw.print("permittedInputMethods=");
1250 pw.println(permittedInputMethods);
1252 if (keepUninstalledPackages != null) {
1253 pw.print(prefix); pw.print("keepUninstalledPackages=");
1254 pw.println(keepUninstalledPackages);
1256 pw.print(prefix); pw.print("organizationColor=");
1257 pw.println(organizationColor);
1258 if (organizationName != null) {
1259 pw.print(prefix); pw.print("organizationName=");
1260 pw.println(organizationName);
1262 pw.print(prefix); pw.println("userRestrictions:");
1263 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1264 pw.print(prefix); pw.print("isParent=");
1265 pw.println(isParent);
1266 if (parentAdmin != null) {
1267 pw.print(prefix); pw.println("parentAdmin:");
1268 parentAdmin.dump(prefix + " ", pw);
1273 private void handlePackagesChanged(String packageName, int userHandle) {
1274 boolean removed = false;
1275 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1276 DevicePolicyData policy = getUserData(userHandle);
1277 synchronized (this) {
1278 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1279 ActiveAdmin aa = policy.mAdminList.get(i);
1281 // If we're checking all packages or if the specific one we're checking matches,
1282 // then check if the package and receiver still exist.
1283 final String adminPackage = aa.info.getPackageName();
1284 if (packageName == null || packageName.equals(adminPackage)) {
1285 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1286 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1287 PackageManager.MATCH_DIRECT_BOOT_AWARE
1288 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1289 userHandle) == null) {
1291 policy.mAdminList.remove(i);
1292 policy.mAdminMap.remove(aa.info.getComponent());
1295 } catch (RemoteException re) {
1300 validatePasswordOwnerLocked(policy);
1301 saveSettingsLocked(policy.mUserHandle);
1304 // Check if delegated cert installer or app restrictions managing packages are removed.
1305 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1306 policy.mDelegatedCertInstallerPackage = null;
1307 saveSettingsLocked(policy.mUserHandle);
1309 if (isRemovedPackage(
1310 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1311 policy.mApplicationRestrictionsManagingPackage = null;
1312 saveSettingsLocked(policy.mUserHandle);
1316 // The removed admin might have disabled camera, so update user restrictions.
1317 pushUserRestrictions(userHandle);
1321 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1323 return targetPackage != null
1324 && (changedPackage == null || changedPackage.equals(targetPackage))
1325 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1326 } catch (RemoteException e) {
1334 * Unit test will subclass it to inject mocks.
1337 static class Injector {
1339 private final Context mContext;
1341 Injector(Context context) {
1345 Owners newOwners() {
1346 return new Owners(getUserManager(), getUserManagerInternal(),
1347 getPackageManagerInternal());
1350 UserManager getUserManager() {
1351 return UserManager.get(mContext);
1354 UserManagerInternal getUserManagerInternal() {
1355 return LocalServices.getService(UserManagerInternal.class);
1358 PackageManagerInternal getPackageManagerInternal() {
1359 return LocalServices.getService(PackageManagerInternal.class);
1362 NotificationManager getNotificationManager() {
1363 return mContext.getSystemService(NotificationManager.class);
1366 PowerManagerInternal getPowerManagerInternal() {
1367 return LocalServices.getService(PowerManagerInternal.class);
1370 TelephonyManager getTelephonyManager() {
1371 return TelephonyManager.from(mContext);
1374 IWindowManager getIWindowManager() {
1375 return IWindowManager.Stub
1376 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1379 IActivityManager getIActivityManager() {
1380 return ActivityManagerNative.getDefault();
1383 IPackageManager getIPackageManager() {
1384 return AppGlobals.getPackageManager();
1387 IBackupManager getIBackupManager() {
1388 return IBackupManager.Stub.asInterface(
1389 ServiceManager.getService(Context.BACKUP_SERVICE));
1392 IAudioService getIAudioService() {
1393 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1396 LockPatternUtils newLockPatternUtils() {
1397 return new LockPatternUtils(mContext);
1400 boolean storageManagerIsFileBasedEncryptionEnabled() {
1401 return StorageManager.isFileEncryptedNativeOnly();
1404 boolean storageManagerIsNonDefaultBlockEncrypted() {
1405 long identity = Binder.clearCallingIdentity();
1407 return StorageManager.isNonDefaultBlockEncrypted();
1409 Binder.restoreCallingIdentity(identity);
1413 boolean storageManagerIsEncrypted() {
1414 return StorageManager.isEncrypted();
1417 boolean storageManagerIsEncryptable() {
1418 return StorageManager.isEncryptable();
1421 Looper getMyLooper() {
1422 return Looper.myLooper();
1425 WifiManager getWifiManager() {
1426 return mContext.getSystemService(WifiManager.class);
1429 long binderClearCallingIdentity() {
1430 return Binder.clearCallingIdentity();
1433 void binderRestoreCallingIdentity(long token) {
1434 Binder.restoreCallingIdentity(token);
1437 int binderGetCallingUid() {
1438 return Binder.getCallingUid();
1441 int binderGetCallingPid() {
1442 return Binder.getCallingPid();
1445 UserHandle binderGetCallingUserHandle() {
1446 return Binder.getCallingUserHandle();
1449 boolean binderIsCallingUidMyUid() {
1450 return getCallingUid() == Process.myUid();
1453 final int userHandleGetCallingUserId() {
1454 return UserHandle.getUserId(binderGetCallingUid());
1457 File environmentGetUserSystemDirectory(int userId) {
1458 return Environment.getUserSystemDirectory(userId);
1461 void powerManagerGoToSleep(long time, int reason, int flags) {
1462 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1465 void powerManagerReboot(String reason) {
1466 mContext.getSystemService(PowerManager.class).reboot(reason);
1469 boolean systemPropertiesGetBoolean(String key, boolean def) {
1470 return SystemProperties.getBoolean(key, def);
1473 long systemPropertiesGetLong(String key, long def) {
1474 return SystemProperties.getLong(key, def);
1477 String systemPropertiesGet(String key, String def) {
1478 return SystemProperties.get(key, def);
1481 String systemPropertiesGet(String key) {
1482 return SystemProperties.get(key);
1485 void systemPropertiesSet(String key, String value) {
1486 SystemProperties.set(key, value);
1489 boolean userManagerIsSplitSystemUser() {
1490 return UserManager.isSplitSystemUser();
1493 String getDevicePolicyFilePathForSystemUser() {
1494 return "/data/system/";
1497 void registerContentObserver(Uri uri, boolean notifyForDescendents,
1498 ContentObserver observer, int userHandle) {
1499 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1500 observer, userHandle);
1503 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1504 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1505 name, def, userHandle);
1508 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1509 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1510 name, value, userHandle);
1513 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1514 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1515 name, value, userHandle);
1518 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1519 Settings.Global.putStringForUser(mContext.getContentResolver(),
1520 name, value, userHandle);
1523 void settingsSecurePutInt(String name, int value) {
1524 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1527 int settingsGlobalGetInt(String name, int def) {
1528 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1531 void settingsGlobalPutInt(String name, int value) {
1532 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1535 void settingsSecurePutString(String name, String value) {
1536 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1539 void settingsGlobalPutString(String name, String value) {
1540 Settings.Global.putString(mContext.getContentResolver(), name, value);
1543 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1544 SecurityLog.setLoggingEnabledProperty(enabled);
1547 boolean securityLogGetLoggingEnabledProperty() {
1548 return SecurityLog.getLoggingEnabledProperty();
1551 boolean securityLogIsLoggingEnabled() {
1552 return SecurityLog.isLoggingEnabled();
1557 * Instantiates the service.
1559 public DevicePolicyManagerService(Context context) {
1560 this(new Injector(context));
1564 DevicePolicyManagerService(Injector injector) {
1565 mInjector = injector;
1566 mContext = Preconditions.checkNotNull(injector.mContext);
1567 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1568 mOwners = Preconditions.checkNotNull(injector.newOwners());
1570 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1571 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1572 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1573 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1575 mLocalService = new LocalService();
1576 mLockPatternUtils = injector.newLockPatternUtils();
1578 mSecurityLogMonitor = new SecurityLogMonitor(this);
1580 mHasFeature = mContext.getPackageManager()
1581 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1583 // Skip the rest of the initialization
1586 IntentFilter filter = new IntentFilter();
1587 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1588 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1589 filter.addAction(Intent.ACTION_USER_ADDED);
1590 filter.addAction(Intent.ACTION_USER_REMOVED);
1591 filter.addAction(Intent.ACTION_USER_STARTED);
1592 filter.addAction(Intent.ACTION_USER_UNLOCKED);
1593 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1594 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1595 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1596 filter = new IntentFilter();
1597 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1598 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1599 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1600 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1601 filter.addDataScheme("package");
1602 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1603 filter = new IntentFilter();
1604 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1605 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1607 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1611 * Creates and loads the policy data from xml.
1612 * @param userHandle the user for whom to load the policy data
1616 DevicePolicyData getUserData(int userHandle) {
1617 synchronized (this) {
1618 DevicePolicyData policy = mUserData.get(userHandle);
1619 if (policy == null) {
1620 policy = new DevicePolicyData(userHandle);
1621 mUserData.append(userHandle, policy);
1622 loadSettingsLocked(policy, userHandle);
1629 * Creates and loads the policy data from xml for data that is shared between
1630 * various profiles of a user. In contrast to {@link #getUserData(int)}
1631 * it allows access to data of users other than the calling user.
1633 * This function should only be used for shared data, e.g. everything regarding
1634 * passwords and should be removed once multiple screen locks are present.
1635 * @param userHandle the user for whom to load the policy data
1638 DevicePolicyData getUserDataUnchecked(int userHandle) {
1639 long ident = mInjector.binderClearCallingIdentity();
1641 return getUserData(userHandle);
1643 mInjector.binderRestoreCallingIdentity(ident);
1647 void removeUserData(int userHandle) {
1648 synchronized (this) {
1649 if (userHandle == UserHandle.USER_SYSTEM) {
1650 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1653 mOwners.removeProfileOwner(userHandle);
1654 mOwners.writeProfileOwner(userHandle);
1656 DevicePolicyData policy = mUserData.get(userHandle);
1657 if (policy != null) {
1658 mUserData.remove(userHandle);
1660 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1661 DEVICE_POLICIES_XML);
1662 policyFile.delete();
1663 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1665 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1669 synchronized (this) {
1671 setDeviceOwnerSystemPropertyLocked();
1672 findOwnerComponentIfNecessaryLocked();
1673 migrateUserRestrictionsIfNecessaryLocked();
1675 // TODO PO may not have a class name either due to b/17652534. Address that too.
1677 updateDeviceOwnerLocked();
1681 private void setDeviceOwnerSystemPropertyLocked() {
1682 // Device owner may still be provisioned, do not set the read-only system property yet.
1683 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1686 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1687 // always false at this point.
1688 if (StorageManager.inCryptKeeperBounce()) {
1692 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1693 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1695 if (mOwners.hasDeviceOwner()) {
1696 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1697 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1698 disableSecurityLoggingIfNotCompliant();
1699 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1700 mSecurityLogMonitor.start();
1703 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1704 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1709 private void findOwnerComponentIfNecessaryLocked() {
1710 if (!mOwners.hasDeviceOwner()) {
1713 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1715 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1716 return; // Already a full component name.
1719 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1720 doComponentName.getPackageName(),
1721 mOwners.getDeviceOwnerUserId());
1722 if (doComponent == null) {
1723 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1725 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1727 mOwners.getDeviceOwnerName(),
1728 mOwners.getDeviceOwnerUserId(),
1729 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1730 mOwners.writeDeviceOwner();
1732 Log.v(LOG_TAG, "Device owner component filled in");
1738 * We didn't use to persist user restrictions for each owners but only persisted in user
1741 private void migrateUserRestrictionsIfNecessaryLocked() {
1742 boolean migrated = false;
1743 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1744 // except for the "system controlled" ones.
1745 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1747 Log.v(LOG_TAG, "Migrating DO user restrictions");
1751 // Migrate user 0 restrictions to DO.
1752 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1754 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1755 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1757 // Push DO user restrictions to user manager.
1758 pushUserRestrictions(UserHandle.USER_SYSTEM);
1760 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1765 // The following restrictions can be set on secondary users by the device owner, so we
1766 // assume they're not from the PO.
1767 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1768 UserManager.DISALLOW_OUTGOING_CALLS,
1769 UserManager.DISALLOW_SMS);
1771 for (UserInfo ui : mUserManager.getUsers()) {
1772 final int userId = ui.id;
1773 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1775 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1779 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1781 final Set<String> exceptionList =
1782 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1784 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1785 exceptionList, /* isDeviceOwner =*/ false);
1787 // Note if a secondary user has no PO but has a DA that disables camera, we
1788 // don't get here and won't push the camera user restriction to UserManager
1789 // here. That's okay because we'll push user restrictions anyway when a user
1790 // starts. But we still do it because we want to let user manager persist
1792 pushUserRestrictions(userId);
1794 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1797 if (VERBOSE_LOG && migrated) {
1798 Log.v(LOG_TAG, "User restrictions migrated.");
1802 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1803 Set<String> exceptionList, boolean isDeviceOwner) {
1804 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1805 user.getIdentifier());
1807 final Bundle newBaseRestrictions = new Bundle();
1808 final Bundle newOwnerRestrictions = new Bundle();
1810 for (String key : origRestrictions.keySet()) {
1811 if (!origRestrictions.getBoolean(key)) {
1814 final boolean canOwnerChange = isDeviceOwner
1815 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1816 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1818 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1819 newBaseRestrictions.putBoolean(key, true);
1821 newOwnerRestrictions.putBoolean(key, true);
1826 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1827 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1828 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1830 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1831 newBaseRestrictions);
1833 if (admin != null) {
1834 admin.ensureUserRestrictions().clear();
1835 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1837 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1839 saveSettingsLocked(user.getIdentifier());
1842 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1843 final DevicePolicyData policy = getUserData(userId);
1844 final int n = policy.mAdminList.size();
1845 ComponentName found = null;
1847 for (int i = 0; i < n; i++) {
1848 final ActiveAdmin admin = policy.mAdminList.get(i);
1849 if (packageName.equals(admin.info.getPackageName())) {
1852 found = admin.info.getComponent();
1858 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1864 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1865 * reminders. Clears alarm if no expirations are configured.
1867 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1868 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1869 final long now = System.currentTimeMillis();
1870 final long timeToExpire = expiration - now;
1871 final long alarmTime;
1872 if (expiration == 0) {
1873 // No expirations are currently configured: Cancel alarm.
1875 } else if (timeToExpire <= 0) {
1876 // The password has already expired: Repeat every 24 hours.
1877 alarmTime = now + MS_PER_DAY;
1879 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1880 // the expiration time.
1881 long alarmInterval = timeToExpire % MS_PER_DAY;
1882 if (alarmInterval == 0) {
1883 alarmInterval = MS_PER_DAY;
1885 alarmTime = now + alarmInterval;
1888 long token = mInjector.binderClearCallingIdentity();
1890 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1891 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1892 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1893 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1894 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1895 UserHandle.of(affectedUserHandle));
1897 if (alarmTime != 0) {
1898 am.set(AlarmManager.RTC, alarmTime, pi);
1901 mInjector.binderRestoreCallingIdentity(token);
1905 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1906 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1908 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1909 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1915 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
1917 enforceManagedProfile(userHandle, "call APIs on the parent profile");
1919 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1920 if (admin != null && parent) {
1921 admin = admin.getParentActiveAdmin();
1926 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1927 throws SecurityException {
1928 final int callingUid = mInjector.binderGetCallingUid();
1930 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1931 if (result != null) {
1936 final int userId = UserHandle.getUserId(callingUid);
1937 final DevicePolicyData policy = getUserData(userId);
1938 ActiveAdmin admin = policy.mAdminMap.get(who);
1939 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1940 throw new SecurityException("Admin " + admin.info.getComponent()
1941 + " does not own the device");
1943 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1944 throw new SecurityException("Admin " + admin.info.getComponent()
1945 + " does not own the profile");
1947 throw new SecurityException("Admin " + admin.info.getComponent()
1948 + " did not specify uses-policy for: "
1949 + admin.info.getTagForPolicy(reqPolicy));
1951 throw new SecurityException("No active admin owned by uid "
1952 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
1956 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
1957 throws SecurityException {
1959 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
1960 "call APIs on the parent profile");
1962 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
1963 return parent ? admin.getParentActiveAdmin() : admin;
1966 * Find the admin for the component and userId bit of the uid, then check
1967 * the admin's uid matches the uid.
1969 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
1970 final int userId = UserHandle.getUserId(uid);
1971 final DevicePolicyData policy = getUserData(userId);
1972 ActiveAdmin admin = policy.mAdminMap.get(who);
1973 if (admin == null) {
1974 throw new SecurityException("No active admin " + who);
1976 if (admin.getUid() != uid) {
1977 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1982 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
1984 // Try to find an admin which can use reqPolicy
1985 final int userId = UserHandle.getUserId(uid);
1986 final DevicePolicyData policy = getUserData(userId);
1988 ActiveAdmin admin = policy.mAdminMap.get(who);
1989 if (admin == null) {
1990 throw new SecurityException("No active admin " + who);
1992 if (admin.getUid() != uid) {
1993 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1995 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
1999 for (ActiveAdmin admin : policy.mAdminList) {
2000 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2011 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2013 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2014 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2016 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2018 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2019 // DO always has the PO power.
2020 return ownsDevice || ownsProfile;
2022 return admin.info.usesPolicy(reqPolicy);
2026 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2027 sendAdminCommandLocked(admin, action, null);
2030 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2031 sendAdminCommandLocked(admin, action, null, result);
2035 * Send an update to one specific admin, get notified when that admin returns a result.
2037 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2038 BroadcastReceiver result) {
2039 Intent intent = new Intent(action);
2040 intent.setComponent(admin.info.getComponent());
2041 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2042 intent.putExtra("expiration", admin.passwordExpirationDate);
2044 if (adminExtras != null) {
2045 intent.putExtras(adminExtras);
2047 if (result != null) {
2048 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2049 null, result, mHandler, Activity.RESULT_OK, null, null);
2051 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2056 * Send an update to all admins of a user that enforce a specified policy.
2058 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2059 final DevicePolicyData policy = getUserData(userHandle);
2060 final int count = policy.mAdminList.size();
2062 for (int i = 0; i < count; i++) {
2063 final ActiveAdmin admin = policy.mAdminList.get(i);
2064 if (admin.info.usesPolicy(reqPolicy)) {
2065 sendAdminCommandLocked(admin, action);
2072 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2073 * enforce a specified policy.
2075 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2077 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2078 for (int profileId : profileIds) {
2079 sendAdminCommandLocked(action, reqPolicy, profileId);
2084 * Sends a broadcast to each profile that share the password unlock with the given user id.
2086 private void sendAdminCommandForLockscreenPoliciesLocked(
2087 String action, int reqPolicy, int userHandle) {
2088 if (isSeparateProfileChallengeEnabled(userHandle)) {
2089 sendAdminCommandLocked(action, reqPolicy, userHandle);
2091 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2095 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2096 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2097 DevicePolicyData policy = getUserData(userHandle);
2098 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2099 policy.mRemovingAdmins.add(adminReceiver);
2100 sendAdminCommandLocked(admin,
2101 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2102 new BroadcastReceiver() {
2104 public void onReceive(Context context, Intent intent) {
2105 removeAdminArtifacts(adminReceiver, userHandle);
2106 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2113 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2114 boolean throwForMissiongPermission) {
2118 enforceFullCrossUsersPermission(userHandle);
2119 ActivityInfo ai = null;
2121 ai = mIPackageManager.getReceiverInfo(adminName,
2122 PackageManager.GET_META_DATA |
2123 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2124 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2125 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2126 } catch (RemoteException e) {
2127 // shouldn't happen.
2130 throw new IllegalArgumentException("Unknown admin: " + adminName);
2133 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2134 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2135 + permission.BIND_DEVICE_ADMIN;
2136 Slog.w(LOG_TAG, message);
2137 if (throwForMissiongPermission &&
2138 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2139 throw new IllegalArgumentException(message);
2144 return new DeviceAdminInfo(mContext, ai);
2145 } catch (XmlPullParserException | IOException e) {
2146 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2152 private JournaledFile makeJournaledFile(int userHandle) {
2153 final String base = userHandle == UserHandle.USER_SYSTEM
2154 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2155 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2156 DEVICE_POLICIES_XML).getAbsolutePath();
2158 Log.v(LOG_TAG, "Opening " + base);
2160 return new JournaledFile(new File(base), new File(base + ".tmp"));
2163 private void saveSettingsLocked(int userHandle) {
2164 DevicePolicyData policy = getUserData(userHandle);
2165 JournaledFile journal = makeJournaledFile(userHandle);
2166 FileOutputStream stream = null;
2168 stream = new FileOutputStream(journal.chooseForWrite(), false);
2169 XmlSerializer out = new FastXmlSerializer();
2170 out.setOutput(stream, StandardCharsets.UTF_8.name());
2171 out.startDocument(null, true);
2173 out.startTag(null, "policies");
2174 if (policy.mRestrictionsProvider != null) {
2175 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2176 policy.mRestrictionsProvider.flattenToString());
2178 if (policy.mUserSetupComplete) {
2179 out.attribute(null, ATTR_SETUP_COMPLETE,
2180 Boolean.toString(true));
2182 if (policy.mDeviceProvisioningConfigApplied) {
2183 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2184 Boolean.toString(true));
2186 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2187 out.attribute(null, ATTR_PROVISIONING_STATE,
2188 Integer.toString(policy.mUserProvisioningState));
2190 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2191 out.attribute(null, ATTR_PERMISSION_POLICY,
2192 Integer.toString(policy.mPermissionPolicy));
2194 if (policy.mDelegatedCertInstallerPackage != null) {
2195 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2196 policy.mDelegatedCertInstallerPackage);
2198 if (policy.mApplicationRestrictionsManagingPackage != null) {
2199 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2200 policy.mApplicationRestrictionsManagingPackage);
2203 final int N = policy.mAdminList.size();
2204 for (int i=0; i<N; i++) {
2205 ActiveAdmin ap = policy.mAdminList.get(i);
2207 out.startTag(null, "admin");
2208 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2210 out.endTag(null, "admin");
2214 if (policy.mPasswordOwner >= 0) {
2215 out.startTag(null, "password-owner");
2216 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2217 out.endTag(null, "password-owner");
2220 if (policy.mFailedPasswordAttempts != 0) {
2221 out.startTag(null, "failed-password-attempts");
2222 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2223 out.endTag(null, "failed-password-attempts");
2226 if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2227 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2228 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2229 || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
2230 out.startTag(null, "active-password");
2231 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2232 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2233 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2234 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2235 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2236 out.attribute(null, "numeric", Integer
2237 .toString(policy.mActivePasswordNumeric));
2238 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2239 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2240 out.endTag(null, "active-password");
2243 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2244 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2245 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2246 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2249 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2250 String component = policy.mLockTaskPackages.get(i);
2251 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2252 out.attribute(null, "name", component);
2253 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2256 if (policy.mStatusBarDisabled) {
2257 out.startTag(null, TAG_STATUS_BAR);
2258 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2259 out.endTag(null, TAG_STATUS_BAR);
2262 if (policy.doNotAskCredentialsOnBoot) {
2263 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2264 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2267 for (String id : policy.mAffiliationIds) {
2268 out.startTag(null, TAG_AFFILIATION_ID);
2269 out.attribute(null, "id", id);
2270 out.endTag(null, TAG_AFFILIATION_ID);
2273 if (policy.mAdminBroadcastPending) {
2274 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2275 out.attribute(null, ATTR_VALUE,
2276 Boolean.toString(policy.mAdminBroadcastPending));
2277 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2280 if (policy.mInitBundle != null) {
2281 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2282 policy.mInitBundle.saveToXml(out);
2283 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2286 out.endTag(null, "policies");
2290 FileUtils.sync(stream);
2293 sendChangedNotification(userHandle);
2294 } catch (XmlPullParserException | IOException e) {
2295 Slog.w(LOG_TAG, "failed writing file", e);
2297 if (stream != null) {
2300 } catch (IOException ex) {
2307 private void sendChangedNotification(int userHandle) {
2308 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2309 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2310 long ident = mInjector.binderClearCallingIdentity();
2312 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2314 mInjector.binderRestoreCallingIdentity(ident);
2318 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2319 JournaledFile journal = makeJournaledFile(userHandle);
2320 FileInputStream stream = null;
2321 File file = journal.chooseForRead();
2323 stream = new FileInputStream(file);
2324 XmlPullParser parser = Xml.newPullParser();
2325 parser.setInput(stream, StandardCharsets.UTF_8.name());
2328 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2329 && type != XmlPullParser.START_TAG) {
2331 String tag = parser.getName();
2332 if (!"policies".equals(tag)) {
2333 throw new XmlPullParserException(
2334 "Settings do not start with policies tag: found " + tag);
2337 // Extract the permission provider component name if available
2338 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2339 if (permissionProvider != null) {
2340 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2342 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2343 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2344 policy.mUserSetupComplete = true;
2346 String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2347 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2348 if (deviceProvisioningConfigApplied != null
2349 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2350 policy.mDeviceProvisioningConfigApplied = true;
2352 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2353 if (!TextUtils.isEmpty(provisioningState)) {
2354 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2356 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2357 if (!TextUtils.isEmpty(permissionPolicy)) {
2358 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2360 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2361 ATTR_DELEGATED_CERT_INSTALLER);
2362 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2363 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2365 type = parser.next();
2366 int outerDepth = parser.getDepth();
2367 policy.mLockTaskPackages.clear();
2368 policy.mAdminList.clear();
2369 policy.mAdminMap.clear();
2370 policy.mAffiliationIds.clear();
2371 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2372 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2373 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2376 tag = parser.getName();
2377 if ("admin".equals(tag)) {
2378 String name = parser.getAttributeValue(null, "name");
2380 DeviceAdminInfo dai = findAdmin(
2381 ComponentName.unflattenFromString(name), userHandle,
2382 /* throwForMissionPermission= */ false);
2384 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2386 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2387 + dai.getActivityInfo().applicationInfo.uid + " for user "
2391 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2392 ap.readFromXml(parser);
2393 policy.mAdminMap.put(ap.info.getComponent(), ap);
2395 } catch (RuntimeException e) {
2396 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2398 } else if ("failed-password-attempts".equals(tag)) {
2399 policy.mFailedPasswordAttempts = Integer.parseInt(
2400 parser.getAttributeValue(null, "value"));
2401 } else if ("password-owner".equals(tag)) {
2402 policy.mPasswordOwner = Integer.parseInt(
2403 parser.getAttributeValue(null, "value"));
2404 } else if ("active-password".equals(tag)) {
2405 policy.mActivePasswordQuality = Integer.parseInt(
2406 parser.getAttributeValue(null, "quality"));
2407 policy.mActivePasswordLength = Integer.parseInt(
2408 parser.getAttributeValue(null, "length"));
2409 policy.mActivePasswordUpperCase = Integer.parseInt(
2410 parser.getAttributeValue(null, "uppercase"));
2411 policy.mActivePasswordLowerCase = Integer.parseInt(
2412 parser.getAttributeValue(null, "lowercase"));
2413 policy.mActivePasswordLetters = Integer.parseInt(
2414 parser.getAttributeValue(null, "letters"));
2415 policy.mActivePasswordNumeric = Integer.parseInt(
2416 parser.getAttributeValue(null, "numeric"));
2417 policy.mActivePasswordSymbols = Integer.parseInt(
2418 parser.getAttributeValue(null, "symbols"));
2419 policy.mActivePasswordNonLetter = Integer.parseInt(
2420 parser.getAttributeValue(null, "nonletter"));
2421 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2422 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2423 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2424 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2425 } else if (TAG_STATUS_BAR.equals(tag)) {
2426 policy.mStatusBarDisabled = Boolean.parseBoolean(
2427 parser.getAttributeValue(null, ATTR_DISABLED));
2428 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2429 policy.doNotAskCredentialsOnBoot = true;
2430 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2431 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2432 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2433 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2434 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2435 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2436 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2438 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2439 XmlUtils.skipCurrentTag(parser);
2442 } catch (FileNotFoundException e) {
2443 // Don't be noisy, this is normal if we haven't defined any policies.
2444 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2445 | IndexOutOfBoundsException e) {
2446 Slog.w(LOG_TAG, "failed parsing " + file, e);
2449 if (stream != null) {
2452 } catch (IOException e) {
2456 // Generate a list of admins from the admin map
2457 policy.mAdminList.addAll(policy.mAdminMap.values());
2459 // Validate that what we stored for the password quality matches
2460 // sufficiently what is currently set. Note that this is only
2461 // a sanity check in case the two get out of sync; this should
2462 // never normally happen.
2463 final long identity = mInjector.binderClearCallingIdentity();
2465 int actualPasswordQuality = mLockPatternUtils.getActivePasswordQuality(userHandle);
2466 if (actualPasswordQuality < policy.mActivePasswordQuality) {
2467 Slog.w(LOG_TAG, "Active password quality 0x"
2468 + Integer.toHexString(policy.mActivePasswordQuality)
2469 + " does not match actual quality 0x"
2470 + Integer.toHexString(actualPasswordQuality));
2471 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2472 policy.mActivePasswordLength = 0;
2473 policy.mActivePasswordUpperCase = 0;
2474 policy.mActivePasswordLowerCase = 0;
2475 policy.mActivePasswordLetters = 0;
2476 policy.mActivePasswordNumeric = 0;
2477 policy.mActivePasswordSymbols = 0;
2478 policy.mActivePasswordNonLetter = 0;
2481 mInjector.binderRestoreCallingIdentity(identity);
2484 validatePasswordOwnerLocked(policy);
2485 updateMaximumTimeToLockLocked(userHandle);
2486 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2487 if (policy.mStatusBarDisabled) {
2488 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2492 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2493 long ident = mInjector.binderClearCallingIdentity();
2495 mInjector.getIActivityManager()
2496 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2497 } catch (RemoteException e) {
2498 // Not gonna happen.
2500 mInjector.binderRestoreCallingIdentity(ident);
2504 private void updateDeviceOwnerLocked() {
2505 long ident = mInjector.binderClearCallingIdentity();
2507 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2508 // user id and also protect all other DAs too.
2509 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2510 if (deviceOwnerComponent != null) {
2511 mInjector.getIActivityManager()
2512 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2514 } catch (RemoteException e) {
2515 // Not gonna happen.
2517 mInjector.binderRestoreCallingIdentity(ident);
2521 static void validateQualityConstant(int quality) {
2523 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2524 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2525 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2526 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2527 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2528 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2529 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2530 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2531 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2534 throw new IllegalArgumentException("Invalid quality constant: 0x"
2535 + Integer.toHexString(quality));
2538 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2539 if (policy.mPasswordOwner >= 0) {
2540 boolean haveOwner = false;
2541 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2542 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2548 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2549 + " no longer active; disabling");
2550 policy.mPasswordOwner = -1;
2556 void systemReady(int phase) {
2561 case SystemService.PHASE_LOCK_SETTINGS_READY:
2562 onLockSettingsReady();
2564 case SystemService.PHASE_BOOT_COMPLETED:
2565 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2570 private void onLockSettingsReady() {
2571 getUserData(UserHandle.USER_SYSTEM);
2575 onStartUser(UserHandle.USER_SYSTEM);
2577 // Register an observer for watching for user setup complete.
2578 new SetupContentObserver(mHandler).register();
2579 // Initialize the user setup state, to handle the upgrade case.
2580 updateUserSetupComplete();
2582 List<String> packageList;
2583 synchronized (this) {
2584 packageList = getKeepUninstalledPackagesLocked();
2586 if (packageList != null) {
2587 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2590 synchronized (this) {
2591 // push the force-ephemeral-users policy to the user manager.
2592 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2593 if (deviceOwner != null) {
2594 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2599 private void ensureDeviceOwnerUserStarted() {
2601 synchronized (this) {
2602 if (!mOwners.hasDeviceOwner()) {
2605 userId = mOwners.getDeviceOwnerUserId();
2608 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2610 if (userId != UserHandle.USER_SYSTEM) {
2612 mInjector.getIActivityManager().startUserInBackground(userId);
2614 // STOPSHIP Prevent the DO user from being killed.
2616 } catch (RemoteException e) {
2617 Slog.w(LOG_TAG, "Exception starting user", e);
2622 private void onStartUser(int userId) {
2623 updateScreenCaptureDisabledInWindowManager(userId,
2624 getScreenCaptureDisabled(null, userId));
2625 pushUserRestrictions(userId);
2628 private void cleanUpOldUsers() {
2629 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2631 Set<Integer> usersWithProfileOwners;
2632 Set<Integer> usersWithData;
2633 synchronized(this) {
2634 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2635 usersWithData = new ArraySet<>();
2636 for (int i = 0; i < mUserData.size(); i++) {
2637 usersWithData.add(mUserData.keyAt(i));
2640 List<UserInfo> allUsers = mUserManager.getUsers();
2642 Set<Integer> deletedUsers = new ArraySet<>();
2643 deletedUsers.addAll(usersWithProfileOwners);
2644 deletedUsers.addAll(usersWithData);
2645 for (UserInfo userInfo : allUsers) {
2646 deletedUsers.remove(userInfo.id);
2648 for (Integer userId : deletedUsers) {
2649 removeUserData(userId);
2653 private void handlePasswordExpirationNotification(int userHandle) {
2654 synchronized (this) {
2655 final long now = System.currentTimeMillis();
2657 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2658 userHandle, /* parent */ false);
2659 final int N = admins.size();
2660 for (int i = 0; i < N; i++) {
2661 ActiveAdmin admin = admins.get(i);
2662 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2663 && admin.passwordExpirationTimeout > 0L
2664 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2665 && admin.passwordExpirationDate > 0L) {
2666 sendAdminCommandLocked(admin,
2667 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2670 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2674 private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2676 protected Void doInBackground(Integer... params) {
2677 int userHandle = params[0];
2679 if (userHandle == UserHandle.USER_ALL) {
2680 for (UserInfo userInfo : mUserManager.getUsers(true)) {
2681 manageNotification(userInfo.getUserHandle());
2684 manageNotification(UserHandle.of(userHandle));
2689 private void manageNotification(UserHandle userHandle) {
2690 if (!mUserManager.isUserUnlocked(userHandle)) {
2694 // Call out to KeyChain to check for CAs which are waiting for approval.
2695 final List<String> pendingCertificates;
2697 pendingCertificates = getInstalledCaCertificates(userHandle);
2698 } catch (RemoteException | RuntimeException e) {
2699 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2703 synchronized (DevicePolicyManagerService.this) {
2704 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2706 // Remove deleted certificates. Flush xml if necessary.
2707 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2708 saveSettingsLocked(userHandle.getIdentifier());
2710 // Trim to approved certificates.
2711 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2714 if (pendingCertificates.isEmpty()) {
2715 mInjector.getNotificationManager().cancelAsUser(
2716 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2720 // Build and show a warning notification
2723 int parentUserId = userHandle.getIdentifier();
2724 if (getProfileOwner(userHandle.getIdentifier()) != null) {
2725 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2726 getProfileOwnerName(userHandle.getIdentifier()));
2727 smallIconId = R.drawable.stat_sys_certificate_info;
2728 parentUserId = getProfileParentId(userHandle.getIdentifier());
2729 } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
2730 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2731 getDeviceOwnerName());
2732 smallIconId = R.drawable.stat_sys_certificate_info;
2734 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2735 smallIconId = android.R.drawable.stat_sys_warning;
2738 final int numberOfCertificates = pendingCertificates.size();
2739 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2740 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2741 dialogIntent.setPackage("com.android.settings");
2742 dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
2743 dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
2744 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2745 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
2746 new UserHandle(parentUserId));
2748 final Context userContext;
2750 final String packageName = mContext.getPackageName();
2751 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
2752 } catch (PackageManager.NameNotFoundException e) {
2753 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2756 final Notification noti = new Notification.Builder(userContext)
2757 .setSmallIcon(smallIconId)
2758 .setContentTitle(mContext.getResources().getQuantityText(
2759 R.plurals.ssl_ca_cert_warning, numberOfCertificates))
2760 .setContentText(contentText)
2761 .setContentIntent(notifyIntent)
2762 .setPriority(Notification.PRIORITY_HIGH)
2764 .setColor(mContext.getColor(
2765 com.android.internal.R.color.system_notification_accent_color))
2768 mInjector.getNotificationManager().notifyAsUser(
2769 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2772 private List<String> getInstalledCaCertificates(UserHandle userHandle)
2773 throws RemoteException, RuntimeException {
2774 KeyChainConnection conn = null;
2776 conn = KeyChain.bindAsUser(mContext, userHandle);
2777 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
2778 List<String> result = new ArrayList<>(aliases.size());
2779 for (int i = 0; i < aliases.size(); i++) {
2780 result.add(aliases.get(i).string);
2783 } catch (InterruptedException e) {
2784 Thread.currentThread().interrupt();
2786 } catch (AssertionError e) {
2787 throw new RuntimeException(e);
2797 * @param adminReceiver The admin to add
2798 * @param refreshing true = update an active admin, no error
2801 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2805 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2808 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2809 Bundle onEnableData) {
2810 mContext.enforceCallingOrSelfPermission(
2811 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2812 enforceFullCrossUsersPermission(userHandle);
2814 DevicePolicyData policy = getUserData(userHandle);
2815 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2816 /* throwForMissionPermission= */ true);
2818 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2820 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2821 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2824 synchronized (this) {
2825 long ident = mInjector.binderClearCallingIdentity();
2828 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
2829 throw new IllegalArgumentException("Admin is already added");
2831 if (policy.mRemovingAdmins.contains(adminReceiver)) {
2832 throw new IllegalArgumentException(
2833 "Trying to set an admin which is being removed");
2835 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2836 policy.mAdminMap.put(adminReceiver, newAdmin);
2837 int replaceIndex = -1;
2838 final int N = policy.mAdminList.size();
2839 for (int i=0; i < N; i++) {
2840 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2841 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2846 if (replaceIndex == -1) {
2847 policy.mAdminList.add(newAdmin);
2848 enableIfNecessary(info.getPackageName(), userHandle);
2850 policy.mAdminList.set(replaceIndex, newAdmin);
2852 saveSettingsLocked(userHandle);
2853 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2854 onEnableData, null);
2856 mInjector.binderRestoreCallingIdentity(ident);
2862 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2866 enforceFullCrossUsersPermission(userHandle);
2867 synchronized (this) {
2868 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2873 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2877 enforceFullCrossUsersPermission(userHandle);
2878 synchronized (this) {
2879 DevicePolicyData policyData = getUserData(userHandle);
2880 return policyData.mRemovingAdmins.contains(adminReceiver);
2885 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2889 enforceFullCrossUsersPermission(userHandle);
2890 synchronized (this) {
2891 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2892 if (administrator == null) {
2893 throw new SecurityException("No active admin " + adminReceiver);
2895 return administrator.info.usesPolicy(policyId);
2900 @SuppressWarnings("unchecked")
2901 public List<ComponentName> getActiveAdmins(int userHandle) {
2903 return Collections.EMPTY_LIST;
2906 enforceFullCrossUsersPermission(userHandle);
2907 synchronized (this) {
2908 DevicePolicyData policy = getUserData(userHandle);
2909 final int N = policy.mAdminList.size();
2913 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2914 for (int i=0; i<N; i++) {
2915 res.add(policy.mAdminList.get(i).info.getComponent());
2922 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2926 enforceFullCrossUsersPermission(userHandle);
2927 synchronized (this) {
2928 DevicePolicyData policy = getUserData(userHandle);
2929 final int N = policy.mAdminList.size();
2930 for (int i=0; i<N; i++) {
2931 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2939 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
2943 Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
2944 enforceShell("forceRemoveActiveAdmin");
2945 long ident = mInjector.binderClearCallingIdentity();
2947 if (!isPackageTestOnly(adminReceiver.getPackageName(), userHandle)) {
2948 throw new SecurityException("Attempt to remove non-test admin "
2949 + adminReceiver + " " + userHandle);
2951 // If admin is a device or profile owner tidy that up first.
2952 synchronized (this) {
2953 if (isDeviceOwner(adminReceiver, userHandle)) {
2954 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
2956 if (isProfileOwner(adminReceiver, userHandle)) {
2957 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
2958 userHandle, /* parent */ false);
2959 clearProfileOwnerLocked(admin, userHandle);
2962 // Remove the admin skipping sending the broadcast.
2963 removeAdminArtifacts(adminReceiver, userHandle);
2964 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
2966 mInjector.binderRestoreCallingIdentity(ident);
2970 private boolean isPackageTestOnly(String packageName, int userHandle) {
2971 final ApplicationInfo ai;
2973 ai = mIPackageManager.getApplicationInfo(packageName,
2974 (PackageManager.MATCH_DIRECT_BOOT_AWARE
2975 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
2976 } catch (RemoteException e) {
2977 throw new IllegalStateException(e);
2980 throw new IllegalStateException("Couldn't find package to remove admin "
2981 + packageName + " " + userHandle);
2983 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
2986 private void enforceShell(String method) {
2987 final int callingUid = Binder.getCallingUid();
2988 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
2989 throw new SecurityException("Non-shell user attempted to call " + method);
2994 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
2998 enforceFullCrossUsersPermission(userHandle);
2999 enforceUserUnlocked(userHandle);
3000 synchronized (this) {
3001 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3002 if (admin == null) {
3005 // Active device/profile owners must remain active admins.
3006 if (isDeviceOwner(adminReceiver, userHandle)
3007 || isProfileOwner(adminReceiver, userHandle)) {
3008 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3012 if (admin.getUid() != mInjector.binderGetCallingUid()) {
3013 mContext.enforceCallingOrSelfPermission(
3014 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3016 long ident = mInjector.binderClearCallingIdentity();
3018 removeActiveAdminLocked(adminReceiver, userHandle);
3020 mInjector.binderRestoreCallingIdentity(ident);
3026 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3027 ComponentName profileOwner = getProfileOwner(userHandle);
3028 // Profile challenge is supported on N or newer release.
3029 return profileOwner != null &&
3030 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3034 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3038 Preconditions.checkNotNull(who, "ComponentName is null");
3039 validateQualityConstant(quality);
3041 synchronized (this) {
3042 ActiveAdmin ap = getActiveAdminForCallerLocked(
3043 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3044 if (ap.passwordQuality != quality) {
3045 ap.passwordQuality = quality;
3046 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3052 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3054 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3056 enforceFullCrossUsersPermission(userHandle);
3057 synchronized (this) {
3058 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3061 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3062 return admin != null ? admin.passwordQuality : mode;
3065 // Return the strictest policy across all participating admins.
3066 List<ActiveAdmin> admins =
3067 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3068 final int N = admins.size();
3069 for (int i = 0; i < N; i++) {
3070 ActiveAdmin admin = admins.get(i);
3071 if (mode < admin.passwordQuality) {
3072 mode = admin.passwordQuality;
3079 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3080 int userHandle, boolean parent) {
3081 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3082 // If this user has a separate challenge, only return its restrictions.
3083 return getUserDataUnchecked(userHandle).mAdminList;
3085 // Return all admins for this user and the profiles that are visible from this
3086 // user that do not use a separate work challenge.
3087 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3088 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3089 DevicePolicyData policy = getUserData(userInfo.id);
3090 if (!userInfo.isManagedProfile()) {
3091 admins.addAll(policy.mAdminList);
3093 // For managed profiles, we always include the policies set on the parent
3094 // profile. Additionally, we include the ones set on the managed profile
3095 // if no separate challenge is in place.
3096 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3097 final int N = policy.mAdminList.size();
3098 for (int i = 0; i < N; i++) {
3099 ActiveAdmin admin = policy.mAdminList.get(i);
3100 if (admin.hasParentActiveAdmin()) {
3101 admins.add(admin.getParentActiveAdmin());
3103 if (!hasSeparateChallenge) {
3113 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3114 long ident = mInjector.binderClearCallingIdentity();
3116 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3118 mInjector.binderRestoreCallingIdentity(ident);
3123 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3127 Preconditions.checkNotNull(who, "ComponentName is null");
3128 synchronized (this) {
3129 ActiveAdmin ap = getActiveAdminForCallerLocked(
3130 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3131 if (ap.minimumPasswordLength != length) {
3132 ap.minimumPasswordLength = length;
3133 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3139 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3143 enforceFullCrossUsersPermission(userHandle);
3144 synchronized (this) {
3148 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3149 return admin != null ? admin.minimumPasswordLength : length;
3152 // Return the strictest policy across all participating admins.
3153 List<ActiveAdmin> admins =
3154 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3155 final int N = admins.size();
3156 for (int i = 0; i < N; i++) {
3157 ActiveAdmin admin = admins.get(i);
3158 if (length < admin.minimumPasswordLength) {
3159 length = admin.minimumPasswordLength;
3167 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3171 Preconditions.checkNotNull(who, "ComponentName is null");
3172 synchronized (this) {
3173 ActiveAdmin ap = getActiveAdminForCallerLocked(
3174 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3175 if (ap.passwordHistoryLength != length) {
3176 ap.passwordHistoryLength = length;
3177 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3183 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3187 enforceFullCrossUsersPermission(userHandle);
3188 synchronized (this) {
3192 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3193 return admin != null ? admin.passwordHistoryLength : length;
3196 // Return the strictest policy across all participating admins.
3197 List<ActiveAdmin> admins =
3198 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3199 final int N = admins.size();
3200 for (int i = 0; i < N; i++) {
3201 ActiveAdmin admin = admins.get(i);
3202 if (length < admin.passwordHistoryLength) {
3203 length = admin.passwordHistoryLength;
3212 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3216 Preconditions.checkNotNull(who, "ComponentName is null");
3217 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3218 final int userHandle = mInjector.userHandleGetCallingUserId();
3219 synchronized (this) {
3220 ActiveAdmin ap = getActiveAdminForCallerLocked(
3221 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3222 // Calling this API automatically bumps the expiration date
3223 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3224 ap.passwordExpirationDate = expiration;
3225 ap.passwordExpirationTimeout = timeout;
3227 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3228 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3229 .format(new Date(expiration)));
3231 saveSettingsLocked(userHandle);
3233 // in case this is the first one, set the alarm on the appropriate user.
3234 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3239 * Return a single admin's expiration cycle time, or the min of all cycle times.
3240 * Returns 0 if not configured.
3243 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3247 enforceFullCrossUsersPermission(userHandle);
3248 synchronized (this) {
3252 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3253 return admin != null ? admin.passwordExpirationTimeout : timeout;
3256 // Return the strictest policy across all participating admins.
3257 List<ActiveAdmin> admins =
3258 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3259 final int N = admins.size();
3260 for (int i = 0; i < N; i++) {
3261 ActiveAdmin admin = admins.get(i);
3262 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3263 && timeout > admin.passwordExpirationTimeout)) {
3264 timeout = admin.passwordExpirationTimeout;
3272 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3273 final int userId = UserHandle.getCallingUserId();
3274 List<String> changedProviders = null;
3276 synchronized (this) {
3277 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3278 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3279 if (activeAdmin.crossProfileWidgetProviders == null) {
3280 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3282 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3283 if (!providers.contains(packageName)) {
3284 providers.add(packageName);
3285 changedProviders = new ArrayList<>(providers);
3286 saveSettingsLocked(userId);
3290 if (changedProviders != null) {
3291 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3299 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3300 final int userId = UserHandle.getCallingUserId();
3301 List<String> changedProviders = null;
3303 synchronized (this) {
3304 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3305 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3306 if (activeAdmin.crossProfileWidgetProviders == null) {
3309 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3310 if (providers.remove(packageName)) {
3311 changedProviders = new ArrayList<>(providers);
3312 saveSettingsLocked(userId);
3316 if (changedProviders != null) {
3317 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3325 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3326 synchronized (this) {
3327 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3328 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3329 if (activeAdmin.crossProfileWidgetProviders == null
3330 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3333 if (mInjector.binderIsCallingUidMyUid()) {
3334 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3336 return activeAdmin.crossProfileWidgetProviders;
3342 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3343 * Returns 0 if not configured.
3345 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3349 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3350 return admin != null ? admin.passwordExpirationDate : timeout;
3353 // Return the strictest policy across all participating admins.
3354 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3355 final int N = admins.size();
3356 for (int i = 0; i < N; i++) {
3357 ActiveAdmin admin = admins.get(i);
3358 if (timeout == 0L || (admin.passwordExpirationDate != 0
3359 && timeout > admin.passwordExpirationDate)) {
3360 timeout = admin.passwordExpirationDate;
3367 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3371 enforceFullCrossUsersPermission(userHandle);
3372 synchronized (this) {
3373 return getPasswordExpirationLocked(who, userHandle, parent);
3378 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3382 Preconditions.checkNotNull(who, "ComponentName is null");
3383 synchronized (this) {
3384 ActiveAdmin ap = getActiveAdminForCallerLocked(
3385 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3386 if (ap.minimumPasswordUpperCase != length) {
3387 ap.minimumPasswordUpperCase = length;
3388 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3394 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3398 enforceFullCrossUsersPermission(userHandle);
3399 synchronized (this) {
3403 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3404 return admin != null ? admin.minimumPasswordUpperCase : length;
3407 // Return the strictest policy across all participating admins.
3408 List<ActiveAdmin> admins =
3409 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3410 final int N = admins.size();
3411 for (int i = 0; i < N; i++) {
3412 ActiveAdmin admin = admins.get(i);
3413 if (length < admin.minimumPasswordUpperCase) {
3414 length = admin.minimumPasswordUpperCase;
3422 public void setPasswordMinimumLowerCase(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.minimumPasswordLowerCase != length) {
3428 ap.minimumPasswordLowerCase = length;
3429 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3435 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3439 enforceFullCrossUsersPermission(userHandle);
3440 synchronized (this) {
3444 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3445 return admin != null ? admin.minimumPasswordLowerCase : 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.minimumPasswordLowerCase) {
3455 length = admin.minimumPasswordLowerCase;
3463 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3467 Preconditions.checkNotNull(who, "ComponentName is null");
3468 synchronized (this) {
3469 ActiveAdmin ap = getActiveAdminForCallerLocked(
3470 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3471 if (ap.minimumPasswordLetters != length) {
3472 ap.minimumPasswordLetters = length;
3473 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3479 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3483 enforceFullCrossUsersPermission(userHandle);
3484 synchronized (this) {
3488 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3489 return admin != null ? admin.minimumPasswordLetters : length;
3492 // Return the strictest policy across all participating admins.
3493 List<ActiveAdmin> admins =
3494 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3495 final int N = admins.size();
3496 for (int i = 0; i < N; i++) {
3497 ActiveAdmin admin = admins.get(i);
3498 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3501 if (length < admin.minimumPasswordLetters) {
3502 length = admin.minimumPasswordLetters;
3510 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3514 Preconditions.checkNotNull(who, "ComponentName is null");
3515 synchronized (this) {
3516 ActiveAdmin ap = getActiveAdminForCallerLocked(
3517 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3518 if (ap.minimumPasswordNumeric != length) {
3519 ap.minimumPasswordNumeric = length;
3520 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3526 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3530 enforceFullCrossUsersPermission(userHandle);
3531 synchronized (this) {
3535 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3536 return admin != null ? admin.minimumPasswordNumeric : length;
3539 // Return the strictest policy across all participating admins.
3540 List<ActiveAdmin> admins =
3541 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3542 final int N = admins.size();
3543 for (int i = 0; i < N; i++) {
3544 ActiveAdmin admin = admins.get(i);
3545 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3548 if (length < admin.minimumPasswordNumeric) {
3549 length = admin.minimumPasswordNumeric;
3557 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3561 Preconditions.checkNotNull(who, "ComponentName is null");
3562 synchronized (this) {
3563 ActiveAdmin ap = getActiveAdminForCallerLocked(
3564 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3565 if (ap.minimumPasswordSymbols != length) {
3566 ap.minimumPasswordSymbols = length;
3567 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3573 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3577 enforceFullCrossUsersPermission(userHandle);
3578 synchronized (this) {
3582 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3583 return admin != null ? admin.minimumPasswordSymbols : length;
3586 // Return the strictest policy across all participating admins.
3587 List<ActiveAdmin> admins =
3588 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3589 final int N = admins.size();
3590 for (int i = 0; i < N; i++) {
3591 ActiveAdmin admin = admins.get(i);
3592 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3595 if (length < admin.minimumPasswordSymbols) {
3596 length = admin.minimumPasswordSymbols;
3604 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3608 Preconditions.checkNotNull(who, "ComponentName is null");
3609 synchronized (this) {
3610 ActiveAdmin ap = getActiveAdminForCallerLocked(
3611 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3612 if (ap.minimumPasswordNonLetter != length) {
3613 ap.minimumPasswordNonLetter = length;
3614 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3620 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3624 enforceFullCrossUsersPermission(userHandle);
3625 synchronized (this) {
3629 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3630 return admin != null ? admin.minimumPasswordNonLetter : length;
3633 // Return the strictest policy across all participating admins.
3634 List<ActiveAdmin> admins =
3635 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3636 final int N = admins.size();
3637 for (int i = 0; i < N; i++) {
3638 ActiveAdmin admin = admins.get(i);
3639 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3642 if (length < admin.minimumPasswordNonLetter) {
3643 length = admin.minimumPasswordNonLetter;
3651 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3655 enforceFullCrossUsersPermission(userHandle);
3657 synchronized (this) {
3658 // This API can only be called by an active device admin,
3659 // so try to retrieve it to check that the caller is one.
3660 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3661 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3662 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3667 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3671 enforceFullCrossUsersPermission(userHandle);
3672 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3674 synchronized (this) {
3675 int targetUser = getProfileParentId(userHandle);
3676 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3677 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3681 private boolean isActivePasswordSufficientForUserLocked(
3682 DevicePolicyData policy, int userHandle, boolean parent) {
3683 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
3684 if (policy.mActivePasswordQuality < requiredPasswordQuality) {
3687 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
3688 && policy.mActivePasswordLength < getPasswordMinimumLength(
3689 null, userHandle, parent)) {
3692 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3695 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3696 null, userHandle, parent)
3697 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3698 null, userHandle, parent)
3699 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3700 null, userHandle, parent)
3701 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3702 null, userHandle, parent)
3703 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3704 null, userHandle, parent)
3705 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3706 null, userHandle, parent);
3710 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3711 enforceFullCrossUsersPermission(userHandle);
3712 synchronized (this) {
3713 if (!isCallerWithSystemUid()) {
3714 // This API can only be called by an active device admin,
3715 // so try to retrieve it to check that the caller is one.
3716 getActiveAdminForCallerLocked(
3717 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3720 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3722 return policy.mFailedPasswordAttempts;
3727 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3731 Preconditions.checkNotNull(who, "ComponentName is null");
3732 synchronized (this) {
3733 // This API can only be called by an active device admin,
3734 // so try to retrieve it to check that the caller is one.
3735 getActiveAdminForCallerLocked(
3736 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3737 ActiveAdmin ap = getActiveAdminForCallerLocked(
3738 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3739 if (ap.maximumFailedPasswordsForWipe != num) {
3740 ap.maximumFailedPasswordsForWipe = num;
3741 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3747 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3751 enforceFullCrossUsersPermission(userHandle);
3752 synchronized (this) {
3753 ActiveAdmin admin = (who != null)
3754 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3755 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3756 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3761 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3763 return UserHandle.USER_NULL;
3765 enforceFullCrossUsersPermission(userHandle);
3766 synchronized (this) {
3767 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3768 userHandle, parent);
3769 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3774 * Returns the admin with the strictest policy on maximum failed passwords for:
3776 * <li>this user if it has a separate profile challenge, or
3777 * <li>this user and all profiles that don't have their own challenge otherwise.
3779 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3780 * the primary profile.
3781 * Returns {@code null} if no participating admin has that policy set.
3783 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3784 int userHandle, boolean parent) {
3786 ActiveAdmin strictestAdmin = null;
3788 // Return the strictest policy across all participating admins.
3789 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3790 final int N = admins.size();
3791 for (int i = 0; i < N; i++) {
3792 ActiveAdmin admin = admins.get(i);
3793 if (admin.maximumFailedPasswordsForWipe ==
3794 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3795 continue; // No max number of failed passwords policy set for this profile.
3798 // We always favor the primary profile if several profiles have the same value set.
3799 int userId = admin.getUserHandle().getIdentifier();
3801 count > admin.maximumFailedPasswordsForWipe ||
3802 (count == admin.maximumFailedPasswordsForWipe &&
3803 getUserInfo(userId).isPrimary())) {
3804 count = admin.maximumFailedPasswordsForWipe;
3805 strictestAdmin = admin;
3808 return strictestAdmin;
3811 private UserInfo getUserInfo(@UserIdInt int userId) {
3812 final long token = mInjector.binderClearCallingIdentity();
3814 return mUserManager.getUserInfo(userId);
3816 mInjector.binderRestoreCallingIdentity(token);
3821 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3825 final int callingUid = mInjector.binderGetCallingUid();
3826 final int userHandle = mInjector.userHandleGetCallingUserId();
3828 String password = passwordOrNull != null ? passwordOrNull : "";
3830 // Password resetting to empty/null is not allowed for managed profiles.
3831 if (TextUtils.isEmpty(password)) {
3832 enforceNotManagedProfile(userHandle, "clear the active password");
3836 synchronized (this) {
3837 // If caller has PO (or DO) it can change the password, so see if that's the case first.
3838 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3839 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3841 if (admin != null) {
3842 preN = getTargetSdk(admin.info.getPackageName(),
3843 userHandle) <= android.os.Build.VERSION_CODES.M;
3845 // Otherwise, make sure the caller has any active admin with the right policy.
3846 admin = getActiveAdminForCallerLocked(null,
3847 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3848 preN = getTargetSdk(admin.info.getPackageName(),
3849 userHandle) <= android.os.Build.VERSION_CODES.M;
3851 // As of N, password resetting to empty/null is not allowed anymore.
3852 // TODO Should we allow DO/PO to set an empty password?
3853 if (TextUtils.isEmpty(password)) {
3855 throw new SecurityException("Cannot call with null password");
3857 Slog.e(LOG_TAG, "Cannot call with null password");
3861 // As of N, password cannot be changed by the admin if it is already set.
3862 if (isLockScreenSecureUnchecked(userHandle)) {
3864 throw new SecurityException("Admin cannot change current password");
3866 Slog.e(LOG_TAG, "Admin cannot change current password");
3871 // Do not allow to reset password when current user has a managed profile
3872 if (!isManagedProfile(userHandle)) {
3873 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3874 if (userInfo.isManagedProfile()) {
3876 throw new IllegalStateException(
3877 "Cannot reset password on user has managed profile");
3879 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
3885 // Do not allow to reset password when user is locked
3886 if (!mUserManager.isUserUnlocked(userHandle)) {
3888 throw new IllegalStateException("Cannot reset password when user is locked");
3890 Slog.e(LOG_TAG, "Cannot reset password when user is locked");
3895 quality = getPasswordQuality(null, userHandle, /* parent */ false);
3896 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
3897 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3899 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
3900 int realQuality = LockPatternUtils.computePasswordQuality(password);
3901 if (realQuality < quality
3902 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3903 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
3904 + Integer.toHexString(realQuality)
3905 + " does not meet required quality 0x"
3906 + Integer.toHexString(quality));
3909 quality = Math.max(realQuality, quality);
3911 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
3912 if (password.length() < length) {
3913 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
3914 + " does not meet required length " + length);
3917 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3924 for (int i = 0; i < password.length(); i++) {
3925 char c = password.charAt(i);
3926 if (c >= 'A' && c <= 'Z') {
3929 } else if (c >= 'a' && c <= 'z') {
3932 } else if (c >= '0' && c <= '9') {
3940 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
3941 if(letters < neededLetters) {
3942 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
3943 + " does not meet required number of letters " + neededLetters);
3946 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
3947 if (numbers < neededNumbers) {
3948 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
3949 + " does not meet required number of numerical digits "
3953 int neededLowerCase = getPasswordMinimumLowerCase(
3954 null, userHandle, /* parent */ false);
3955 if (lowercase < neededLowerCase) {
3956 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
3957 + " does not meet required number of lowercase letters "
3961 int neededUpperCase = getPasswordMinimumUpperCase(
3962 null, userHandle, /* parent */ false);
3963 if (uppercase < neededUpperCase) {
3964 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
3965 + " does not meet required number of uppercase letters "
3969 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
3970 if (symbols < neededSymbols) {
3971 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
3972 + " does not meet required number of special symbols " + neededSymbols);
3975 int neededNonLetter = getPasswordMinimumNonLetter(
3976 null, userHandle, /* parent */ false);
3977 if (nonletter < neededNonLetter) {
3978 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
3979 + " does not meet required number of non-letter characters "
3986 DevicePolicyData policy = getUserData(userHandle);
3987 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
3988 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
3992 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
3993 boolean doNotAskCredentialsOnBoot =
3994 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
3995 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
3996 setDoNotAskCredentialsOnBoot();
3999 // Don't do this with the lock held, because it is going to call
4000 // back in to the service.
4001 final long ident = mInjector.binderClearCallingIdentity();
4003 if (!TextUtils.isEmpty(password)) {
4004 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4006 mLockPatternUtils.clearLock(userHandle);
4008 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4010 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4011 UserHandle.USER_ALL);
4013 synchronized (this) {
4014 int newOwner = requireEntry ? callingUid : -1;
4015 if (policy.mPasswordOwner != newOwner) {
4016 policy.mPasswordOwner = newOwner;
4017 saveSettingsLocked(userHandle);
4021 mInjector.binderRestoreCallingIdentity(ident);
4027 private boolean isLockScreenSecureUnchecked(int userId) {
4028 long ident = mInjector.binderClearCallingIdentity();
4030 return mLockPatternUtils.isSecure(userId);
4032 mInjector.binderRestoreCallingIdentity(ident);
4036 private void setDoNotAskCredentialsOnBoot() {
4037 synchronized (this) {
4038 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4039 if (!policyData.doNotAskCredentialsOnBoot) {
4040 policyData.doNotAskCredentialsOnBoot = true;
4041 saveSettingsLocked(UserHandle.USER_SYSTEM);
4047 public boolean getDoNotAskCredentialsOnBoot() {
4048 mContext.enforceCallingOrSelfPermission(
4049 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4050 synchronized (this) {
4051 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4052 return policyData.doNotAskCredentialsOnBoot;
4057 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4061 Preconditions.checkNotNull(who, "ComponentName is null");
4062 final int userHandle = mInjector.userHandleGetCallingUserId();
4063 synchronized (this) {
4064 ActiveAdmin ap = getActiveAdminForCallerLocked(
4065 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4066 if (ap.maximumTimeToUnlock != timeMs) {
4067 ap.maximumTimeToUnlock = timeMs;
4068 saveSettingsLocked(userHandle);
4069 updateMaximumTimeToLockLocked(userHandle);
4074 void updateMaximumTimeToLockLocked(int userHandle) {
4075 // Calculate the min timeout for all profiles - including the ones with a separate
4076 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4077 // challenge only and keep the screen on. However there is no easy way of doing that at the
4078 // moment so we set the screen off timeout regardless of whether it affects the parent user
4079 // or the profile challenge only.
4080 long timeMs = Long.MAX_VALUE;
4081 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4082 for (int profileId : profileIds) {
4083 DevicePolicyData policy = getUserDataUnchecked(profileId);
4084 final int N = policy.mAdminList.size();
4085 for (int i = 0; i < N; i++) {
4086 ActiveAdmin admin = policy.mAdminList.get(i);
4087 if (admin.maximumTimeToUnlock > 0
4088 && timeMs > admin.maximumTimeToUnlock) {
4089 timeMs = admin.maximumTimeToUnlock;
4091 // If userInfo.id is a managed profile, we also need to look at
4092 // the policies set on the parent.
4093 if (admin.hasParentActiveAdmin()) {
4094 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4095 if (parentAdmin.maximumTimeToUnlock > 0
4096 && timeMs > parentAdmin.maximumTimeToUnlock) {
4097 timeMs = parentAdmin.maximumTimeToUnlock;
4103 // We only store the last maximum time to lock on the parent profile. So if calling from a
4104 // managed profile, retrieve the policy for the parent.
4105 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4106 if (policy.mLastMaximumTimeToLock == timeMs) {
4109 policy.mLastMaximumTimeToLock = timeMs;
4111 final long ident = mInjector.binderClearCallingIdentity();
4113 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4114 // Make sure KEEP_SCREEN_ON is disabled, since that
4115 // would allow bypassing of the maximum time to lock.
4116 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4119 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4120 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4122 mInjector.binderRestoreCallingIdentity(ident);
4127 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4131 enforceFullCrossUsersPermission(userHandle);
4132 synchronized (this) {
4134 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4135 return admin != null ? admin.maximumTimeToUnlock : 0;
4137 // Return the strictest policy across all participating admins.
4138 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4139 userHandle, parent);
4140 return getMaximumTimeToLockPolicyFromAdmins(admins);
4145 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4149 enforceFullCrossUsersPermission(userHandle);
4150 synchronized (this) {
4151 // All admins for this user.
4152 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4153 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4154 DevicePolicyData policy = getUserData(userInfo.id);
4155 admins.addAll(policy.mAdminList);
4156 // If it is a managed profile, it may have parent active admins
4157 if (userInfo.isManagedProfile()) {
4158 for (ActiveAdmin admin : policy.mAdminList) {
4159 if (admin.hasParentActiveAdmin()) {
4160 admins.add(admin.getParentActiveAdmin());
4165 return getMaximumTimeToLockPolicyFromAdmins(admins);
4169 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4171 final int N = admins.size();
4172 for (int i = 0; i < N; i++) {
4173 ActiveAdmin admin = admins.get(i);
4175 time = admin.maximumTimeToUnlock;
4176 } else if (admin.maximumTimeToUnlock != 0
4177 && time > admin.maximumTimeToUnlock) {
4178 time = admin.maximumTimeToUnlock;
4185 public void lockNow(boolean parent) {
4189 synchronized (this) {
4190 // This API can only be called by an active device admin,
4191 // so try to retrieve it to check that the caller is one.
4192 getActiveAdminForCallerLocked(
4193 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4195 int userToLock = mInjector.userHandleGetCallingUserId();
4197 // Unless this is a managed profile with work challenge enabled, lock all users.
4198 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4199 userToLock = UserHandle.USER_ALL;
4201 final long ident = mInjector.binderClearCallingIdentity();
4203 mLockPatternUtils.requireStrongAuth(
4204 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4205 if (userToLock == UserHandle.USER_ALL) {
4206 // Power off the display
4207 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4208 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4209 mInjector.getIWindowManager().lockNow(null);
4211 } catch (RemoteException e) {
4213 mInjector.binderRestoreCallingIdentity(ident);
4219 public void enforceCanManageCaCerts(ComponentName who) {
4221 if (!isCallerDelegatedCertInstaller()) {
4222 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4225 synchronized (this) {
4226 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4231 private void enforceCanManageInstalledKeys(ComponentName who) {
4233 if (!isCallerDelegatedCertInstaller()) {
4234 throw new SecurityException("who == null, but caller is not cert installer");
4237 synchronized (this) {
4238 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4243 private boolean isCallerDelegatedCertInstaller() {
4244 final int callingUid = mInjector.binderGetCallingUid();
4245 final int userHandle = UserHandle.getUserId(callingUid);
4246 synchronized (this) {
4247 final DevicePolicyData policy = getUserData(userHandle);
4248 if (policy.mDelegatedCertInstallerPackage == null) {
4253 int uid = mContext.getPackageManager().getPackageUidAsUser(
4254 policy.mDelegatedCertInstallerPackage, userHandle);
4255 return uid == callingUid;
4256 } catch (NameNotFoundException e) {
4263 public boolean approveCaCert(String alias, int userId, boolean approval) {
4264 enforceManageUsers();
4265 synchronized (this) {
4266 Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4267 boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4271 saveSettingsLocked(userId);
4273 new MonitoringCertNotificationTask().execute(userId);
4278 public boolean isCaCertApproved(String alias, int userId) {
4279 enforceManageUsers();
4280 synchronized (this) {
4281 return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4285 private void removeCaApprovalsIfNeeded(int userId) {
4286 for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4287 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4288 if (userInfo.isManagedProfile()){
4289 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4292 synchronized (this) {
4293 getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4294 saveSettingsLocked(userInfo.id);
4297 new MonitoringCertNotificationTask().execute(userInfo.id);
4303 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4304 enforceCanManageCaCerts(admin);
4308 X509Certificate cert = parseCert(certBuffer);
4309 pemCert = Credentials.convertToPem(cert);
4310 } catch (CertificateException ce) {
4311 Log.e(LOG_TAG, "Problem converting cert", ce);
4313 } catch (IOException ioe) {
4314 Log.e(LOG_TAG, "Problem reading cert", ioe);
4318 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4319 final long id = mInjector.binderClearCallingIdentity();
4321 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4323 keyChainConnection.getService().installCaCertificate(pemCert);
4325 } catch (RemoteException e) {
4326 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4328 keyChainConnection.close();
4330 } catch (InterruptedException e1) {
4331 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4332 Thread.currentThread().interrupt();
4334 mInjector.binderRestoreCallingIdentity(id);
4339 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4340 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4341 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4346 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4347 enforceCanManageCaCerts(admin);
4349 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4350 final long id = mInjector.binderClearCallingIdentity();
4352 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4354 for (int i = 0 ; i < aliases.length; i++) {
4355 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4357 } catch (RemoteException e) {
4358 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4360 keyChainConnection.close();
4362 } catch (InterruptedException ie) {
4363 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4364 Thread.currentThread().interrupt();
4366 mInjector.binderRestoreCallingIdentity(id);
4371 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4372 String alias, boolean requestAccess) {
4373 enforceCanManageInstalledKeys(who);
4375 final int callingUid = mInjector.binderGetCallingUid();
4376 final long id = mInjector.binderClearCallingIdentity();
4378 final KeyChainConnection keyChainConnection =
4379 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4381 IKeyChainService keyChain = keyChainConnection.getService();
4382 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4385 if (requestAccess) {
4386 keyChain.setGrant(callingUid, alias, true);
4389 } catch (RemoteException e) {
4390 Log.e(LOG_TAG, "Installing certificate", e);
4392 keyChainConnection.close();
4394 } catch (InterruptedException e) {
4395 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4396 Thread.currentThread().interrupt();
4398 mInjector.binderRestoreCallingIdentity(id);
4404 public boolean removeKeyPair(ComponentName who, String alias) {
4405 enforceCanManageInstalledKeys(who);
4407 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4408 final long id = Binder.clearCallingIdentity();
4410 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4412 IKeyChainService keyChain = keyChainConnection.getService();
4413 return keyChain.removeKeyPair(alias);
4414 } catch (RemoteException e) {
4415 Log.e(LOG_TAG, "Removing keypair", e);
4417 keyChainConnection.close();
4419 } catch (InterruptedException e) {
4420 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4421 Thread.currentThread().interrupt();
4423 Binder.restoreCallingIdentity(id);
4429 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4430 final IBinder response) {
4431 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4432 if (!isCallerWithSystemUid()) {
4436 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4437 // If there is a profile owner, redirect to that; otherwise query the device owner.
4438 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4439 if (aliasChooser == null && caller.isSystem()) {
4440 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4441 if (deviceOwnerAdmin != null) {
4442 aliasChooser = deviceOwnerAdmin.info.getComponent();
4445 if (aliasChooser == null) {
4446 sendPrivateKeyAliasResponse(null, response);
4450 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4451 intent.setComponent(aliasChooser);
4452 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4453 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4454 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4455 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4456 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4458 final long id = mInjector.binderClearCallingIdentity();
4460 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4462 public void onReceive(Context context, Intent intent) {
4463 final String chosenAlias = getResultData();
4464 sendPrivateKeyAliasResponse(chosenAlias, response);
4466 }, null, Activity.RESULT_OK, null, null);
4468 mInjector.binderRestoreCallingIdentity(id);
4472 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4473 final IKeyChainAliasCallback keyChainAliasResponse =
4474 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4475 new AsyncTask<Void, Void, Void>() {
4477 protected Void doInBackground(Void... unused) {
4479 keyChainAliasResponse.alias(alias);
4480 } catch (Exception e) {
4481 // Catch everything (not just RemoteException): caller could throw a
4482 // RuntimeException back across processes.
4483 Log.e(LOG_TAG, "error while responding to callback", e);
4491 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4492 throws SecurityException {
4493 int userHandle = UserHandle.getCallingUserId();
4494 synchronized (this) {
4495 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4496 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4497 if (installerPackage != null &&
4498 !isPackageInstalledForUser(installerPackage, userHandle)) {
4499 throw new IllegalArgumentException("Package " + installerPackage
4500 + " is not installed on the current user");
4503 DevicePolicyData policy = getUserData(userHandle);
4504 policy.mDelegatedCertInstallerPackage = installerPackage;
4505 saveSettingsLocked(userHandle);
4510 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4511 int userHandle = UserHandle.getCallingUserId();
4512 synchronized (this) {
4513 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4514 DevicePolicyData policy = getUserData(userHandle);
4515 return policy.mDelegatedCertInstallerPackage;
4520 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4521 * not installed and therefore not available.
4523 * @throws SecurityException if the caller is not a profile or device owner.
4524 * @throws UnsupportedOperationException if the package does not support being set as always-on.
4527 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4528 throws SecurityException {
4529 synchronized (this) {
4530 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4533 final int userId = mInjector.userHandleGetCallingUserId();
4534 final long token = mInjector.binderClearCallingIdentity();
4536 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4539 ConnectivityManager connectivityManager = (ConnectivityManager)
4540 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4541 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4542 throw new UnsupportedOperationException();
4545 mInjector.binderRestoreCallingIdentity(token);
4551 public String getAlwaysOnVpnPackage(ComponentName admin)
4552 throws SecurityException {
4553 synchronized (this) {
4554 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4557 final int userId = mInjector.userHandleGetCallingUserId();
4558 final long token = mInjector.binderClearCallingIdentity();
4560 ConnectivityManager connectivityManager = (ConnectivityManager)
4561 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4562 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4564 mInjector.binderRestoreCallingIdentity(token);
4568 private void wipeDataLocked(boolean wipeExtRequested, String reason) {
4569 if (wipeExtRequested) {
4570 StorageManager sm = (StorageManager) mContext.getSystemService(
4571 Context.STORAGE_SERVICE);
4572 sm.wipeAdoptableDisks();
4575 RecoverySystem.rebootWipeUserData(mContext, reason);
4576 } catch (IOException | SecurityException e) {
4577 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4582 public void wipeData(int flags) {
4586 final int userHandle = mInjector.userHandleGetCallingUserId();
4587 enforceFullCrossUsersPermission(userHandle);
4588 synchronized (this) {
4589 // This API can only be called by an active device admin,
4590 // so try to retrieve it to check that the caller is one.
4591 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4592 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4594 final String source = admin.info.getComponent().flattenToShortString();
4596 long ident = mInjector.binderClearCallingIdentity();
4598 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4599 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4600 throw new SecurityException(
4601 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4603 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4604 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4605 if (manager != null) {
4609 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4610 wipeDeviceOrUserLocked(wipeExtRequested, userHandle,
4611 "DevicePolicyManager.wipeData() from " + source);
4613 mInjector.binderRestoreCallingIdentity(ident);
4618 private void wipeDeviceOrUserLocked(boolean wipeExtRequested, final int userHandle, String reason) {
4619 if (userHandle == UserHandle.USER_SYSTEM) {
4620 wipeDataLocked(wipeExtRequested, reason);
4622 mHandler.post(new Runnable() {
4626 IActivityManager am = mInjector.getIActivityManager();
4627 if (am.getCurrentUser().id == userHandle) {
4628 am.switchUser(UserHandle.USER_SYSTEM);
4631 boolean isManagedProfile = isManagedProfile(userHandle);
4632 if (!mUserManager.removeUser(userHandle)) {
4633 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4634 } else if (isManagedProfile) {
4635 sendWipeProfileNotification();
4637 } catch (RemoteException re) {
4645 private void sendWipeProfileNotification() {
4646 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4647 Notification notification = new Notification.Builder(mContext)
4648 .setSmallIcon(android.R.drawable.stat_sys_warning)
4649 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4650 .setContentText(contentText)
4651 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4652 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4654 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4657 private void clearWipeProfileNotification() {
4658 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4662 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4666 enforceFullCrossUsersPermission(userHandle);
4667 mContext.enforceCallingOrSelfPermission(
4668 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4670 synchronized (this) {
4671 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4672 if (admin == null) {
4673 result.sendResult(null);
4676 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4677 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4678 intent.setComponent(admin.info.getComponent());
4679 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4680 null, new BroadcastReceiver() {
4682 public void onReceive(Context context, Intent intent) {
4683 result.sendResult(getResultExtras(false));
4685 }, null, Activity.RESULT_OK, null, null);
4690 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4691 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4695 enforceFullCrossUsersPermission(userHandle);
4697 // Managed Profile password can only be changed when it has a separate challenge.
4698 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4699 enforceNotManagedProfile(userHandle, "set the active password");
4702 mContext.enforceCallingOrSelfPermission(
4703 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4704 validateQualityConstant(quality);
4706 DevicePolicyData policy = getUserData(userHandle);
4708 long ident = mInjector.binderClearCallingIdentity();
4710 synchronized (this) {
4711 policy.mActivePasswordQuality = quality;
4712 policy.mActivePasswordLength = length;
4713 policy.mActivePasswordLetters = letters;
4714 policy.mActivePasswordLowerCase = lowercase;
4715 policy.mActivePasswordUpperCase = uppercase;
4716 policy.mActivePasswordNumeric = numbers;
4717 policy.mActivePasswordSymbols = symbols;
4718 policy.mActivePasswordNonLetter = nonletter;
4719 policy.mFailedPasswordAttempts = 0;
4720 saveSettingsLocked(userHandle);
4721 updatePasswordExpirationsLocked(userHandle);
4722 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
4724 // Send a broadcast to each profile using this password as its primary unlock.
4725 sendAdminCommandForLockscreenPoliciesLocked(
4726 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4727 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
4729 removeCaApprovalsIfNeeded(userHandle);
4731 mInjector.binderRestoreCallingIdentity(ident);
4736 * Called any time the device password is updated. Resets all password expiration clocks.
4738 private void updatePasswordExpirationsLocked(int userHandle) {
4739 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4740 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4741 userHandle, /* parent */ false);
4742 final int N = admins.size();
4743 for (int i = 0; i < N; i++) {
4744 ActiveAdmin admin = admins.get(i);
4745 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4746 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4747 long timeout = admin.passwordExpirationTimeout;
4748 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4749 admin.passwordExpirationDate = expiration;
4752 for (int affectedUserId : affectedUserIds) {
4753 saveSettingsLocked(affectedUserId);
4758 public void reportFailedPasswordAttempt(int userHandle) {
4759 enforceFullCrossUsersPermission(userHandle);
4760 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4761 enforceNotManagedProfile(userHandle,
4762 "report failed password attempt if separate profile challenge is not in place");
4764 mContext.enforceCallingOrSelfPermission(
4765 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4767 final long ident = mInjector.binderClearCallingIdentity();
4769 boolean wipeData = false;
4771 synchronized (this) {
4772 DevicePolicyData policy = getUserData(userHandle);
4773 policy.mFailedPasswordAttempts++;
4774 saveSettingsLocked(userHandle);
4776 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4777 userHandle, /* parent */ false);
4778 int max = strictestAdmin != null
4779 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4780 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4781 // Wipe the user/profile associated with the policy that was violated. This
4782 // is not necessarily calling user: if the policy that fired was from a
4783 // managed profile rather than the main user profile, we wipe former only.
4785 identifier = strictestAdmin.getUserHandle().getIdentifier();
4788 sendAdminCommandForLockscreenPoliciesLocked(
4789 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
4790 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4794 // Call without holding lock.
4795 wipeDeviceOrUserLocked(false, identifier,
4796 "reportFailedPasswordAttempt()");
4799 mInjector.binderRestoreCallingIdentity(ident);
4802 if (mInjector.securityLogIsLoggingEnabled()) {
4803 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4804 /*method strength*/ 1);
4809 public void reportSuccessfulPasswordAttempt(int userHandle) {
4810 enforceFullCrossUsersPermission(userHandle);
4811 mContext.enforceCallingOrSelfPermission(
4812 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4814 synchronized (this) {
4815 DevicePolicyData policy = getUserData(userHandle);
4816 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
4817 long ident = mInjector.binderClearCallingIdentity();
4819 policy.mFailedPasswordAttempts = 0;
4820 policy.mPasswordOwner = -1;
4821 saveSettingsLocked(userHandle);
4823 sendAdminCommandForLockscreenPoliciesLocked(
4824 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
4825 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4828 mInjector.binderRestoreCallingIdentity(ident);
4833 if (mInjector.securityLogIsLoggingEnabled()) {
4834 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4835 /*method strength*/ 1);
4840 public void reportFailedFingerprintAttempt(int userHandle) {
4841 enforceFullCrossUsersPermission(userHandle);
4842 mContext.enforceCallingOrSelfPermission(
4843 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4844 if (mInjector.securityLogIsLoggingEnabled()) {
4845 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4846 /*method strength*/ 0);
4851 public void reportSuccessfulFingerprintAttempt(int userHandle) {
4852 enforceFullCrossUsersPermission(userHandle);
4853 mContext.enforceCallingOrSelfPermission(
4854 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4855 if (mInjector.securityLogIsLoggingEnabled()) {
4856 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4857 /*method strength*/ 0);
4862 public void reportKeyguardDismissed(int userHandle) {
4863 enforceFullCrossUsersPermission(userHandle);
4864 mContext.enforceCallingOrSelfPermission(
4865 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4867 if (mInjector.securityLogIsLoggingEnabled()) {
4868 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
4873 public void reportKeyguardSecured(int userHandle) {
4874 enforceFullCrossUsersPermission(userHandle);
4875 mContext.enforceCallingOrSelfPermission(
4876 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4878 if (mInjector.securityLogIsLoggingEnabled()) {
4879 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
4884 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
4885 String exclusionList) {
4889 synchronized(this) {
4890 Preconditions.checkNotNull(who, "ComponentName is null");
4892 // Only check if system user has set global proxy. We don't allow other users to set it.
4893 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4894 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4895 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
4897 // Scan through active admins and find if anyone has already
4898 // set the global proxy.
4899 Set<ComponentName> compSet = policy.mAdminMap.keySet();
4900 for (ComponentName component : compSet) {
4901 ActiveAdmin ap = policy.mAdminMap.get(component);
4902 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
4903 // Another admin already sets the global proxy
4904 // Return it to the caller.
4909 // If the user is not system, don't set the global proxy. Fail silently.
4910 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
4911 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
4912 + UserHandle.getCallingUserId() + " is not permitted.");
4915 if (proxySpec == null) {
4916 admin.specifiesGlobalProxy = false;
4917 admin.globalProxySpec = null;
4918 admin.globalProxyExclusionList = null;
4921 admin.specifiesGlobalProxy = true;
4922 admin.globalProxySpec = proxySpec;
4923 admin.globalProxyExclusionList = exclusionList;
4926 // Reset the global proxy accordingly
4927 // Do this using system permissions, as apps cannot write to secure settings
4928 long origId = mInjector.binderClearCallingIdentity();
4930 resetGlobalProxyLocked(policy);
4932 mInjector.binderRestoreCallingIdentity(origId);
4939 public ComponentName getGlobalProxyAdmin(int userHandle) {
4943 enforceFullCrossUsersPermission(userHandle);
4944 synchronized(this) {
4945 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4946 // Scan through active admins and find if anyone has already
4947 // set the global proxy.
4948 final int N = policy.mAdminList.size();
4949 for (int i = 0; i < N; i++) {
4950 ActiveAdmin ap = policy.mAdminList.get(i);
4951 if (ap.specifiesGlobalProxy) {
4952 // Device admin sets the global proxy
4953 // Return it to the caller.
4954 return ap.info.getComponent();
4958 // No device admin sets the global proxy.
4963 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
4964 synchronized (this) {
4965 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4967 long token = mInjector.binderClearCallingIdentity();
4969 ConnectivityManager connectivityManager = (ConnectivityManager)
4970 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4971 connectivityManager.setGlobalProxy(proxyInfo);
4973 mInjector.binderRestoreCallingIdentity(token);
4977 private void resetGlobalProxyLocked(DevicePolicyData policy) {
4978 final int N = policy.mAdminList.size();
4979 for (int i = 0; i < N; i++) {
4980 ActiveAdmin ap = policy.mAdminList.get(i);
4981 if (ap.specifiesGlobalProxy) {
4982 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
4986 // No device admins defining global proxies - reset global proxy settings to none
4987 saveGlobalProxyLocked(null, null);
4990 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
4991 if (exclusionList == null) {
4994 if (proxySpec == null) {
4997 // Remove white spaces
4998 proxySpec = proxySpec.trim();
4999 String data[] = proxySpec.split(":");
5000 int proxyPort = 8080;
5001 if (data.length > 1) {
5003 proxyPort = Integer.parseInt(data[1]);
5004 } catch (NumberFormatException e) {}
5006 exclusionList = exclusionList.trim();
5008 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5009 if (!proxyProperties.isValid()) {
5010 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5013 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5014 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5015 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5020 * Set the storage encryption request for a single admin. Returns the new total request
5021 * status (for all admins).
5024 public int setStorageEncryption(ComponentName who, boolean encrypt) {
5026 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5028 Preconditions.checkNotNull(who, "ComponentName is null");
5029 final int userHandle = UserHandle.getCallingUserId();
5030 synchronized (this) {
5031 // Check for permissions
5032 // Only system user can set storage encryption
5033 if (userHandle != UserHandle.USER_SYSTEM) {
5034 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5035 + UserHandle.getCallingUserId() + " is not permitted.");
5039 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5040 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5042 // Quick exit: If the filesystem does not support encryption, we can exit early.
5043 if (!isEncryptionSupported()) {
5044 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5047 // (1) Record the value for the admin so it's sticky
5048 if (ap.encryptionRequested != encrypt) {
5049 ap.encryptionRequested = encrypt;
5050 saveSettingsLocked(userHandle);
5053 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5054 // (2) Compute "max" for all admins
5055 boolean newRequested = false;
5056 final int N = policy.mAdminList.size();
5057 for (int i = 0; i < N; i++) {
5058 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5061 // Notify OS of new request
5062 setEncryptionRequested(newRequested);
5064 // Return the new global request status
5066 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5067 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5072 * Get the current storage encryption request status for a given admin, or aggregate of all
5076 public boolean getStorageEncryption(ComponentName who, int userHandle) {
5080 enforceFullCrossUsersPermission(userHandle);
5081 synchronized (this) {
5082 // Check for permissions if a particular caller is specified
5084 // When checking for a single caller, status is based on caller's request
5085 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5086 return ap != null ? ap.encryptionRequested : false;
5089 // If no particular caller is specified, return the aggregate set of requests.
5090 // This is short circuited by returning true on the first hit.
5091 DevicePolicyData policy = getUserData(userHandle);
5092 final int N = policy.mAdminList.size();
5093 for (int i = 0; i < N; i++) {
5094 if (policy.mAdminList.get(i).encryptionRequested) {
5103 * Get the current encryption status of the device.
5106 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5108 // Ok to return current status.
5110 enforceFullCrossUsersPermission(userHandle);
5112 // It's not critical here, but let's make sure the package name is correct, in case
5113 // we start using it for different purposes.
5114 ensureCallerPackage(callerPackage);
5116 final ApplicationInfo ai;
5118 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5119 } catch (RemoteException e) {
5120 throw new SecurityException(e);
5123 boolean legacyApp = false;
5124 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5128 final int rawStatus = getEncryptionStatus();
5129 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5130 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5136 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
5138 private boolean isEncryptionSupported() {
5139 // Note, this can be implemented as
5140 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5141 // But is provided as a separate internal method if there's a faster way to do a
5142 // simple check for supported-or-not.
5143 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5147 * Hook to low-levels: Reporting the current status of encryption.
5148 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5149 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5150 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5151 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5152 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5154 private int getEncryptionStatus() {
5155 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5156 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5157 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5158 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5159 } else if (mInjector.storageManagerIsEncrypted()) {
5160 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5161 } else if (mInjector.storageManagerIsEncryptable()) {
5162 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5164 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5169 * Hook to low-levels: If needed, record the new admin setting for encryption.
5171 private void setEncryptionRequested(boolean encrypt) {
5175 * Set whether the screen capture is disabled for the user managed by the specified admin.
5178 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5182 Preconditions.checkNotNull(who, "ComponentName is null");
5183 final int userHandle = UserHandle.getCallingUserId();
5184 synchronized (this) {
5185 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5186 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5187 if (ap.disableScreenCapture != disabled) {
5188 ap.disableScreenCapture = disabled;
5189 saveSettingsLocked(userHandle);
5190 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5196 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5197 * active admin (if given admin is null).
5200 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5204 synchronized (this) {
5206 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5207 return (admin != null) ? admin.disableScreenCapture : false;
5210 DevicePolicyData policy = getUserData(userHandle);
5211 final int N = policy.mAdminList.size();
5212 for (int i = 0; i < N; i++) {
5213 ActiveAdmin admin = policy.mAdminList.get(i);
5214 if (admin.disableScreenCapture) {
5222 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5223 final boolean disabled) {
5224 mHandler.post(new Runnable() {
5228 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5229 } catch (RemoteException e) {
5230 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5237 * Set whether auto time is required by the specified admin (must be device owner).
5240 public void setAutoTimeRequired(ComponentName who, boolean required) {
5244 Preconditions.checkNotNull(who, "ComponentName is null");
5245 final int userHandle = UserHandle.getCallingUserId();
5246 synchronized (this) {
5247 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5248 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5249 if (admin.requireAutoTime != required) {
5250 admin.requireAutoTime = required;
5251 saveSettingsLocked(userHandle);
5255 // Turn AUTO_TIME on in settings if it is required
5257 long ident = mInjector.binderClearCallingIdentity();
5259 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5261 mInjector.binderRestoreCallingIdentity(ident);
5267 * Returns whether or not auto time is required by the device owner.
5270 public boolean getAutoTimeRequired() {
5274 synchronized (this) {
5275 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5276 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5281 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5285 Preconditions.checkNotNull(who, "ComponentName is null");
5286 // Allow setting this policy to true only if there is a split system user.
5287 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5288 throw new UnsupportedOperationException(
5289 "Cannot force ephemeral users on systems without split system user.");
5291 boolean removeAllUsers = false;
5292 synchronized (this) {
5293 final ActiveAdmin deviceOwner =
5294 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5295 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5296 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5297 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5298 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5299 removeAllUsers = forceEphemeralUsers;
5302 if (removeAllUsers) {
5303 long identitity = mInjector.binderClearCallingIdentity();
5305 mUserManagerInternal.removeAllUsers();
5307 mInjector.binderRestoreCallingIdentity(identitity);
5313 public boolean getForceEphemeralUsers(ComponentName who) {
5317 Preconditions.checkNotNull(who, "ComponentName is null");
5318 synchronized (this) {
5319 final ActiveAdmin deviceOwner =
5320 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5321 return deviceOwner.forceEphemeralUsers;
5325 private boolean isDeviceOwnerManagedSingleUserDevice() {
5326 synchronized (this) {
5327 if (!mOwners.hasDeviceOwner()) {
5331 final long callingIdentity = mInjector.binderClearCallingIdentity();
5333 if (mInjector.userManagerIsSplitSystemUser()) {
5334 // In split system user mode, only allow the case where the device owner is managing
5335 // the only non-system user of the device
5336 return (mUserManager.getUserCount() == 2
5337 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5339 return mUserManager.getUserCount() == 1;
5342 mInjector.binderRestoreCallingIdentity(callingIdentity);
5346 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5347 synchronized (this) {
5348 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5350 if (!isDeviceOwnerManagedSingleUserDevice()) {
5351 throw new SecurityException(
5352 "There should only be one user, managed by Device Owner");
5357 public boolean requestBugreport(ComponentName who) {
5361 Preconditions.checkNotNull(who, "ComponentName is null");
5362 ensureDeviceOwnerManagingSingleUser(who);
5364 if (mRemoteBugreportServiceIsActive.get()
5365 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5366 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5370 final long callingIdentity = mInjector.binderClearCallingIdentity();
5372 ActivityManagerNative.getDefault().requestBugReport(
5373 ActivityManager.BUGREPORT_OPTION_REMOTE);
5375 mRemoteBugreportServiceIsActive.set(true);
5376 mRemoteBugreportSharingAccepted.set(false);
5377 registerRemoteBugreportReceivers();
5378 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5379 RemoteBugreportUtils.buildNotification(mContext,
5380 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5381 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5382 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5384 } catch (RemoteException re) {
5385 // should never happen
5386 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5389 mInjector.binderRestoreCallingIdentity(callingIdentity);
5393 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5394 Intent intent = new Intent(action);
5395 intent.setComponent(mOwners.getDeviceOwnerComponent());
5396 if (extras != null) {
5397 intent.putExtras(extras);
5399 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5402 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5403 return mOwners.getDeviceOwnerRemoteBugreportUri();
5406 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5407 String bugreportHash) {
5408 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5411 private void registerRemoteBugreportReceivers() {
5413 IntentFilter filterFinished = new IntentFilter(
5414 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5415 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5416 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5417 } catch (IntentFilter.MalformedMimeTypeException e) {
5418 // should never happen, as setting a constant
5419 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5421 IntentFilter filterConsent = new IntentFilter();
5422 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5423 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5424 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5427 private void onBugreportFinished(Intent intent) {
5428 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5429 mRemoteBugreportServiceIsActive.set(false);
5430 Uri bugreportUri = intent.getData();
5431 String bugreportUriString = null;
5432 if (bugreportUri != null) {
5433 bugreportUriString = bugreportUri.toString();
5435 String bugreportHash = intent.getStringExtra(
5436 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5437 if (mRemoteBugreportSharingAccepted.get()) {
5438 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5439 mInjector.getNotificationManager().cancel(LOG_TAG,
5440 RemoteBugreportUtils.NOTIFICATION_ID);
5442 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5443 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5444 RemoteBugreportUtils.buildNotification(mContext,
5445 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5448 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5451 private void onBugreportFailed() {
5452 mRemoteBugreportServiceIsActive.set(false);
5453 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5454 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5455 mRemoteBugreportSharingAccepted.set(false);
5456 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5457 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5458 Bundle extras = new Bundle();
5459 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5460 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5461 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5462 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5463 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5466 private void onBugreportSharingAccepted() {
5467 mRemoteBugreportSharingAccepted.set(true);
5468 String bugreportUriString = null;
5469 String bugreportHash = null;
5470 synchronized (this) {
5471 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5472 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5474 if (bugreportUriString != null) {
5475 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5476 } else if (mRemoteBugreportServiceIsActive.get()) {
5477 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5478 RemoteBugreportUtils.buildNotification(mContext,
5479 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5484 private void onBugreportSharingDeclined() {
5485 if (mRemoteBugreportServiceIsActive.get()) {
5486 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5487 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5488 mRemoteBugreportServiceIsActive.set(false);
5489 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5490 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5492 mRemoteBugreportSharingAccepted.set(false);
5493 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5494 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5497 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5498 String bugreportHash) {
5499 ParcelFileDescriptor pfd = null;
5501 if (bugreportUriString == null) {
5502 throw new FileNotFoundException();
5504 Uri bugreportUri = Uri.parse(bugreportUriString);
5505 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5507 synchronized (this) {
5508 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5509 intent.setComponent(mOwners.getDeviceOwnerComponent());
5510 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5511 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5512 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
5513 bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5514 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5516 } catch (FileNotFoundException e) {
5517 Bundle extras = new Bundle();
5518 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5519 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5520 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5526 } catch (IOException ex) {
5529 mRemoteBugreportSharingAccepted.set(false);
5530 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5535 * Disables all device cameras according to the specified admin.
5538 public void setCameraDisabled(ComponentName who, boolean disabled) {
5542 Preconditions.checkNotNull(who, "ComponentName is null");
5543 final int userHandle = mInjector.userHandleGetCallingUserId();
5544 synchronized (this) {
5545 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5546 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5547 if (ap.disableCamera != disabled) {
5548 ap.disableCamera = disabled;
5549 saveSettingsLocked(userHandle);
5552 // Tell the user manager that the restrictions have changed.
5553 pushUserRestrictions(userHandle);
5557 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5561 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5562 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5565 private boolean getCameraDisabled(ComponentName who, int userHandle,
5566 boolean mergeDeviceOwnerRestriction) {
5570 synchronized (this) {
5572 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5573 return (admin != null) ? admin.disableCamera : false;
5575 // First, see if DO has set it. If so, it's device-wide.
5576 if (mergeDeviceOwnerRestriction) {
5577 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5578 if (deviceOwner != null && deviceOwner.disableCamera) {
5583 // Then check each device admin on the user.
5584 DevicePolicyData policy = getUserData(userHandle);
5585 // Determine whether or not the device camera is disabled for any active admins.
5586 final int N = policy.mAdminList.size();
5587 for (int i = 0; i < N; i++) {
5588 ActiveAdmin admin = policy.mAdminList.get(i);
5589 if (admin.disableCamera) {
5598 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5602 Preconditions.checkNotNull(who, "ComponentName is null");
5603 final int userHandle = mInjector.userHandleGetCallingUserId();
5604 if (isManagedProfile(userHandle)) {
5606 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5608 which = which & PROFILE_KEYGUARD_FEATURES;
5611 synchronized (this) {
5612 ActiveAdmin ap = getActiveAdminForCallerLocked(
5613 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5614 if (ap.disabledKeyguardFeatures != which) {
5615 ap.disabledKeyguardFeatures = which;
5616 saveSettingsLocked(userHandle);
5622 * Gets the disabled state for features in keyguard for the given admin,
5623 * or the aggregate of all active admins if who is null.
5626 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5630 enforceFullCrossUsersPermission(userHandle);
5631 final long ident = mInjector.binderClearCallingIdentity();
5633 synchronized (this) {
5635 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5636 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5639 final List<ActiveAdmin> admins;
5640 if (!parent && isManagedProfile(userHandle)) {
5641 // If we are being asked about a managed profile, just return keyguard features
5642 // disabled by admins in the profile.
5643 admins = getUserDataUnchecked(userHandle).mAdminList;
5645 // Otherwise return those set by admins in the user and its profiles.
5646 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5649 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5650 final int N = admins.size();
5651 for (int i = 0; i < N; i++) {
5652 ActiveAdmin admin = admins.get(i);
5653 int userId = admin.getUserHandle().getIdentifier();
5654 boolean isRequestedUser = !parent && (userId == userHandle);
5655 if (isRequestedUser || !isManagedProfile(userId)) {
5656 // If we are being asked explicitly about this user
5657 // return all disabled features even if its a managed profile.
5658 which |= admin.disabledKeyguardFeatures;
5660 // Otherwise a managed profile is only allowed to disable
5661 // some features on the parent user.
5662 which |= (admin.disabledKeyguardFeatures
5663 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5669 mInjector.binderRestoreCallingIdentity(ident);
5674 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5678 Preconditions.checkNotNull(who, "ComponentName is null");
5679 Preconditions.checkNotNull(packageList, "packageList is null");
5680 final int userHandle = UserHandle.getCallingUserId();
5681 synchronized (this) {
5682 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5683 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5684 admin.keepUninstalledPackages = packageList;
5685 saveSettingsLocked(userHandle);
5686 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5691 public List<String> getKeepUninstalledPackages(ComponentName who) {
5692 Preconditions.checkNotNull(who, "ComponentName is null");
5696 // TODO In split system user mode, allow apps on user 0 to query the list
5697 synchronized (this) {
5698 // Check if this is the device owner who is calling
5699 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5700 return getKeepUninstalledPackagesLocked();
5704 private List<String> getKeepUninstalledPackagesLocked() {
5705 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5706 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5710 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5715 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5716 throw new IllegalArgumentException("Invalid component " + admin
5717 + " for device owner");
5719 synchronized (this) {
5720 enforceCanSetDeviceOwnerLocked(admin, userId);
5721 if (getActiveAdminUncheckedLocked(admin, userId) == null
5722 || getUserData(userId).mRemovingAdmins.contains(admin)) {
5723 throw new IllegalArgumentException("Not active admin: " + admin);
5726 // Shutting down backup manager service permanently.
5727 long ident = mInjector.binderClearCallingIdentity();
5729 if (mInjector.getIBackupManager() != null) {
5730 mInjector.getIBackupManager()
5731 .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5733 } catch (RemoteException e) {
5734 throw new IllegalStateException("Failed deactivating backup service.", e);
5736 mInjector.binderRestoreCallingIdentity(ident);
5739 mOwners.setDeviceOwner(admin, ownerName, userId);
5740 mOwners.writeDeviceOwner();
5741 updateDeviceOwnerLocked();
5742 setDeviceOwnerSystemPropertyLocked();
5743 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5745 ident = mInjector.binderClearCallingIdentity();
5747 // TODO Send to system too?
5748 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5750 mInjector.binderRestoreCallingIdentity(ident);
5752 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
5757 public boolean isDeviceOwner(ComponentName who, int userId) {
5758 synchronized (this) {
5759 return mOwners.hasDeviceOwner()
5760 && mOwners.getDeviceOwnerUserId() == userId
5761 && mOwners.getDeviceOwnerComponent().equals(who);
5765 public boolean isProfileOwner(ComponentName who, int userId) {
5766 final ComponentName profileOwner = getProfileOwner(userId);
5767 return who != null && who.equals(profileOwner);
5771 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5775 if (!callingUserOnly) {
5776 enforceManageUsers();
5778 synchronized (this) {
5779 if (!mOwners.hasDeviceOwner()) {
5782 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
5783 mOwners.getDeviceOwnerUserId()) {
5786 return mOwners.getDeviceOwnerComponent();
5791 public int getDeviceOwnerUserId() {
5793 return UserHandle.USER_NULL;
5795 enforceManageUsers();
5796 synchronized (this) {
5797 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
5802 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
5806 public String getDeviceOwnerName() {
5810 enforceManageUsers();
5811 synchronized (this) {
5812 if (!mOwners.hasDeviceOwner()) {
5815 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
5816 // Should setDeviceOwner/ProfileOwner still take a name?
5817 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
5818 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
5822 // Returns the active device owner or null if there is no device owner.
5824 ActiveAdmin getDeviceOwnerAdminLocked() {
5825 ComponentName component = mOwners.getDeviceOwnerComponent();
5826 if (component == null) {
5830 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
5831 final int n = policy.mAdminList.size();
5832 for (int i = 0; i < n; i++) {
5833 ActiveAdmin admin = policy.mAdminList.get(i);
5834 if (component.equals(admin.info.getComponent())) {
5838 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
5843 public void clearDeviceOwner(String packageName) {
5844 Preconditions.checkNotNull(packageName, "packageName is null");
5845 final int callingUid = mInjector.binderGetCallingUid();
5847 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
5848 UserHandle.getUserId(callingUid));
5849 if (uid != callingUid) {
5850 throw new SecurityException("Invalid packageName");
5852 } catch (NameNotFoundException e) {
5853 throw new SecurityException(e);
5855 synchronized (this) {
5856 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
5857 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
5858 if (!mOwners.hasDeviceOwner()
5859 || !deviceOwnerComponent.getPackageName().equals(packageName)
5860 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
5861 throw new SecurityException(
5862 "clearDeviceOwner can only be called by the device owner");
5864 enforceUserUnlocked(deviceOwnerUserId);
5866 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
5867 long ident = mInjector.binderClearCallingIdentity();
5869 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
5870 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
5872 mInjector.binderRestoreCallingIdentity(ident);
5874 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
5878 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
5879 if (admin != null) {
5880 admin.disableCamera = false;
5881 admin.userRestrictions = null;
5882 admin.forceEphemeralUsers = false;
5883 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
5885 clearUserPoliciesLocked(userId);
5887 mOwners.clearDeviceOwner();
5888 mOwners.writeDeviceOwner();
5889 updateDeviceOwnerLocked();
5890 disableSecurityLoggingIfNotCompliant();
5892 // Reactivate backup service.
5893 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
5894 } catch (RemoteException e) {
5895 throw new IllegalStateException("Failed reactivating backup service.", e);
5900 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
5905 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
5906 throw new IllegalArgumentException("Component " + who
5907 + " not installed for userId:" + userHandle);
5909 synchronized (this) {
5910 enforceCanSetProfileOwnerLocked(who, userHandle);
5912 if (getActiveAdminUncheckedLocked(who, userHandle) == null
5913 || getUserData(userHandle).mRemovingAdmins.contains(who)) {
5914 throw new IllegalArgumentException("Not active admin: " + who);
5917 mOwners.setProfileOwner(who, ownerName, userHandle);
5918 mOwners.writeProfileOwner(userHandle);
5919 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
5925 public void clearProfileOwner(ComponentName who) {
5929 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
5930 final int userId = callingUser.getIdentifier();
5931 enforceNotManagedProfile(userId, "clear profile owner");
5932 enforceUserUnlocked(userId);
5933 // Check if this is the profile owner who is calling
5934 final ActiveAdmin admin =
5935 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5936 synchronized (this) {
5937 final long ident = mInjector.binderClearCallingIdentity();
5939 clearProfileOwnerLocked(admin, userId);
5940 removeActiveAdminLocked(who, userId);
5942 mInjector.binderRestoreCallingIdentity(ident);
5944 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
5948 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
5949 if (admin != null) {
5950 admin.disableCamera = false;
5951 admin.userRestrictions = null;
5953 clearUserPoliciesLocked(userId);
5954 mOwners.removeProfileOwner(userId);
5955 mOwners.writeProfileOwner(userId);
5959 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
5960 Preconditions.checkNotNull(who, "ComponentName is null");
5965 synchronized (this) {
5966 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5967 long token = mInjector.binderClearCallingIdentity();
5969 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
5971 mInjector.binderRestoreCallingIdentity(token);
5977 public CharSequence getDeviceOwnerLockScreenInfo() {
5978 return mLockPatternUtils.getDeviceOwnerInfo();
5981 private void clearUserPoliciesLocked(int userId) {
5982 // Reset some of the user-specific policies
5983 DevicePolicyData policy = getUserData(userId);
5984 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
5985 policy.mDelegatedCertInstallerPackage = null;
5986 policy.mApplicationRestrictionsManagingPackage = null;
5987 policy.mStatusBarDisabled = false;
5988 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
5989 saveSettingsLocked(userId);
5992 mIPackageManager.updatePermissionFlagsForAllApps(
5993 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
5994 0 /* flagValues */, userId);
5995 pushUserRestrictions(userId);
5996 } catch (RemoteException re) {
5997 // Shouldn't happen.
6002 public boolean hasUserSetupCompleted() {
6003 return hasUserSetupCompleted(UserHandle.getCallingUserId());
6006 private boolean hasUserSetupCompleted(int userHandle) {
6010 return getUserData(userHandle).mUserSetupComplete;
6014 public int getUserProvisioningState() {
6016 return DevicePolicyManager.STATE_USER_UNMANAGED;
6018 int userHandle = mInjector.userHandleGetCallingUserId();
6019 return getUserProvisioningState(userHandle);
6022 private int getUserProvisioningState(int userHandle) {
6023 return getUserData(userHandle).mUserProvisioningState;
6027 public void setUserProvisioningState(int newState, int userHandle) {
6032 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6033 && getManagedUserId(userHandle) == -1) {
6034 // No managed device, user or profile, so setting provisioning state makes no sense.
6035 throw new IllegalStateException("Not allowed to change provisioning state unless a "
6036 + "device or profile owner is set.");
6039 synchronized (this) {
6040 boolean transitionCheckNeeded = true;
6042 // Calling identity/permission checks.
6043 final int callingUid = mInjector.binderGetCallingUid();
6044 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6045 // ADB shell can only move directly from un-managed to finalized as part of directly
6046 // setting profile-owner or device-owner.
6047 if (getUserProvisioningState(userHandle) !=
6048 DevicePolicyManager.STATE_USER_UNMANAGED
6049 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6050 throw new IllegalStateException("Not allowed to change provisioning state "
6051 + "unless current provisioning state is unmanaged, and new state is "
6054 transitionCheckNeeded = false;
6056 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6057 enforceCanManageProfileAndDeviceOwners();
6060 final DevicePolicyData policyData = getUserData(userHandle);
6061 if (transitionCheckNeeded) {
6062 // Optional state transition check for non-ADB case.
6063 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6065 policyData.mUserProvisioningState = newState;
6066 saveSettingsLocked(userHandle);
6070 private void checkUserProvisioningStateTransition(int currentState, int newState) {
6071 // Valid transitions for normal use-cases.
6072 switch (currentState) {
6073 case DevicePolicyManager.STATE_USER_UNMANAGED:
6074 // Can move to any state from unmanaged (except itself as an edge case)..
6075 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6079 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6080 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6081 // Can only move to finalized from these states.
6082 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6086 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6087 // Current user has a managed-profile, but current user is not managed, so
6088 // rather than moving to finalized state, go back to unmanaged once
6089 // profile provisioning is complete.
6090 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6094 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6095 // Cannot transition out of finalized.
6099 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6100 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6101 + "from state [" + currentState + "]");
6105 public void setProfileEnabled(ComponentName who) {
6109 Preconditions.checkNotNull(who, "ComponentName is null");
6110 synchronized (this) {
6111 // Check if this is the profile owner who is calling
6112 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6113 final int userId = UserHandle.getCallingUserId();
6114 enforceManagedProfile(userId, "enable the profile");
6116 long id = mInjector.binderClearCallingIdentity();
6118 mUserManager.setUserEnabled(userId);
6119 UserInfo parent = mUserManager.getProfileParent(userId);
6120 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6121 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6122 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6123 Intent.FLAG_RECEIVER_FOREGROUND);
6124 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6126 mInjector.binderRestoreCallingIdentity(id);
6132 public void setProfileName(ComponentName who, String profileName) {
6133 Preconditions.checkNotNull(who, "ComponentName is null");
6134 int userId = UserHandle.getCallingUserId();
6135 // Check if this is the profile owner (includes device owner).
6136 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6138 long id = mInjector.binderClearCallingIdentity();
6140 mUserManager.setUserName(userId, profileName);
6142 mInjector.binderRestoreCallingIdentity(id);
6147 public ComponentName getProfileOwner(int userHandle) {
6152 synchronized (this) {
6153 return mOwners.getProfileOwnerComponent(userHandle);
6157 // Returns the active profile owner for this user or null if the current user has no
6160 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6161 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6162 if (profileOwner == null) {
6165 DevicePolicyData policy = getUserData(userHandle);
6166 final int n = policy.mAdminList.size();
6167 for (int i = 0; i < n; i++) {
6168 ActiveAdmin admin = policy.mAdminList.get(i);
6169 if (profileOwner.equals(admin.info.getComponent())) {
6177 public String getProfileOwnerName(int userHandle) {
6181 enforceManageUsers();
6182 ComponentName profileOwner = getProfileOwner(userHandle);
6183 if (profileOwner == null) {
6186 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6190 * Canonical name for a given package.
6192 private String getApplicationLabel(String packageName, int userHandle) {
6193 long token = mInjector.binderClearCallingIdentity();
6195 final Context userContext;
6197 UserHandle handle = new UserHandle(userHandle);
6198 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6199 } catch (PackageManager.NameNotFoundException nnfe) {
6200 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6203 ApplicationInfo appInfo = userContext.getApplicationInfo();
6204 CharSequence result = null;
6205 if (appInfo != null) {
6206 PackageManager pm = userContext.getPackageManager();
6207 result = pm.getApplicationLabel(appInfo);
6209 return result != null ? result.toString() : null;
6211 mInjector.binderRestoreCallingIdentity(token);
6216 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6218 * The profile owner can only be set before the user setup phase has completed,
6221 * - adb if there are no accounts. (But see {@link #hasIncompatibleAccounts})
6223 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle) {
6224 UserInfo info = getUserInfo(userHandle);
6226 // User doesn't exist.
6227 throw new IllegalArgumentException(
6228 "Attempted to set profile owner for invalid userId: " + userHandle);
6230 if (info.isGuest()) {
6231 throw new IllegalStateException("Cannot set a profile owner on a guest");
6233 if (mOwners.hasProfileOwner(userHandle)) {
6234 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6235 + "is already set.");
6237 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6238 throw new IllegalStateException("Trying to set the profile owner, but the user "
6239 + "already has a device owner.");
6241 int callingUid = mInjector.binderGetCallingUid();
6242 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6243 if (hasUserSetupCompleted(userHandle)
6244 && hasIncompatibleAccounts(userHandle, owner)) {
6245 throw new IllegalStateException("Not allowed to set the profile owner because "
6246 + "there are already some accounts on the profile");
6250 enforceCanManageProfileAndDeviceOwners();
6251 if (hasUserSetupCompleted(userHandle) && !isCallerWithSystemUid()) {
6252 throw new IllegalStateException("Cannot set the profile owner on a user which is "
6253 + "already set-up");
6258 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6261 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId) {
6262 int callingUid = mInjector.binderGetCallingUid();
6263 boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6265 enforceCanManageProfileAndDeviceOwners();
6268 final int code = checkSetDeviceOwnerPreCondition(owner, userId, isAdb);
6272 case CODE_HAS_DEVICE_OWNER:
6273 throw new IllegalStateException(
6274 "Trying to set the device owner, but device owner is already set.");
6275 case CODE_USER_HAS_PROFILE_OWNER:
6276 throw new IllegalStateException("Trying to set the device owner, but the user "
6277 + "already has a profile owner.");
6278 case CODE_USER_NOT_RUNNING:
6279 throw new IllegalStateException("User not running: " + userId);
6280 case CODE_NOT_SYSTEM_USER:
6281 throw new IllegalStateException("User is not system user");
6282 case CODE_USER_SETUP_COMPLETED:
6283 throw new IllegalStateException(
6284 "Cannot set the device owner if the device is already set-up");
6285 case CODE_NONSYSTEM_USER_EXISTS:
6286 throw new IllegalStateException("Not allowed to set the device owner because there "
6287 + "are already several users on the device");
6288 case CODE_ACCOUNTS_NOT_EMPTY:
6289 throw new IllegalStateException("Not allowed to set the device owner because there "
6290 + "are already some accounts on the device");
6292 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6296 private void enforceUserUnlocked(int userId) {
6297 // Since we're doing this operation on behalf of an app, we only
6298 // want to use the actual "unlocked" state.
6299 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6300 "User must be running and unlocked");
6303 private void enforceManageUsers() {
6304 final int callingUid = mInjector.binderGetCallingUid();
6305 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6306 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6310 private void enforceFullCrossUsersPermission(int userHandle) {
6311 enforceSystemUserOrPermission(userHandle,
6312 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6315 private void enforceCrossUsersPermission(int userHandle) {
6316 enforceSystemUserOrPermission(userHandle,
6317 android.Manifest.permission.INTERACT_ACROSS_USERS);
6320 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6321 if (userHandle < 0) {
6322 throw new IllegalArgumentException("Invalid userId " + userHandle);
6324 final int callingUid = mInjector.binderGetCallingUid();
6325 if (userHandle == UserHandle.getUserId(callingUid)) {
6328 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6329 mContext.enforceCallingOrSelfPermission(permission,
6330 "Must be system or have " + permission + " permission");
6334 private void enforceManagedProfile(int userHandle, String message) {
6335 if(!isManagedProfile(userHandle)) {
6336 throw new SecurityException("You can not " + message + " outside a managed profile.");
6340 private void enforceNotManagedProfile(int userHandle, String message) {
6341 if(isManagedProfile(userHandle)) {
6342 throw new SecurityException("You can not " + message + " for a managed profile.");
6346 private void ensureCallerPackage(@Nullable String packageName) {
6347 if (packageName == null) {
6348 Preconditions.checkState(isCallerWithSystemUid(),
6349 "Only caller can omit package name");
6351 final int callingUid = mInjector.binderGetCallingUid();
6352 final int userId = mInjector.userHandleGetCallingUserId();
6354 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6355 packageName, 0, userId);
6356 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6357 } catch (RemoteException e) {
6363 private boolean isCallerWithSystemUid() {
6364 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6367 private int getProfileParentId(int userHandle) {
6368 final long ident = mInjector.binderClearCallingIdentity();
6370 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6371 return parentUser != null ? parentUser.id : userHandle;
6373 mInjector.binderRestoreCallingIdentity(ident);
6377 private int getCredentialOwner(int userHandle, boolean parent) {
6378 final long ident = mInjector.binderClearCallingIdentity();
6381 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6382 if (parentProfile != null) {
6383 userHandle = parentProfile.id;
6386 return mUserManager.getCredentialOwnerProfile(userHandle);
6388 mInjector.binderRestoreCallingIdentity(ident);
6392 private boolean isManagedProfile(int userHandle) {
6393 return getUserInfo(userHandle).isManagedProfile();
6396 private void enableIfNecessary(String packageName, int userId) {
6398 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6399 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6401 if (ai.enabledSetting
6402 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6403 mIPackageManager.setApplicationEnabledSetting(packageName,
6404 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6405 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6407 } catch (RemoteException e) {
6412 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6413 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6414 != PackageManager.PERMISSION_GRANTED) {
6416 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6417 + mInjector.binderGetCallingPid()
6418 + ", uid=" + mInjector.binderGetCallingUid());
6422 synchronized (this) {
6423 pw.println("Current Device Policy Manager state:");
6424 mOwners.dump(" ", pw);
6425 int userCount = mUserData.size();
6426 for (int u = 0; u < userCount; u++) {
6427 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6429 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6430 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6431 final int N = policy.mAdminList.size();
6432 for (int i=0; i<N; i++) {
6433 ActiveAdmin ap = policy.mAdminList.get(i);
6435 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6440 if (!policy.mRemovingAdmins.isEmpty()) {
6441 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6442 + policy.mRemovingAdmins);
6446 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6449 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6453 private String getEncryptionStatusName(int encryptionStatus) {
6454 switch (encryptionStatus) {
6455 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6457 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6458 return "block default key";
6459 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6461 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6463 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6464 return "unsupported";
6465 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6466 return "activating";
6473 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6474 ComponentName activity) {
6475 Preconditions.checkNotNull(who, "ComponentName is null");
6476 final int userHandle = UserHandle.getCallingUserId();
6477 synchronized (this) {
6478 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6480 long id = mInjector.binderClearCallingIdentity();
6482 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6483 } catch (RemoteException re) {
6486 mInjector.binderRestoreCallingIdentity(id);
6492 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6493 Preconditions.checkNotNull(who, "ComponentName is null");
6494 final int userHandle = UserHandle.getCallingUserId();
6495 synchronized (this) {
6496 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6498 long id = mInjector.binderClearCallingIdentity();
6500 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6501 } catch (RemoteException re) {
6504 mInjector.binderRestoreCallingIdentity(id);
6510 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6511 String packageName) {
6512 Preconditions.checkNotNull(admin, "ComponentName is null");
6514 final int userHandle = mInjector.userHandleGetCallingUserId();
6515 synchronized (this) {
6516 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6517 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6520 DevicePolicyData policy = getUserData(userHandle);
6521 policy.mApplicationRestrictionsManagingPackage = packageName;
6522 saveSettingsLocked(userHandle);
6528 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6529 Preconditions.checkNotNull(admin, "ComponentName is null");
6531 final int userHandle = mInjector.userHandleGetCallingUserId();
6532 synchronized (this) {
6533 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6534 DevicePolicyData policy = getUserData(userHandle);
6535 return policy.mApplicationRestrictionsManagingPackage;
6540 public boolean isCallerApplicationRestrictionsManagingPackage() {
6541 final int callingUid = mInjector.binderGetCallingUid();
6542 final int userHandle = UserHandle.getUserId(callingUid);
6543 synchronized (this) {
6544 final DevicePolicyData policy = getUserData(userHandle);
6545 if (policy.mApplicationRestrictionsManagingPackage == null) {
6550 int uid = mContext.getPackageManager().getPackageUidAsUser(
6551 policy.mApplicationRestrictionsManagingPackage, userHandle);
6552 return uid == callingUid;
6553 } catch (NameNotFoundException e) {
6559 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6561 synchronized (this) {
6562 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6564 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6565 throw new SecurityException(
6566 "No admin component given, and caller cannot manage application restrictions "
6567 + "for other apps.");
6572 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6573 enforceCanManageApplicationRestrictions(who);
6575 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6576 final long id = mInjector.binderClearCallingIdentity();
6578 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6580 mInjector.binderRestoreCallingIdentity(id);
6585 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6586 PersistableBundle args, boolean parent) {
6590 Preconditions.checkNotNull(admin, "admin is null");
6591 Preconditions.checkNotNull(agent, "agent is null");
6592 final int userHandle = UserHandle.getCallingUserId();
6593 synchronized (this) {
6594 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6595 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6596 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6597 saveSettingsLocked(userHandle);
6602 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6603 ComponentName agent, int userHandle, boolean parent) {
6607 Preconditions.checkNotNull(agent, "agent null");
6608 enforceFullCrossUsersPermission(userHandle);
6610 synchronized (this) {
6611 final String componentName = agent.flattenToString();
6612 if (admin != null) {
6613 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6614 if (ap == null) return null;
6615 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6616 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6617 List<PersistableBundle> result = new ArrayList<>();
6618 result.add(trustAgentInfo.options);
6622 // Return strictest policy for this user and profiles that are visible from this user.
6623 List<PersistableBundle> result = null;
6624 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6625 // of the options. If any admin doesn't have options, discard options for the rest
6627 List<ActiveAdmin> admins =
6628 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6629 boolean allAdminsHaveOptions = true;
6630 final int N = admins.size();
6631 for (int i = 0; i < N; i++) {
6632 final ActiveAdmin active = admins.get(i);
6634 final boolean disablesTrust = (active.disabledKeyguardFeatures
6635 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6636 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6637 if (info != null && info.options != null && !info.options.isEmpty()) {
6638 if (disablesTrust) {
6639 if (result == null) {
6640 result = new ArrayList<>();
6642 result.add(info.options);
6644 Log.w(LOG_TAG, "Ignoring admin " + active.info
6645 + " because it has trust options but doesn't declare "
6646 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6648 } else if (disablesTrust) {
6649 allAdminsHaveOptions = false;
6653 return allAdminsHaveOptions ? result : null;
6658 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6659 Preconditions.checkNotNull(who, "ComponentName is null");
6660 synchronized (this) {
6661 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6663 int userHandle = UserHandle.getCallingUserId();
6664 DevicePolicyData userData = getUserData(userHandle);
6665 userData.mRestrictionsProvider = permissionProvider;
6666 saveSettingsLocked(userHandle);
6671 public ComponentName getRestrictionsProvider(int userHandle) {
6672 synchronized (this) {
6673 if (!isCallerWithSystemUid()) {
6674 throw new SecurityException("Only the system can query the permission provider");
6676 DevicePolicyData userData = getUserData(userHandle);
6677 return userData != null ? userData.mRestrictionsProvider : null;
6682 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6683 Preconditions.checkNotNull(who, "ComponentName is null");
6684 int callingUserId = UserHandle.getCallingUserId();
6685 synchronized (this) {
6686 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6688 long id = mInjector.binderClearCallingIdentity();
6690 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6691 if (parent == null) {
6692 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6696 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6697 mIPackageManager.addCrossProfileIntentFilter(
6698 filter, who.getPackageName(), callingUserId, parent.id, 0);
6700 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6701 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6702 parent.id, callingUserId, 0);
6704 } catch (RemoteException re) {
6707 mInjector.binderRestoreCallingIdentity(id);
6713 public void clearCrossProfileIntentFilters(ComponentName who) {
6714 Preconditions.checkNotNull(who, "ComponentName is null");
6715 int callingUserId = UserHandle.getCallingUserId();
6716 synchronized (this) {
6717 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6718 long id = mInjector.binderClearCallingIdentity();
6720 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6721 if (parent == null) {
6722 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6726 // Removing those that go from the managed profile to the parent.
6727 mIPackageManager.clearCrossProfileIntentFilters(
6728 callingUserId, who.getPackageName());
6729 // And those that go from the parent to the managed profile.
6730 // If we want to support multiple managed profiles, we will have to only remove
6731 // those that have callingUserId as their target.
6732 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6733 } catch (RemoteException re) {
6736 mInjector.binderRestoreCallingIdentity(id);
6742 * @return true if all packages in enabledPackages are either in the list
6743 * permittedList or are a system app.
6745 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6746 List<String> permittedList, int userIdToCheck) {
6747 long id = mInjector.binderClearCallingIdentity();
6749 // If we have an enabled packages list for a managed profile the packages
6750 // we should check are installed for the parent user.
6751 UserInfo user = getUserInfo(userIdToCheck);
6752 if (user.isManagedProfile()) {
6753 userIdToCheck = user.profileGroupId;
6756 for (String enabledPackage : enabledPackages) {
6757 boolean systemService = false;
6759 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
6760 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
6761 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6762 } catch (RemoteException e) {
6763 Log.i(LOG_TAG, "Can't talk to package managed", e);
6765 if (!systemService && !permittedList.contains(enabledPackage)) {
6770 mInjector.binderRestoreCallingIdentity(id);
6775 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
6776 // Not using AccessibilityManager.getInstance because that guesses
6777 // at the user you require based on callingUid and caches for a given
6779 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
6780 IAccessibilityManager service = iBinder == null
6781 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
6782 return new AccessibilityManager(mContext, service, userId);
6786 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
6790 Preconditions.checkNotNull(who, "ComponentName is null");
6792 if (packageList != null) {
6793 int userId = UserHandle.getCallingUserId();
6794 List<AccessibilityServiceInfo> enabledServices = null;
6795 long id = mInjector.binderClearCallingIdentity();
6797 UserInfo user = getUserInfo(userId);
6798 if (user.isManagedProfile()) {
6799 userId = user.profileGroupId;
6801 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
6802 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
6803 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
6805 mInjector.binderRestoreCallingIdentity(id);
6808 if (enabledServices != null) {
6809 List<String> enabledPackages = new ArrayList<String>();
6810 for (AccessibilityServiceInfo service : enabledServices) {
6811 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
6813 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6815 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
6816 + "because it contains already enabled accesibility services.");
6822 synchronized (this) {
6823 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6824 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6825 admin.permittedAccessiblityServices = packageList;
6826 saveSettingsLocked(UserHandle.getCallingUserId());
6832 public List getPermittedAccessibilityServices(ComponentName who) {
6836 Preconditions.checkNotNull(who, "ComponentName is null");
6838 synchronized (this) {
6839 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6840 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6841 return admin.permittedAccessiblityServices;
6846 public List getPermittedAccessibilityServicesForUser(int userId) {
6850 synchronized (this) {
6851 List<String> result = null;
6852 // If we have multiple profiles we return the intersection of the
6853 // permitted lists. This can happen in cases where we have a device
6854 // and profile owner.
6855 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
6856 for (int profileId : profileIds) {
6857 // Just loop though all admins, only device or profiles
6858 // owners can have permitted lists set.
6859 DevicePolicyData policy = getUserDataUnchecked(profileId);
6860 final int N = policy.mAdminList.size();
6861 for (int j = 0; j < N; j++) {
6862 ActiveAdmin admin = policy.mAdminList.get(j);
6863 List<String> fromAdmin = admin.permittedAccessiblityServices;
6864 if (fromAdmin != null) {
6865 if (result == null) {
6866 result = new ArrayList<>(fromAdmin);
6868 result.retainAll(fromAdmin);
6874 // If we have a permitted list add all system accessibility services.
6875 if (result != null) {
6876 long id = mInjector.binderClearCallingIdentity();
6878 UserInfo user = getUserInfo(userId);
6879 if (user.isManagedProfile()) {
6880 userId = user.profileGroupId;
6882 AccessibilityManager accessibilityManager =
6883 getAccessibilityManagerForUser(userId);
6884 List<AccessibilityServiceInfo> installedServices =
6885 accessibilityManager.getInstalledAccessibilityServiceList();
6887 if (installedServices != null) {
6888 for (AccessibilityServiceInfo service : installedServices) {
6889 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
6890 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
6891 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6892 result.add(serviceInfo.packageName);
6897 mInjector.binderRestoreCallingIdentity(id);
6906 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
6911 Preconditions.checkNotNull(who, "ComponentName is null");
6912 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
6913 if (!isCallerWithSystemUid()){
6914 throw new SecurityException(
6915 "Only the system can query if an accessibility service is disabled by admin");
6917 synchronized (this) {
6918 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6919 if (admin == null) {
6922 if (admin.permittedAccessiblityServices == null) {
6925 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
6926 admin.permittedAccessiblityServices, userHandle);
6930 private boolean checkCallerIsCurrentUserOrProfile() {
6931 int callingUserId = UserHandle.getCallingUserId();
6932 long token = mInjector.binderClearCallingIdentity();
6934 UserInfo currentUser;
6935 UserInfo callingUser = getUserInfo(callingUserId);
6937 currentUser = mInjector.getIActivityManager().getCurrentUser();
6938 } catch (RemoteException e) {
6939 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
6943 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
6944 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
6945 + "of a user that isn't the foreground user.");
6948 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
6949 Slog.e(LOG_TAG, "Cannot set permitted input methods "
6950 + "of a user that isn't the foreground user.");
6954 mInjector.binderRestoreCallingIdentity(token);
6960 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
6964 Preconditions.checkNotNull(who, "ComponentName is null");
6966 // TODO When InputMethodManager supports per user calls remove
6967 // this restriction.
6968 if (!checkCallerIsCurrentUserOrProfile()) {
6972 if (packageList != null) {
6973 // InputMethodManager fetches input methods for current user.
6974 // So this can only be set when calling user is the current user
6975 // or parent is current user in case of managed profiles.
6976 InputMethodManager inputMethodManager =
6977 mContext.getSystemService(InputMethodManager.class);
6978 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
6980 if (enabledImes != null) {
6981 List<String> enabledPackages = new ArrayList<String>();
6982 for (InputMethodInfo ime : enabledImes) {
6983 enabledPackages.add(ime.getPackageName());
6985 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6986 mInjector.binderGetCallingUserHandle().getIdentifier())) {
6987 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
6988 + "because it contains already enabled input method.");
6994 synchronized (this) {
6995 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6996 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6997 admin.permittedInputMethods = packageList;
6998 saveSettingsLocked(UserHandle.getCallingUserId());
7004 public List getPermittedInputMethods(ComponentName who) {
7008 Preconditions.checkNotNull(who, "ComponentName is null");
7010 synchronized (this) {
7011 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7012 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7013 return admin.permittedInputMethods;
7018 public List getPermittedInputMethodsForCurrentUser() {
7019 UserInfo currentUser;
7021 currentUser = mInjector.getIActivityManager().getCurrentUser();
7022 } catch (RemoteException e) {
7023 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7024 // Activity managed is dead, just allow all IMEs
7028 int userId = currentUser.id;
7029 synchronized (this) {
7030 List<String> result = null;
7031 // If we have multiple profiles we return the intersection of the
7032 // permitted lists. This can happen in cases where we have a device
7033 // and profile owner.
7034 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7035 for (int profileId : profileIds) {
7036 // Just loop though all admins, only device or profiles
7037 // owners can have permitted lists set.
7038 DevicePolicyData policy = getUserDataUnchecked(profileId);
7039 final int N = policy.mAdminList.size();
7040 for (int j = 0; j < N; j++) {
7041 ActiveAdmin admin = policy.mAdminList.get(j);
7042 List<String> fromAdmin = admin.permittedInputMethods;
7043 if (fromAdmin != null) {
7044 if (result == null) {
7045 result = new ArrayList<String>(fromAdmin);
7047 result.retainAll(fromAdmin);
7053 // If we have a permitted list add all system input methods.
7054 if (result != null) {
7055 InputMethodManager inputMethodManager =
7056 mContext.getSystemService(InputMethodManager.class);
7057 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7058 long id = mInjector.binderClearCallingIdentity();
7061 for (InputMethodInfo ime : imes) {
7062 ServiceInfo serviceInfo = ime.getServiceInfo();
7063 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7064 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7065 result.add(serviceInfo.packageName);
7070 mInjector.binderRestoreCallingIdentity(id);
7078 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7083 Preconditions.checkNotNull(who, "ComponentName is null");
7084 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7085 if (!isCallerWithSystemUid()) {
7086 throw new SecurityException(
7087 "Only the system can query if an input method is disabled by admin");
7089 synchronized (this) {
7090 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7091 if (admin == null) {
7094 if (admin.permittedInputMethods == null) {
7097 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7098 admin.permittedInputMethods, userHandle);
7102 private void sendAdminEnabledBroadcastLocked(int userHandle) {
7103 DevicePolicyData policyData = getUserData(userHandle);
7104 if (policyData.mAdminBroadcastPending) {
7105 // Send the initialization data to profile owner and delete the data
7106 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7107 if (admin != null) {
7108 PersistableBundle initBundle = policyData.mInitBundle;
7109 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7110 initBundle == null ? null : new Bundle(initBundle), null);
7112 policyData.mInitBundle = null;
7113 policyData.mAdminBroadcastPending = false;
7114 saveSettingsLocked(userHandle);
7119 public UserHandle createAndManageUser(ComponentName admin, String name,
7120 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7121 Preconditions.checkNotNull(admin, "admin is null");
7122 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7123 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7124 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7125 + admin + " are not in the same package");
7127 // Only allow the system user to use this method
7128 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7129 throw new SecurityException("createAndManageUser was called from non-system user");
7131 if (!mInjector.userManagerIsSplitSystemUser()
7132 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7133 throw new IllegalArgumentException(
7134 "Ephemeral users are only supported on systems with a split system user.");
7137 UserHandle user = null;
7138 synchronized (this) {
7139 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7141 final long id = mInjector.binderClearCallingIdentity();
7143 int userInfoFlags = 0;
7144 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7145 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7147 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7149 if (userInfo != null) {
7150 user = userInfo.getUserHandle();
7153 mInjector.binderRestoreCallingIdentity(id);
7160 final long id = mInjector.binderClearCallingIdentity();
7162 final String adminPkg = admin.getPackageName();
7164 final int userHandle = user.getIdentifier();
7166 // Install the profile owner if not present.
7167 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7168 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7170 } catch (RemoteException e) {
7171 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7172 + "removing created user", e);
7173 mUserManager.removeUser(user.getIdentifier());
7177 setActiveAdmin(profileOwner, true, userHandle);
7178 // User is not started yet, the broadcast by setActiveAdmin will not be received.
7179 // So we store adminExtras for broadcasting when the user starts for first time.
7180 synchronized(this) {
7181 DevicePolicyData policyData = getUserData(userHandle);
7182 policyData.mInitBundle = adminExtras;
7183 policyData.mAdminBroadcastPending = true;
7184 saveSettingsLocked(userHandle);
7186 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7187 setProfileOwner(profileOwner, ownerName, userHandle);
7189 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7190 Settings.Secure.putIntForUser(mContext.getContentResolver(),
7191 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7196 mInjector.binderRestoreCallingIdentity(id);
7201 public boolean removeUser(ComponentName who, UserHandle userHandle) {
7202 Preconditions.checkNotNull(who, "ComponentName is null");
7203 synchronized (this) {
7204 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7206 long id = mInjector.binderClearCallingIdentity();
7208 return mUserManager.removeUser(userHandle.getIdentifier());
7210 mInjector.binderRestoreCallingIdentity(id);
7216 public boolean switchUser(ComponentName who, UserHandle userHandle) {
7217 Preconditions.checkNotNull(who, "ComponentName is null");
7218 synchronized (this) {
7219 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7221 long id = mInjector.binderClearCallingIdentity();
7223 int userId = UserHandle.USER_SYSTEM;
7224 if (userHandle != null) {
7225 userId = userHandle.getIdentifier();
7227 return mInjector.getIActivityManager().switchUser(userId);
7228 } catch (RemoteException e) {
7229 Log.e(LOG_TAG, "Couldn't switch user", e);
7232 mInjector.binderRestoreCallingIdentity(id);
7238 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7239 enforceCanManageApplicationRestrictions(who);
7241 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7242 final long id = mInjector.binderClearCallingIdentity();
7244 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7245 // if no restrictions were saved, mUserManager.getApplicationRestrictions
7246 // returns null, but DPM method should return an empty Bundle as per JavaDoc
7247 return bundle != null ? bundle : Bundle.EMPTY;
7249 mInjector.binderRestoreCallingIdentity(id);
7254 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7255 boolean suspended) {
7256 Preconditions.checkNotNull(who, "ComponentName is null");
7257 int callingUserId = UserHandle.getCallingUserId();
7258 synchronized (this) {
7259 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7261 long id = mInjector.binderClearCallingIdentity();
7263 return mIPackageManager.setPackagesSuspendedAsUser(
7264 packageNames, suspended, callingUserId);
7265 } catch (RemoteException re) {
7266 // Shouldn't happen.
7267 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7269 mInjector.binderRestoreCallingIdentity(id);
7271 return packageNames;
7276 public boolean isPackageSuspended(ComponentName who, String packageName) {
7277 Preconditions.checkNotNull(who, "ComponentName is null");
7278 int callingUserId = UserHandle.getCallingUserId();
7279 synchronized (this) {
7280 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7282 long id = mInjector.binderClearCallingIdentity();
7284 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7285 } catch (RemoteException re) {
7286 // Shouldn't happen.
7287 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7289 mInjector.binderRestoreCallingIdentity(id);
7296 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7297 Preconditions.checkNotNull(who, "ComponentName is null");
7298 if (!UserRestrictionsUtils.isValidRestriction(key)) {
7302 final int userHandle = mInjector.userHandleGetCallingUserId();
7303 synchronized (this) {
7304 ActiveAdmin activeAdmin =
7305 getActiveAdminForCallerLocked(who,
7306 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7307 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7308 if (isDeviceOwner) {
7309 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7310 throw new SecurityException("Device owner cannot set user restriction " + key);
7312 } else { // profile owner
7313 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7314 throw new SecurityException("Profile owner cannot set user restriction " + key);
7318 // Save the restriction to ActiveAdmin.
7319 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7320 saveSettingsLocked(userHandle);
7322 pushUserRestrictions(userHandle);
7324 sendChangedNotification(userHandle);
7328 private void pushUserRestrictions(int userId) {
7329 synchronized (this) {
7330 final Bundle global;
7331 final Bundle local = new Bundle();
7332 if (mOwners.isDeviceOwnerUserId(userId)) {
7333 global = new Bundle();
7335 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7336 if (deviceOwner == null) {
7337 return; // Shouldn't happen.
7340 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7342 // DO can disable camera globally.
7343 if (deviceOwner.disableCamera) {
7344 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7349 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7350 if (profileOwner != null) {
7351 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7354 // Also merge in *local* camera restriction.
7355 if (getCameraDisabled(/* who= */ null,
7356 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7357 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7359 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7364 public Bundle getUserRestrictions(ComponentName who) {
7368 Preconditions.checkNotNull(who, "ComponentName is null");
7369 synchronized (this) {
7370 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7371 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7372 return activeAdmin.userRestrictions;
7377 public boolean setApplicationHidden(ComponentName who, String packageName,
7379 Preconditions.checkNotNull(who, "ComponentName is null");
7380 int callingUserId = UserHandle.getCallingUserId();
7381 synchronized (this) {
7382 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7384 long id = mInjector.binderClearCallingIdentity();
7386 return mIPackageManager.setApplicationHiddenSettingAsUser(
7387 packageName, hidden, callingUserId);
7388 } catch (RemoteException re) {
7390 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7392 mInjector.binderRestoreCallingIdentity(id);
7399 public boolean isApplicationHidden(ComponentName who, String packageName) {
7400 Preconditions.checkNotNull(who, "ComponentName is null");
7401 int callingUserId = UserHandle.getCallingUserId();
7402 synchronized (this) {
7403 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7405 long id = mInjector.binderClearCallingIdentity();
7407 return mIPackageManager.getApplicationHiddenSettingAsUser(
7408 packageName, callingUserId);
7409 } catch (RemoteException re) {
7411 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7413 mInjector.binderRestoreCallingIdentity(id);
7420 public void enableSystemApp(ComponentName who, String packageName) {
7421 Preconditions.checkNotNull(who, "ComponentName is null");
7422 synchronized (this) {
7423 // This API can only be called by an active device admin,
7424 // so try to retrieve it to check that the caller is one.
7425 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7427 int userId = UserHandle.getCallingUserId();
7428 long id = mInjector.binderClearCallingIdentity();
7432 Slog.v(LOG_TAG, "installing " + packageName + " for "
7436 int parentUserId = getProfileParentId(userId);
7437 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7438 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7442 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7444 } catch (RemoteException re) {
7446 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7448 mInjector.binderRestoreCallingIdentity(id);
7454 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7455 Preconditions.checkNotNull(who, "ComponentName is null");
7456 synchronized (this) {
7457 // This API can only be called by an active device admin,
7458 // so try to retrieve it to check that the caller is one.
7459 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7461 int userId = UserHandle.getCallingUserId();
7462 long id = mInjector.binderClearCallingIdentity();
7465 int parentUserId = getProfileParentId(userId);
7466 List<ResolveInfo> activitiesToEnable = mIPackageManager
7467 .queryIntentActivities(intent,
7468 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7469 PackageManager.MATCH_DIRECT_BOOT_AWARE
7470 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7475 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7477 int numberOfAppsInstalled = 0;
7478 if (activitiesToEnable != null) {
7479 for (ResolveInfo info : activitiesToEnable) {
7480 if (info.activityInfo != null) {
7481 String packageName = info.activityInfo.packageName;
7482 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7483 numberOfAppsInstalled++;
7484 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7486 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7492 return numberOfAppsInstalled;
7493 } catch (RemoteException e) {
7495 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7498 mInjector.binderRestoreCallingIdentity(id);
7503 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7504 throws RemoteException {
7505 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7507 if (appInfo == null) {
7508 throw new IllegalArgumentException("The application " + packageName +
7509 " is not present on this device");
7511 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7515 public void setAccountManagementDisabled(ComponentName who, String accountType,
7520 Preconditions.checkNotNull(who, "ComponentName is null");
7521 synchronized (this) {
7522 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7523 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7525 ap.accountTypesWithManagementDisabled.add(accountType);
7527 ap.accountTypesWithManagementDisabled.remove(accountType);
7529 saveSettingsLocked(UserHandle.getCallingUserId());
7534 public String[] getAccountTypesWithManagementDisabled() {
7535 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7539 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7540 enforceFullCrossUsersPermission(userId);
7544 synchronized (this) {
7545 DevicePolicyData policy = getUserData(userId);
7546 final int N = policy.mAdminList.size();
7547 ArraySet<String> resultSet = new ArraySet<>();
7548 for (int i = 0; i < N; i++) {
7549 ActiveAdmin admin = policy.mAdminList.get(i);
7550 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7552 return resultSet.toArray(new String[resultSet.size()]);
7557 public void setUninstallBlocked(ComponentName who, String packageName,
7558 boolean uninstallBlocked) {
7559 Preconditions.checkNotNull(who, "ComponentName is null");
7560 final int userId = UserHandle.getCallingUserId();
7561 synchronized (this) {
7562 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7564 long id = mInjector.binderClearCallingIdentity();
7566 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7567 } catch (RemoteException re) {
7568 // Shouldn't happen.
7569 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7571 mInjector.binderRestoreCallingIdentity(id);
7577 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7578 // This function should return true if and only if the package is blocked by
7579 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7580 // when the package is a system app, or when it is an active device admin.
7581 final int userId = UserHandle.getCallingUserId();
7583 synchronized (this) {
7585 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7588 long id = mInjector.binderClearCallingIdentity();
7590 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7591 } catch (RemoteException re) {
7592 // Shouldn't happen.
7593 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7595 mInjector.binderRestoreCallingIdentity(id);
7602 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7606 Preconditions.checkNotNull(who, "ComponentName is null");
7607 synchronized (this) {
7608 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7609 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7610 if (admin.disableCallerId != disabled) {
7611 admin.disableCallerId = disabled;
7612 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7618 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7622 Preconditions.checkNotNull(who, "ComponentName is null");
7623 synchronized (this) {
7624 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7625 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7626 return admin.disableCallerId;
7631 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7632 enforceCrossUsersPermission(userId);
7633 synchronized (this) {
7634 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7635 return (admin != null) ? admin.disableCallerId : false;
7640 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7644 Preconditions.checkNotNull(who, "ComponentName is null");
7645 synchronized (this) {
7646 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7647 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7648 if (admin.disableContactsSearch != disabled) {
7649 admin.disableContactsSearch = disabled;
7650 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7656 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7660 Preconditions.checkNotNull(who, "ComponentName is null");
7661 synchronized (this) {
7662 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7663 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7664 return admin.disableContactsSearch;
7669 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7670 enforceCrossUsersPermission(userId);
7671 synchronized (this) {
7672 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7673 return (admin != null) ? admin.disableContactsSearch : false;
7678 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7679 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7680 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7681 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7682 final int callingUserId = UserHandle.getCallingUserId();
7684 final long ident = mInjector.binderClearCallingIdentity();
7686 synchronized (this) {
7687 final int managedUserId = getManagedUserId(callingUserId);
7688 if (managedUserId < 0) {
7691 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7694 "Cross-profile contacts access disabled for user " + managedUserId);
7698 ContactsInternal.startQuickContactWithErrorToastForUser(
7699 mContext, intent, new UserHandle(managedUserId));
7702 mInjector.binderRestoreCallingIdentity(ident);
7707 * @return true if cross-profile QuickContact is disabled
7709 private boolean isCrossProfileQuickContactDisabled(int userId) {
7710 return getCrossProfileCallerIdDisabledForUser(userId)
7711 && getCrossProfileContactsSearchDisabledForUser(userId);
7715 * @return the user ID of the managed user that is linked to the current user, if any.
7718 public int getManagedUserId(int callingUserId) {
7720 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7723 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7724 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7725 continue; // Caller user self, or not a managed profile. Skip.
7728 Log.v(LOG_TAG, "Managed user=" + ui.id);
7733 Log.v(LOG_TAG, "Managed user not found.");
7739 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7743 Preconditions.checkNotNull(who, "ComponentName is null");
7744 synchronized (this) {
7745 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7746 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7747 if (admin.disableBluetoothContactSharing != disabled) {
7748 admin.disableBluetoothContactSharing = disabled;
7749 saveSettingsLocked(UserHandle.getCallingUserId());
7755 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
7759 Preconditions.checkNotNull(who, "ComponentName is null");
7760 synchronized (this) {
7761 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7762 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7763 return admin.disableBluetoothContactSharing;
7768 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
7769 // TODO: Should there be a check to make sure this relationship is
7770 // within a profile group?
7771 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
7772 synchronized (this) {
7773 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7774 return (admin != null) ? admin.disableBluetoothContactSharing : false;
7779 * Sets which packages may enter lock task mode.
7781 * <p>This function can only be called by the device owner or alternatively by the profile owner
7782 * in case the user is affiliated.
7784 * @param packages The list of packages allowed to enter lock task mode.
7787 public void setLockTaskPackages(ComponentName who, String[] packages)
7788 throws SecurityException {
7789 Preconditions.checkNotNull(who, "ComponentName is null");
7790 synchronized (this) {
7791 ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
7792 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
7793 ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
7794 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
7795 if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
7796 int userHandle = mInjector.userHandleGetCallingUserId();
7797 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
7799 throw new SecurityException("Admin " + who +
7800 " is neither the device owner or affiliated user's profile owner.");
7805 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
7806 DevicePolicyData policy = getUserData(userHandle);
7807 policy.mLockTaskPackages = packages;
7809 // Store the settings persistently.
7810 saveSettingsLocked(userHandle);
7811 updateLockTaskPackagesLocked(packages, userHandle);
7815 * This function returns the list of components allowed to start the task lock mode.
7818 public String[] getLockTaskPackages(ComponentName who) {
7819 Preconditions.checkNotNull(who, "ComponentName is null");
7820 synchronized (this) {
7821 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7822 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
7823 final List<String> packages = getLockTaskPackagesLocked(userHandle);
7824 return packages.toArray(new String[packages.size()]);
7828 private List<String> getLockTaskPackagesLocked(int userHandle) {
7829 final DevicePolicyData policy = getUserData(userHandle);
7830 return policy.mLockTaskPackages;
7834 * This function lets the caller know whether the given package is allowed to start the
7836 * @param pkg The package to check
7839 public boolean isLockTaskPermitted(String pkg) {
7840 // Get current user's devicepolicy
7841 int uid = mInjector.binderGetCallingUid();
7842 int userHandle = UserHandle.getUserId(uid);
7843 DevicePolicyData policy = getUserData(userHandle);
7844 synchronized (this) {
7845 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
7846 String lockTaskPackage = policy.mLockTaskPackages.get(i);
7848 // If the given package equals one of the packages stored our list,
7849 // we allow this package to start lock task mode.
7850 if (lockTaskPackage.equals(pkg)) {
7859 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
7860 if (!isCallerWithSystemUid()) {
7861 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
7863 synchronized (this) {
7864 final DevicePolicyData policy = getUserData(userHandle);
7865 Bundle adminExtras = new Bundle();
7866 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
7867 for (ActiveAdmin admin : policy.mAdminList) {
7868 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
7869 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
7870 if (ownsDevice || ownsProfile) {
7872 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
7875 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
7883 public void setGlobalSetting(ComponentName who, String setting, String value) {
7884 Preconditions.checkNotNull(who, "ComponentName is null");
7886 synchronized (this) {
7887 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7889 // Some settings are no supported any more. However we do not want to throw a
7890 // SecurityException to avoid breaking apps.
7891 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
7892 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
7896 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
7897 throw new SecurityException(String.format(
7898 "Permission denial: device owners cannot update %1$s", setting));
7901 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
7902 // ignore if it contradicts an existing policy
7903 long timeMs = getMaximumTimeToLock(
7904 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
7905 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
7910 long id = mInjector.binderClearCallingIdentity();
7912 mInjector.settingsGlobalPutString(setting, value);
7914 mInjector.binderRestoreCallingIdentity(id);
7920 public void setSecureSetting(ComponentName who, String setting, String value) {
7921 Preconditions.checkNotNull(who, "ComponentName is null");
7922 int callingUserId = mInjector.userHandleGetCallingUserId();
7924 synchronized (this) {
7925 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7927 if (isDeviceOwner(who, callingUserId)) {
7928 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
7929 throw new SecurityException(String.format(
7930 "Permission denial: Device owners cannot update %1$s", setting));
7932 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
7933 throw new SecurityException(String.format(
7934 "Permission denial: Profile owners cannot update %1$s", setting));
7937 long id = mInjector.binderClearCallingIdentity();
7939 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
7941 mInjector.binderRestoreCallingIdentity(id);
7947 public void setMasterVolumeMuted(ComponentName who, boolean on) {
7948 Preconditions.checkNotNull(who, "ComponentName is null");
7949 synchronized (this) {
7950 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7951 setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
7956 public boolean isMasterVolumeMuted(ComponentName who) {
7957 Preconditions.checkNotNull(who, "ComponentName is null");
7958 synchronized (this) {
7959 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7961 AudioManager audioManager =
7962 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
7963 return audioManager.isMasterMute();
7968 public void setUserIcon(ComponentName who, Bitmap icon) {
7969 synchronized (this) {
7970 Preconditions.checkNotNull(who, "ComponentName is null");
7971 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7973 int userId = UserHandle.getCallingUserId();
7974 long id = mInjector.binderClearCallingIdentity();
7976 mUserManagerInternal.setUserIcon(userId, icon);
7978 mInjector.binderRestoreCallingIdentity(id);
7984 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
7985 Preconditions.checkNotNull(who, "ComponentName is null");
7986 synchronized (this) {
7987 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7989 final int userId = UserHandle.getCallingUserId();
7991 long ident = mInjector.binderClearCallingIdentity();
7993 // disallow disabling the keyguard if a password is currently set
7994 if (disabled && mLockPatternUtils.isSecure(userId)) {
7997 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
7999 mInjector.binderRestoreCallingIdentity(ident);
8005 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8006 int userId = UserHandle.getCallingUserId();
8007 synchronized (this) {
8008 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8009 DevicePolicyData policy = getUserData(userId);
8010 if (policy.mStatusBarDisabled != disabled) {
8011 if (!setStatusBarDisabledInternal(disabled, userId)) {
8014 policy.mStatusBarDisabled = disabled;
8015 saveSettingsLocked(userId);
8021 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8022 long ident = mInjector.binderClearCallingIdentity();
8024 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8025 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8026 if (statusBarService != null) {
8027 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8028 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8029 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8030 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8033 } catch (RemoteException e) {
8034 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8036 mInjector.binderRestoreCallingIdentity(ident);
8042 * We need to update the internal state of whether a user has completed setup once. After
8043 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
8044 * as we don't trust any apps that might try to reset it.
8046 * Unfortunately, we don't know which user's setup state was changed, so we write all of
8049 void updateUserSetupComplete() {
8050 List<UserInfo> users = mUserManager.getUsers(true);
8051 final int N = users.size();
8052 for (int i = 0; i < N; i++) {
8053 int userHandle = users.get(i).id;
8054 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8056 DevicePolicyData policy = getUserData(userHandle);
8057 if (!policy.mUserSetupComplete) {
8058 policy.mUserSetupComplete = true;
8059 synchronized (this) {
8060 saveSettingsLocked(userHandle);
8067 private class SetupContentObserver extends ContentObserver {
8069 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8070 Settings.Secure.USER_SETUP_COMPLETE);
8071 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8072 Settings.Global.DEVICE_PROVISIONED);
8074 public SetupContentObserver(Handler handler) {
8079 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8080 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8084 public void onChange(boolean selfChange, Uri uri) {
8085 if (mUserSetupComplete.equals(uri)) {
8086 updateUserSetupComplete();
8087 } else if (mDeviceProvisioned.equals(uri)) {
8088 synchronized (DevicePolicyManagerService.this) {
8089 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8090 // is delayed until device is marked as provisioned.
8091 setDeviceOwnerSystemPropertyLocked();
8098 final class LocalService extends DevicePolicyManagerInternal {
8099 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8102 public List<String> getCrossProfileWidgetProviders(int profileId) {
8103 synchronized (DevicePolicyManagerService.this) {
8104 if (mOwners == null) {
8105 return Collections.emptyList();
8107 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8108 if (ownerComponent == null) {
8109 return Collections.emptyList();
8112 DevicePolicyData policy = getUserDataUnchecked(profileId);
8113 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8115 if (admin == null || admin.crossProfileWidgetProviders == null
8116 || admin.crossProfileWidgetProviders.isEmpty()) {
8117 return Collections.emptyList();
8120 return admin.crossProfileWidgetProviders;
8125 public void addOnCrossProfileWidgetProvidersChangeListener(
8126 OnCrossProfileWidgetProvidersChangeListener listener) {
8127 synchronized (DevicePolicyManagerService.this) {
8128 if (mWidgetProviderListeners == null) {
8129 mWidgetProviderListeners = new ArrayList<>();
8131 if (!mWidgetProviderListeners.contains(listener)) {
8132 mWidgetProviderListeners.add(listener);
8138 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8139 synchronized(DevicePolicyManagerService.this) {
8140 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8144 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8145 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8146 synchronized (DevicePolicyManagerService.this) {
8147 listeners = new ArrayList<>(mWidgetProviderListeners);
8149 final int listenerCount = listeners.size();
8150 for (int i = 0; i < listenerCount; i++) {
8151 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8152 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8157 public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
8158 Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8159 intent.putExtra(Intent.EXTRA_USER_ID, userId);
8160 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8162 // This method is called from AM with its lock held, so don't take the DPMS lock.
8165 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8166 if (profileOwner != null) {
8167 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
8171 final Pair<Integer, ComponentName> deviceOwner =
8172 mOwners.getDeviceOwnerUserIdAndComponent();
8173 if (deviceOwner != null && deviceOwner.first == userId) {
8174 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
8178 // We're not specifying the device admin because there isn't one.
8184 * Returns true if specified admin is allowed to limit passwords and has a
8185 * {@code passwordQuality} of at least {@code minPasswordQuality}
8187 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8188 if (admin.passwordQuality < minPasswordQuality) {
8191 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8195 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8196 if (policy != null && !policy.isValid()) {
8197 throw new IllegalArgumentException("Invalid system update policy.");
8199 synchronized (this) {
8200 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8201 if (policy == null) {
8202 mOwners.clearSystemUpdatePolicy();
8204 mOwners.setSystemUpdatePolicy(policy);
8206 mOwners.writeDeviceOwner();
8208 mContext.sendBroadcastAsUser(
8209 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8214 public SystemUpdatePolicy getSystemUpdatePolicy() {
8215 if (UserManager.isDeviceInDemoMode(mContext)) {
8216 // Pretending to have an automatic update policy when the device is in retail demo
8217 // mode. This will allow the device to download and install an ota without
8218 // any user interaction.
8219 return SystemUpdatePolicy.createAutomaticInstallPolicy();
8221 synchronized (this) {
8222 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
8223 if (policy != null && !policy.isValid()) {
8224 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8232 * Checks if the caller of the method is the device owner app.
8234 * @param callerUid UID of the caller.
8235 * @return true if the caller is the device owner app
8238 boolean isCallerDeviceOwner(int callerUid) {
8239 synchronized (this) {
8240 if (!mOwners.hasDeviceOwner()) {
8243 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8246 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8248 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8250 for (String pkg : pkgs) {
8251 if (deviceOwnerPackageName.equals(pkg)) {
8261 public void notifyPendingSystemUpdate(long updateReceivedTime) {
8262 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8263 "Only the system update service can broadcast update information");
8265 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8266 Slog.w(LOG_TAG, "Only the system update service in the system user " +
8267 "can broadcast update information.");
8270 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8271 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8272 updateReceivedTime);
8274 synchronized (this) {
8275 final String deviceOwnerPackage =
8276 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8278 if (deviceOwnerPackage == null) {
8281 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8283 ActivityInfo[] receivers = null;
8285 receivers = mContext.getPackageManager().getPackageInfo(
8286 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8287 } catch (NameNotFoundException e) {
8288 Log.e(LOG_TAG, "Cannot find device owner package", e);
8290 if (receivers != null) {
8291 long ident = mInjector.binderClearCallingIdentity();
8293 for (int i = 0; i < receivers.length; i++) {
8294 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8295 intent.setComponent(new ComponentName(deviceOwnerPackage,
8296 receivers[i].name));
8297 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8301 mInjector.binderRestoreCallingIdentity(ident);
8308 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8309 int userId = UserHandle.getCallingUserId();
8310 synchronized (this) {
8311 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8312 DevicePolicyData userPolicy = getUserData(userId);
8313 if (userPolicy.mPermissionPolicy != policy) {
8314 userPolicy.mPermissionPolicy = policy;
8315 saveSettingsLocked(userId);
8321 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8322 int userId = UserHandle.getCallingUserId();
8323 synchronized (this) {
8324 DevicePolicyData userPolicy = getUserData(userId);
8325 return userPolicy.mPermissionPolicy;
8330 public boolean setPermissionGrantState(ComponentName admin, String packageName,
8331 String permission, int grantState) throws RemoteException {
8332 UserHandle user = mInjector.binderGetCallingUserHandle();
8333 synchronized (this) {
8334 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8335 long ident = mInjector.binderClearCallingIdentity();
8337 if (getTargetSdk(packageName, user.getIdentifier())
8338 < android.os.Build.VERSION_CODES.M) {
8341 final PackageManager packageManager = mContext.getPackageManager();
8342 switch (grantState) {
8343 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8344 packageManager.grantRuntimePermission(packageName, permission, user);
8345 packageManager.updatePermissionFlags(permission, packageName,
8346 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8347 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8350 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8351 packageManager.revokeRuntimePermission(packageName,
8353 packageManager.updatePermissionFlags(permission, packageName,
8354 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8355 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8358 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8359 packageManager.updatePermissionFlags(permission, packageName,
8360 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8364 } catch (SecurityException se) {
8367 mInjector.binderRestoreCallingIdentity(ident);
8373 public int getPermissionGrantState(ComponentName admin, String packageName,
8374 String permission) throws RemoteException {
8375 PackageManager packageManager = mContext.getPackageManager();
8377 UserHandle user = mInjector.binderGetCallingUserHandle();
8378 synchronized (this) {
8379 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8380 long ident = mInjector.binderClearCallingIdentity();
8382 int granted = mIPackageManager.checkPermission(permission,
8383 packageName, user.getIdentifier());
8384 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8385 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8386 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8387 // Not controlled by policy
8388 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8390 // Policy controlled so return result based on permission grant state
8391 return granted == PackageManager.PERMISSION_GRANTED
8392 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8393 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8396 mInjector.binderRestoreCallingIdentity(ident);
8401 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8403 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8405 return (pi != null) && (pi.applicationInfo.flags != 0);
8406 } catch (RemoteException re) {
8407 throw new RuntimeException("Package manager has died", re);
8412 public boolean isProvisioningAllowed(String action) {
8417 final int callingUserId = mInjector.userHandleGetCallingUserId();
8418 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8419 if (!hasFeatureManagedUsers()) {
8422 synchronized (this) {
8423 if (mOwners.hasDeviceOwner()) {
8424 if (!mInjector.userManagerIsSplitSystemUser()) {
8425 // Only split-system-user systems support managed-profiles in combination with
8429 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8430 // Only system device-owner supports managed-profiles. Non-system device-owner
8434 if (callingUserId == UserHandle.USER_SYSTEM) {
8435 // Managed-profiles cannot be setup on the system user, only regular users.
8440 if (getProfileOwner(callingUserId) != null) {
8441 // Managed user cannot have a managed profile.
8444 final long ident = mInjector.binderClearCallingIdentity();
8446 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8450 mInjector.binderRestoreCallingIdentity(ident);
8453 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8454 return isDeviceOwnerProvisioningAllowed(callingUserId);
8455 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8456 if (!hasFeatureManagedUsers()) {
8459 if (!mInjector.userManagerIsSplitSystemUser()) {
8460 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8463 if (callingUserId == UserHandle.USER_SYSTEM) {
8464 // System user cannot be a managed user.
8467 if (hasUserSetupCompleted(callingUserId)) {
8471 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8472 if (!mInjector.userManagerIsSplitSystemUser()) {
8473 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8476 return isDeviceOwnerProvisioningAllowed(callingUserId);
8478 throw new IllegalArgumentException("Unknown provisioning action " + action);
8482 * The device owner can only be set before the setup phase of the primary user has completed,
8483 * except for adb command if no accounts or additional users are present on the device.
8485 private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreCondition(
8486 @Nullable ComponentName owner, int deviceOwnerUserId, boolean isAdb) {
8487 if (mOwners.hasDeviceOwner()) {
8488 return CODE_HAS_DEVICE_OWNER;
8490 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8491 return CODE_USER_HAS_PROFILE_OWNER;
8493 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8494 return CODE_USER_NOT_RUNNING;
8497 // if shell command runs after user setup completed check device status. Otherwise, OK.
8498 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8499 if (!mInjector.userManagerIsSplitSystemUser()) {
8500 if (mUserManager.getUserCount() > 1) {
8501 return CODE_NONSYSTEM_USER_EXISTS;
8503 if (hasIncompatibleAccounts(UserHandle.USER_SYSTEM, owner)) {
8504 return CODE_ACCOUNTS_NOT_EMPTY;
8507 // STOPSHIP Do proper check in split user mode
8512 if (!mInjector.userManagerIsSplitSystemUser()) {
8513 // In non-split user mode, DO has to be user 0
8514 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8515 return CODE_NOT_SYSTEM_USER;
8517 // In non-split user mode, only provision DO before setup wizard completes
8518 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8519 return CODE_USER_SETUP_COMPLETED;
8522 // STOPSHIP Do proper check in split user mode
8528 private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8529 return CODE_OK == checkSetDeviceOwnerPreCondition(
8530 /* owner unknown */ null, deviceOwnerUserId, /* isAdb */ false);
8533 private boolean hasFeatureManagedUsers() {
8535 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8536 } catch (RemoteException e) {
8542 public String getWifiMacAddress(ComponentName admin) {
8543 // Make sure caller has DO.
8544 synchronized (this) {
8545 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8548 final long ident = mInjector.binderClearCallingIdentity();
8550 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8551 if (wifiInfo == null) {
8554 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8556 mInjector.binderRestoreCallingIdentity(ident);
8561 * Returns the target sdk version number that the given packageName was built for
8562 * in the given user.
8564 private int getTargetSdk(String packageName, int userId) {
8565 final ApplicationInfo ai;
8567 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8568 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8569 return targetSdkVersion;
8570 } catch (RemoteException e) {
8577 public boolean isManagedProfile(ComponentName admin) {
8578 synchronized (this) {
8579 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8581 final int callingUserId = mInjector.userHandleGetCallingUserId();
8582 final UserInfo user = getUserInfo(callingUserId);
8583 return user != null && user.isManagedProfile();
8587 public boolean isSystemOnlyUser(ComponentName admin) {
8588 synchronized (this) {
8589 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8591 final int callingUserId = mInjector.userHandleGetCallingUserId();
8592 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8596 public void reboot(ComponentName admin) {
8597 Preconditions.checkNotNull(admin);
8598 // Make sure caller has DO.
8599 synchronized (this) {
8600 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8602 long ident = mInjector.binderClearCallingIdentity();
8604 // Make sure there are no ongoing calls on the device.
8605 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8606 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8608 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8610 mInjector.binderRestoreCallingIdentity(ident);
8615 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8619 Preconditions.checkNotNull(who, "ComponentName is null");
8620 final int userHandle = mInjector.userHandleGetCallingUserId();
8621 synchronized (this) {
8622 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8623 mInjector.binderGetCallingUid());
8624 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8625 admin.shortSupportMessage = message;
8626 saveSettingsLocked(userHandle);
8632 public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8636 Preconditions.checkNotNull(who, "ComponentName is null");
8637 synchronized (this) {
8638 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8639 mInjector.binderGetCallingUid());
8640 return admin.shortSupportMessage;
8645 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8649 Preconditions.checkNotNull(who, "ComponentName is null");
8650 final int userHandle = mInjector.userHandleGetCallingUserId();
8651 synchronized (this) {
8652 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8653 mInjector.binderGetCallingUid());
8654 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8655 admin.longSupportMessage = message;
8656 saveSettingsLocked(userHandle);
8662 public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8666 Preconditions.checkNotNull(who, "ComponentName is null");
8667 synchronized (this) {
8668 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8669 mInjector.binderGetCallingUid());
8670 return admin.longSupportMessage;
8675 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8679 Preconditions.checkNotNull(who, "ComponentName is null");
8680 if (!isCallerWithSystemUid()) {
8681 throw new SecurityException("Only the system can query support message for user");
8683 synchronized (this) {
8684 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8685 if (admin != null) {
8686 return admin.shortSupportMessage;
8693 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8697 Preconditions.checkNotNull(who, "ComponentName is null");
8698 if (!isCallerWithSystemUid()) {
8699 throw new SecurityException("Only the system can query support message for user");
8701 synchronized (this) {
8702 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8703 if (admin != null) {
8704 return admin.longSupportMessage;
8711 public void setOrganizationColor(@NonNull ComponentName who, int color) {
8715 Preconditions.checkNotNull(who, "ComponentName is null");
8716 final int userHandle = mInjector.userHandleGetCallingUserId();
8717 enforceManagedProfile(userHandle, "set organization color");
8718 synchronized (this) {
8719 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8720 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8721 admin.organizationColor = color;
8722 saveSettingsLocked(userHandle);
8727 public void setOrganizationColorForUser(int color, int userId) {
8731 enforceFullCrossUsersPermission(userId);
8732 enforceManageUsers();
8733 enforceManagedProfile(userId, "set organization color");
8734 synchronized (this) {
8735 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8736 admin.organizationColor = color;
8737 saveSettingsLocked(userId);
8742 public int getOrganizationColor(@NonNull ComponentName who) {
8744 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8746 Preconditions.checkNotNull(who, "ComponentName is null");
8747 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
8748 synchronized (this) {
8749 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8750 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8751 return admin.organizationColor;
8756 public int getOrganizationColorForUser(int userHandle) {
8758 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8760 enforceFullCrossUsersPermission(userHandle);
8761 enforceManagedProfile(userHandle, "get organization color");
8762 synchronized (this) {
8763 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8764 return (profileOwner != null)
8765 ? profileOwner.organizationColor
8766 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
8771 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
8775 Preconditions.checkNotNull(who, "ComponentName is null");
8776 final int userHandle = mInjector.userHandleGetCallingUserId();
8777 enforceManagedProfile(userHandle, "set organization name");
8778 synchronized (this) {
8779 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8780 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8781 if (!TextUtils.equals(admin.organizationName, text)) {
8782 admin.organizationName = (text == null || text.length() == 0)
8783 ? null : text.toString();
8784 saveSettingsLocked(userHandle);
8790 public CharSequence getOrganizationName(@NonNull ComponentName who) {
8794 Preconditions.checkNotNull(who, "ComponentName is null");
8795 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
8796 synchronized(this) {
8797 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8798 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8799 return admin.organizationName;
8804 public CharSequence getOrganizationNameForUser(int userHandle) {
8808 enforceFullCrossUsersPermission(userHandle);
8809 enforceManagedProfile(userHandle, "get organization name");
8810 synchronized (this) {
8811 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8812 return (profileOwner != null)
8813 ? profileOwner.organizationName
8819 public void setAffiliationIds(ComponentName admin, List<String> ids) {
8820 final Set<String> affiliationIds = new ArraySet<String>(ids);
8821 final int callingUserId = mInjector.userHandleGetCallingUserId();
8823 synchronized (this) {
8824 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8825 getUserData(callingUserId).mAffiliationIds = affiliationIds;
8826 saveSettingsLocked(callingUserId);
8827 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
8828 // Affiliation ids specified by the device owner are additionally stored in
8829 // UserHandle.USER_SYSTEM's DevicePolicyData.
8830 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
8831 saveSettingsLocked(UserHandle.USER_SYSTEM);
8837 public boolean isAffiliatedUser() {
8838 final int callingUserId = mInjector.userHandleGetCallingUserId();
8840 synchronized (this) {
8841 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
8842 // The user that the DO is installed on is always affiliated.
8845 final ComponentName profileOwner = getProfileOwner(callingUserId);
8846 if (profileOwner == null
8847 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
8850 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
8851 final Set<String> deviceAffiliationIds =
8852 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
8853 for (String id : userAffiliationIds) {
8854 if (deviceAffiliationIds.contains(id)) {
8862 private synchronized void disableSecurityLoggingIfNotCompliant() {
8863 if (!isDeviceOwnerManagedSingleUserDevice()) {
8864 mInjector.securityLogSetLoggingEnabledProperty(false);
8865 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user device.");
8870 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
8871 Preconditions.checkNotNull(admin);
8872 ensureDeviceOwnerManagingSingleUser(admin);
8874 synchronized (this) {
8875 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
8878 mInjector.securityLogSetLoggingEnabledProperty(enabled);
8880 mSecurityLogMonitor.start();
8882 mSecurityLogMonitor.stop();
8888 public boolean isSecurityLoggingEnabled(ComponentName admin) {
8889 Preconditions.checkNotNull(admin);
8890 synchronized (this) {
8891 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8892 return mInjector.securityLogGetLoggingEnabledProperty();
8897 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
8898 Preconditions.checkNotNull(admin);
8899 ensureDeviceOwnerManagingSingleUser(admin);
8901 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
8905 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
8907 SecurityLog.readPreviousEvents(output);
8908 return new ParceledListSlice<SecurityEvent>(output);
8909 } catch (IOException e) {
8910 Slog.w(LOG_TAG, "Fail to read previous events" , e);
8911 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
8916 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
8917 Preconditions.checkNotNull(admin);
8918 ensureDeviceOwnerManagingSingleUser(admin);
8920 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
8921 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
8924 private void enforceCanManageDeviceAdmin() {
8925 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
8929 private void enforceCanManageProfileAndDeviceOwners() {
8930 mContext.enforceCallingOrSelfPermission(
8931 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
8935 public boolean isUninstallInQueue(final String packageName) {
8936 enforceCanManageDeviceAdmin();
8937 final int userId = mInjector.userHandleGetCallingUserId();
8938 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8939 synchronized (this) {
8940 return mPackagesToRemove.contains(packageUserPair);
8945 public void uninstallPackageWithActiveAdmins(final String packageName) {
8946 enforceCanManageDeviceAdmin();
8947 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
8949 final int userId = mInjector.userHandleGetCallingUserId();
8951 enforceUserUnlocked(userId);
8953 final ComponentName profileOwner = getProfileOwner(userId);
8954 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
8955 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
8958 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
8959 if (getDeviceOwnerUserId() == userId && deviceOwner != null
8960 && packageName.equals(deviceOwner.getPackageName())) {
8961 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
8964 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8965 synchronized (this) {
8966 mPackagesToRemove.add(packageUserPair);
8969 // All active admins on the user.
8970 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
8972 // Active admins in the target package.
8973 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
8974 if (allActiveAdmins != null) {
8975 for (ComponentName activeAdmin : allActiveAdmins) {
8976 if (packageName.equals(activeAdmin.getPackageName())) {
8977 packageActiveAdmins.add(activeAdmin);
8978 removeActiveAdmin(activeAdmin, userId);
8982 if (packageActiveAdmins.size() == 0) {
8983 startUninstallIntent(packageName, userId);
8985 mHandler.postDelayed(new Runnable() {
8988 for (ComponentName activeAdmin : packageActiveAdmins) {
8989 removeAdminArtifacts(activeAdmin, userId);
8991 startUninstallIntent(packageName, userId);
8993 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
8998 public boolean isDeviceProvisioned() {
8999 return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9002 private void removePackageIfRequired(final String packageName, final int userId) {
9003 if (!packageHasActiveAdmins(packageName, userId)) {
9004 // Will not do anything if uninstall was not requested or was already started.
9005 startUninstallIntent(packageName, userId);
9009 private void startUninstallIntent(final String packageName, final int userId) {
9010 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9011 synchronized (this) {
9012 if (!mPackagesToRemove.contains(packageUserPair)) {
9013 // Do nothing if uninstall was not requested or was already started.
9016 mPackagesToRemove.remove(packageUserPair);
9019 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9020 // Package does not exist. Nothing to do.
9023 } catch (RemoteException re) {
9024 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9027 try { // force stop the package before uninstalling
9028 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9029 } catch (RemoteException re) {
9030 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9032 final Uri packageURI = Uri.parse("package:" + packageName);
9033 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9034 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9035 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9039 * Removes the admin from the policy. Ideally called after the admin's
9040 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9042 * @param adminReceiver The admin to remove
9043 * @param userHandle The user for which this admin has to be removed.
9045 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9046 synchronized (this) {
9047 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9048 if (admin == null) {
9051 final DevicePolicyData policy = getUserData(userHandle);
9052 final boolean doProxyCleanup = admin.info.usesPolicy(
9053 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9054 policy.mAdminList.remove(admin);
9055 policy.mAdminMap.remove(adminReceiver);
9056 validatePasswordOwnerLocked(policy);
9057 if (doProxyCleanup) {
9058 resetGlobalProxyLocked(policy);
9060 saveSettingsLocked(userHandle);
9061 updateMaximumTimeToLockLocked(userHandle);
9062 policy.mRemovingAdmins.remove(adminReceiver);
9064 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
9066 // The removed admin might have disabled camera, so update user
9068 pushUserRestrictions(userHandle);
9072 public void setDeviceProvisioningConfigApplied() {
9073 enforceManageUsers();
9074 synchronized (this) {
9075 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9076 policy.mDeviceProvisioningConfigApplied = true;
9077 saveSettingsLocked(UserHandle.USER_SYSTEM);
9082 public boolean isDeviceProvisioningConfigApplied() {
9083 enforceManageUsers();
9084 synchronized (this) {
9085 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9086 return policy.mDeviceProvisioningConfigApplied;
9091 * Return true if a given user has any accounts that'll prevent installing a device or profile
9092 * owner {@code owner}.
9093 * - If the user has no accounts, then return false.
9094 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
9095 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
9096 * ..._DISALLOWED, return true.
9097 * - Otherwise return false.
9099 private boolean hasIncompatibleAccounts(int userId, @Nullable ComponentName owner) {
9100 final long token = mInjector.binderClearCallingIdentity();
9102 final AccountManager am = AccountManager.get(mContext);
9103 final Account accounts[] = am.getAccountsAsUser(userId);
9104 if (accounts.length == 0) {
9107 final String[] feature_allow =
9108 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
9109 final String[] feature_disallow =
9110 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
9112 // Even if we find incompatible accounts along the way, we still check all accounts
9114 boolean compatible = true;
9115 for (Account account : accounts) {
9116 if (hasAccountFeatures(am, account, feature_disallow)) {
9117 Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
9120 if (!hasAccountFeatures(am, account, feature_allow)) {
9121 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
9126 Log.w(LOG_TAG, "All accounts are compatible");
9128 Log.e(LOG_TAG, "Found incompatible accounts");
9131 // Then check if the owner is test-only.
9133 if (owner == null) {
9134 // Owner is unknown. Suppose it's not test-only
9136 log = "Only test-only device/profile owner can be installed with accounts";
9137 } else if (isPackageTestOnly(owner.getPackageName(), userId)) {
9139 log = "Installing test-only owner " + owner;
9141 log = "Can't install test-only owner " + owner + " with incompatible accounts";
9145 log = "Can't install non test-only owner " + owner + " with accounts";
9148 Log.w(LOG_TAG, log);
9150 Log.e(LOG_TAG, log);
9154 mInjector.binderRestoreCallingIdentity(token);
9158 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
9160 return am.hasFeatures(account, features, null, null).getResult();
9161 } catch (Exception e) {
9162 Log.w(LOG_TAG, "Failed to get account feature", e);