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.AccountManager;
33 import android.annotation.IntDef;
34 import android.annotation.NonNull;
35 import android.annotation.Nullable;
36 import android.annotation.UserIdInt;
37 import android.app.Activity;
38 import android.app.ActivityManager;
39 import android.app.ActivityManagerNative;
40 import android.app.AlarmManager;
41 import android.app.AppGlobals;
42 import android.app.IActivityManager;
43 import android.app.Notification;
44 import android.app.NotificationManager;
45 import android.app.PendingIntent;
46 import android.app.StatusBarManager;
47 import android.app.admin.DeviceAdminInfo;
48 import android.app.admin.DeviceAdminReceiver;
49 import android.app.admin.DevicePolicyManager;
50 import android.app.admin.DevicePolicyManagerInternal;
51 import android.app.admin.IDevicePolicyManager;
52 import android.app.admin.SecurityLog;
53 import android.app.admin.SecurityLog.SecurityEvent;
54 import android.app.admin.SystemUpdatePolicy;
55 import android.app.backup.IBackupManager;
56 import android.app.trust.TrustManager;
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 TrustManager getTrustManager() {
1375 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1378 IWindowManager getIWindowManager() {
1379 return IWindowManager.Stub
1380 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1383 IActivityManager getIActivityManager() {
1384 return ActivityManagerNative.getDefault();
1387 IPackageManager getIPackageManager() {
1388 return AppGlobals.getPackageManager();
1391 IBackupManager getIBackupManager() {
1392 return IBackupManager.Stub.asInterface(
1393 ServiceManager.getService(Context.BACKUP_SERVICE));
1396 IAudioService getIAudioService() {
1397 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1400 LockPatternUtils newLockPatternUtils() {
1401 return new LockPatternUtils(mContext);
1404 boolean storageManagerIsFileBasedEncryptionEnabled() {
1405 return StorageManager.isFileEncryptedNativeOnly();
1408 boolean storageManagerIsNonDefaultBlockEncrypted() {
1409 long identity = Binder.clearCallingIdentity();
1411 return StorageManager.isNonDefaultBlockEncrypted();
1413 Binder.restoreCallingIdentity(identity);
1417 boolean storageManagerIsEncrypted() {
1418 return StorageManager.isEncrypted();
1421 boolean storageManagerIsEncryptable() {
1422 return StorageManager.isEncryptable();
1425 Looper getMyLooper() {
1426 return Looper.myLooper();
1429 WifiManager getWifiManager() {
1430 return mContext.getSystemService(WifiManager.class);
1433 long binderClearCallingIdentity() {
1434 return Binder.clearCallingIdentity();
1437 void binderRestoreCallingIdentity(long token) {
1438 Binder.restoreCallingIdentity(token);
1441 int binderGetCallingUid() {
1442 return Binder.getCallingUid();
1445 int binderGetCallingPid() {
1446 return Binder.getCallingPid();
1449 UserHandle binderGetCallingUserHandle() {
1450 return Binder.getCallingUserHandle();
1453 boolean binderIsCallingUidMyUid() {
1454 return getCallingUid() == Process.myUid();
1457 final int userHandleGetCallingUserId() {
1458 return UserHandle.getUserId(binderGetCallingUid());
1461 File environmentGetUserSystemDirectory(int userId) {
1462 return Environment.getUserSystemDirectory(userId);
1465 void powerManagerGoToSleep(long time, int reason, int flags) {
1466 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1469 void powerManagerReboot(String reason) {
1470 mContext.getSystemService(PowerManager.class).reboot(reason);
1473 boolean systemPropertiesGetBoolean(String key, boolean def) {
1474 return SystemProperties.getBoolean(key, def);
1477 long systemPropertiesGetLong(String key, long def) {
1478 return SystemProperties.getLong(key, def);
1481 String systemPropertiesGet(String key, String def) {
1482 return SystemProperties.get(key, def);
1485 String systemPropertiesGet(String key) {
1486 return SystemProperties.get(key);
1489 void systemPropertiesSet(String key, String value) {
1490 SystemProperties.set(key, value);
1493 boolean userManagerIsSplitSystemUser() {
1494 return UserManager.isSplitSystemUser();
1497 String getDevicePolicyFilePathForSystemUser() {
1498 return "/data/system/";
1501 void registerContentObserver(Uri uri, boolean notifyForDescendents,
1502 ContentObserver observer, int userHandle) {
1503 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1504 observer, userHandle);
1507 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1508 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1509 name, def, userHandle);
1512 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1513 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1514 name, value, userHandle);
1517 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1518 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1519 name, value, userHandle);
1522 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1523 Settings.Global.putStringForUser(mContext.getContentResolver(),
1524 name, value, userHandle);
1527 void settingsSecurePutInt(String name, int value) {
1528 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1531 int settingsGlobalGetInt(String name, int def) {
1532 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1535 void settingsGlobalPutInt(String name, int value) {
1536 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1539 void settingsSecurePutString(String name, String value) {
1540 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1543 void settingsGlobalPutString(String name, String value) {
1544 Settings.Global.putString(mContext.getContentResolver(), name, value);
1547 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1548 SecurityLog.setLoggingEnabledProperty(enabled);
1551 boolean securityLogGetLoggingEnabledProperty() {
1552 return SecurityLog.getLoggingEnabledProperty();
1555 boolean securityLogIsLoggingEnabled() {
1556 return SecurityLog.isLoggingEnabled();
1561 * Instantiates the service.
1563 public DevicePolicyManagerService(Context context) {
1564 this(new Injector(context));
1568 DevicePolicyManagerService(Injector injector) {
1569 mInjector = injector;
1570 mContext = Preconditions.checkNotNull(injector.mContext);
1571 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1572 mOwners = Preconditions.checkNotNull(injector.newOwners());
1574 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1575 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1576 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1577 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1579 mLocalService = new LocalService();
1580 mLockPatternUtils = injector.newLockPatternUtils();
1582 mSecurityLogMonitor = new SecurityLogMonitor(this);
1584 mHasFeature = mContext.getPackageManager()
1585 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1587 // Skip the rest of the initialization
1590 IntentFilter filter = new IntentFilter();
1591 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1592 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1593 filter.addAction(Intent.ACTION_USER_ADDED);
1594 filter.addAction(Intent.ACTION_USER_REMOVED);
1595 filter.addAction(Intent.ACTION_USER_STARTED);
1596 filter.addAction(Intent.ACTION_USER_UNLOCKED);
1597 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1598 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1599 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1600 filter = new IntentFilter();
1601 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1602 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1603 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1604 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1605 filter.addDataScheme("package");
1606 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1607 filter = new IntentFilter();
1608 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1609 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1611 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1615 * Creates and loads the policy data from xml.
1616 * @param userHandle the user for whom to load the policy data
1620 DevicePolicyData getUserData(int userHandle) {
1621 synchronized (this) {
1622 DevicePolicyData policy = mUserData.get(userHandle);
1623 if (policy == null) {
1624 policy = new DevicePolicyData(userHandle);
1625 mUserData.append(userHandle, policy);
1626 loadSettingsLocked(policy, userHandle);
1633 * Creates and loads the policy data from xml for data that is shared between
1634 * various profiles of a user. In contrast to {@link #getUserData(int)}
1635 * it allows access to data of users other than the calling user.
1637 * This function should only be used for shared data, e.g. everything regarding
1638 * passwords and should be removed once multiple screen locks are present.
1639 * @param userHandle the user for whom to load the policy data
1642 DevicePolicyData getUserDataUnchecked(int userHandle) {
1643 long ident = mInjector.binderClearCallingIdentity();
1645 return getUserData(userHandle);
1647 mInjector.binderRestoreCallingIdentity(ident);
1651 void removeUserData(int userHandle) {
1652 synchronized (this) {
1653 if (userHandle == UserHandle.USER_SYSTEM) {
1654 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1657 mOwners.removeProfileOwner(userHandle);
1658 mOwners.writeProfileOwner(userHandle);
1660 DevicePolicyData policy = mUserData.get(userHandle);
1661 if (policy != null) {
1662 mUserData.remove(userHandle);
1664 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1665 DEVICE_POLICIES_XML);
1666 policyFile.delete();
1667 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1669 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1673 synchronized (this) {
1675 setDeviceOwnerSystemPropertyLocked();
1676 findOwnerComponentIfNecessaryLocked();
1677 migrateUserRestrictionsIfNecessaryLocked();
1679 // TODO PO may not have a class name either due to b/17652534. Address that too.
1681 updateDeviceOwnerLocked();
1685 private void setDeviceOwnerSystemPropertyLocked() {
1686 // Device owner may still be provisioned, do not set the read-only system property yet.
1687 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1690 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1691 // always false at this point.
1692 if (StorageManager.inCryptKeeperBounce()) {
1696 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1697 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1699 if (mOwners.hasDeviceOwner()) {
1700 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1701 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1702 disableSecurityLoggingIfNotCompliant();
1703 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1704 mSecurityLogMonitor.start();
1707 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1708 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1713 private void findOwnerComponentIfNecessaryLocked() {
1714 if (!mOwners.hasDeviceOwner()) {
1717 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1719 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1720 return; // Already a full component name.
1723 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1724 doComponentName.getPackageName(),
1725 mOwners.getDeviceOwnerUserId());
1726 if (doComponent == null) {
1727 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1729 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1731 mOwners.getDeviceOwnerName(),
1732 mOwners.getDeviceOwnerUserId(),
1733 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1734 mOwners.writeDeviceOwner();
1736 Log.v(LOG_TAG, "Device owner component filled in");
1742 * We didn't use to persist user restrictions for each owners but only persisted in user
1745 private void migrateUserRestrictionsIfNecessaryLocked() {
1746 boolean migrated = false;
1747 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1748 // except for the "system controlled" ones.
1749 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1751 Log.v(LOG_TAG, "Migrating DO user restrictions");
1755 // Migrate user 0 restrictions to DO.
1756 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1758 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1759 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1761 // Push DO user restrictions to user manager.
1762 pushUserRestrictions(UserHandle.USER_SYSTEM);
1764 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1769 // The following restrictions can be set on secondary users by the device owner, so we
1770 // assume they're not from the PO.
1771 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1772 UserManager.DISALLOW_OUTGOING_CALLS,
1773 UserManager.DISALLOW_SMS);
1775 for (UserInfo ui : mUserManager.getUsers()) {
1776 final int userId = ui.id;
1777 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1779 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1783 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1785 final Set<String> exceptionList =
1786 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1788 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1789 exceptionList, /* isDeviceOwner =*/ false);
1791 // Note if a secondary user has no PO but has a DA that disables camera, we
1792 // don't get here and won't push the camera user restriction to UserManager
1793 // here. That's okay because we'll push user restrictions anyway when a user
1794 // starts. But we still do it because we want to let user manager persist
1796 pushUserRestrictions(userId);
1798 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1801 if (VERBOSE_LOG && migrated) {
1802 Log.v(LOG_TAG, "User restrictions migrated.");
1806 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1807 Set<String> exceptionList, boolean isDeviceOwner) {
1808 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1809 user.getIdentifier());
1811 final Bundle newBaseRestrictions = new Bundle();
1812 final Bundle newOwnerRestrictions = new Bundle();
1814 for (String key : origRestrictions.keySet()) {
1815 if (!origRestrictions.getBoolean(key)) {
1818 final boolean canOwnerChange = isDeviceOwner
1819 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1820 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1822 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1823 newBaseRestrictions.putBoolean(key, true);
1825 newOwnerRestrictions.putBoolean(key, true);
1830 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1831 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1832 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1834 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1835 newBaseRestrictions);
1837 if (admin != null) {
1838 admin.ensureUserRestrictions().clear();
1839 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1841 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1843 saveSettingsLocked(user.getIdentifier());
1846 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1847 final DevicePolicyData policy = getUserData(userId);
1848 final int n = policy.mAdminList.size();
1849 ComponentName found = null;
1851 for (int i = 0; i < n; i++) {
1852 final ActiveAdmin admin = policy.mAdminList.get(i);
1853 if (packageName.equals(admin.info.getPackageName())) {
1856 found = admin.info.getComponent();
1862 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1868 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1869 * reminders. Clears alarm if no expirations are configured.
1871 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1872 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1873 final long now = System.currentTimeMillis();
1874 final long timeToExpire = expiration - now;
1875 final long alarmTime;
1876 if (expiration == 0) {
1877 // No expirations are currently configured: Cancel alarm.
1879 } else if (timeToExpire <= 0) {
1880 // The password has already expired: Repeat every 24 hours.
1881 alarmTime = now + MS_PER_DAY;
1883 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1884 // the expiration time.
1885 long alarmInterval = timeToExpire % MS_PER_DAY;
1886 if (alarmInterval == 0) {
1887 alarmInterval = MS_PER_DAY;
1889 alarmTime = now + alarmInterval;
1892 long token = mInjector.binderClearCallingIdentity();
1894 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1895 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1896 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1897 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1898 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1899 UserHandle.of(affectedUserHandle));
1901 if (alarmTime != 0) {
1902 am.set(AlarmManager.RTC, alarmTime, pi);
1905 mInjector.binderRestoreCallingIdentity(token);
1909 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1910 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1912 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1913 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1919 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
1921 enforceManagedProfile(userHandle, "call APIs on the parent profile");
1923 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1924 if (admin != null && parent) {
1925 admin = admin.getParentActiveAdmin();
1930 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1931 throws SecurityException {
1932 final int callingUid = mInjector.binderGetCallingUid();
1934 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1935 if (result != null) {
1940 final int userId = UserHandle.getUserId(callingUid);
1941 final DevicePolicyData policy = getUserData(userId);
1942 ActiveAdmin admin = policy.mAdminMap.get(who);
1943 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1944 throw new SecurityException("Admin " + admin.info.getComponent()
1945 + " does not own the device");
1947 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1948 throw new SecurityException("Admin " + admin.info.getComponent()
1949 + " does not own the profile");
1951 throw new SecurityException("Admin " + admin.info.getComponent()
1952 + " did not specify uses-policy for: "
1953 + admin.info.getTagForPolicy(reqPolicy));
1955 throw new SecurityException("No active admin owned by uid "
1956 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
1960 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
1961 throws SecurityException {
1963 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
1964 "call APIs on the parent profile");
1966 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
1967 return parent ? admin.getParentActiveAdmin() : admin;
1970 * Find the admin for the component and userId bit of the uid, then check
1971 * the admin's uid matches the uid.
1973 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
1974 final int userId = UserHandle.getUserId(uid);
1975 final DevicePolicyData policy = getUserData(userId);
1976 ActiveAdmin admin = policy.mAdminMap.get(who);
1977 if (admin == null) {
1978 throw new SecurityException("No active admin " + who);
1980 if (admin.getUid() != uid) {
1981 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1986 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
1988 // Try to find an admin which can use reqPolicy
1989 final int userId = UserHandle.getUserId(uid);
1990 final DevicePolicyData policy = getUserData(userId);
1992 ActiveAdmin admin = policy.mAdminMap.get(who);
1993 if (admin == null) {
1994 throw new SecurityException("No active admin " + who);
1996 if (admin.getUid() != uid) {
1997 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1999 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2003 for (ActiveAdmin admin : policy.mAdminList) {
2004 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2015 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2017 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2018 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2020 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2022 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2023 // DO always has the PO power.
2024 return ownsDevice || ownsProfile;
2026 return admin.info.usesPolicy(reqPolicy);
2030 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2031 sendAdminCommandLocked(admin, action, null);
2034 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2035 sendAdminCommandLocked(admin, action, null, result);
2039 * Send an update to one specific admin, get notified when that admin returns a result.
2041 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2042 BroadcastReceiver result) {
2043 Intent intent = new Intent(action);
2044 intent.setComponent(admin.info.getComponent());
2045 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2046 intent.putExtra("expiration", admin.passwordExpirationDate);
2048 if (adminExtras != null) {
2049 intent.putExtras(adminExtras);
2051 if (result != null) {
2052 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2053 null, result, mHandler, Activity.RESULT_OK, null, null);
2055 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2060 * Send an update to all admins of a user that enforce a specified policy.
2062 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2063 final DevicePolicyData policy = getUserData(userHandle);
2064 final int count = policy.mAdminList.size();
2066 for (int i = 0; i < count; i++) {
2067 final ActiveAdmin admin = policy.mAdminList.get(i);
2068 if (admin.info.usesPolicy(reqPolicy)) {
2069 sendAdminCommandLocked(admin, action);
2076 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2077 * enforce a specified policy.
2079 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2081 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2082 for (int profileId : profileIds) {
2083 sendAdminCommandLocked(action, reqPolicy, profileId);
2088 * Sends a broadcast to each profile that share the password unlock with the given user id.
2090 private void sendAdminCommandForLockscreenPoliciesLocked(
2091 String action, int reqPolicy, int userHandle) {
2092 if (isSeparateProfileChallengeEnabled(userHandle)) {
2093 sendAdminCommandLocked(action, reqPolicy, userHandle);
2095 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2099 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2100 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2101 DevicePolicyData policy = getUserData(userHandle);
2102 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2103 policy.mRemovingAdmins.add(adminReceiver);
2104 sendAdminCommandLocked(admin,
2105 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2106 new BroadcastReceiver() {
2108 public void onReceive(Context context, Intent intent) {
2109 removeAdminArtifacts(adminReceiver, userHandle);
2110 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2117 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2118 boolean throwForMissiongPermission) {
2122 enforceFullCrossUsersPermission(userHandle);
2123 ActivityInfo ai = null;
2125 ai = mIPackageManager.getReceiverInfo(adminName,
2126 PackageManager.GET_META_DATA |
2127 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2128 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2129 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2130 } catch (RemoteException e) {
2131 // shouldn't happen.
2134 throw new IllegalArgumentException("Unknown admin: " + adminName);
2137 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2138 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2139 + permission.BIND_DEVICE_ADMIN;
2140 Slog.w(LOG_TAG, message);
2141 if (throwForMissiongPermission &&
2142 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2143 throw new IllegalArgumentException(message);
2148 return new DeviceAdminInfo(mContext, ai);
2149 } catch (XmlPullParserException | IOException e) {
2150 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2156 private JournaledFile makeJournaledFile(int userHandle) {
2157 final String base = userHandle == UserHandle.USER_SYSTEM
2158 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2159 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2160 DEVICE_POLICIES_XML).getAbsolutePath();
2162 Log.v(LOG_TAG, "Opening " + base);
2164 return new JournaledFile(new File(base), new File(base + ".tmp"));
2167 private void saveSettingsLocked(int userHandle) {
2168 DevicePolicyData policy = getUserData(userHandle);
2169 JournaledFile journal = makeJournaledFile(userHandle);
2170 FileOutputStream stream = null;
2172 stream = new FileOutputStream(journal.chooseForWrite(), false);
2173 XmlSerializer out = new FastXmlSerializer();
2174 out.setOutput(stream, StandardCharsets.UTF_8.name());
2175 out.startDocument(null, true);
2177 out.startTag(null, "policies");
2178 if (policy.mRestrictionsProvider != null) {
2179 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2180 policy.mRestrictionsProvider.flattenToString());
2182 if (policy.mUserSetupComplete) {
2183 out.attribute(null, ATTR_SETUP_COMPLETE,
2184 Boolean.toString(true));
2186 if (policy.mDeviceProvisioningConfigApplied) {
2187 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2188 Boolean.toString(true));
2190 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2191 out.attribute(null, ATTR_PROVISIONING_STATE,
2192 Integer.toString(policy.mUserProvisioningState));
2194 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2195 out.attribute(null, ATTR_PERMISSION_POLICY,
2196 Integer.toString(policy.mPermissionPolicy));
2198 if (policy.mDelegatedCertInstallerPackage != null) {
2199 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2200 policy.mDelegatedCertInstallerPackage);
2202 if (policy.mApplicationRestrictionsManagingPackage != null) {
2203 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2204 policy.mApplicationRestrictionsManagingPackage);
2207 final int N = policy.mAdminList.size();
2208 for (int i=0; i<N; i++) {
2209 ActiveAdmin ap = policy.mAdminList.get(i);
2211 out.startTag(null, "admin");
2212 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2214 out.endTag(null, "admin");
2218 if (policy.mPasswordOwner >= 0) {
2219 out.startTag(null, "password-owner");
2220 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2221 out.endTag(null, "password-owner");
2224 if (policy.mFailedPasswordAttempts != 0) {
2225 out.startTag(null, "failed-password-attempts");
2226 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2227 out.endTag(null, "failed-password-attempts");
2230 // Don't save metrics for FBE devices
2231 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
2232 && (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2233 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2234 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2235 || policy.mActivePasswordSymbols != 0
2236 || policy.mActivePasswordNonLetter != 0)) {
2237 out.startTag(null, "active-password");
2238 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2239 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2240 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2241 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2242 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2243 out.attribute(null, "numeric", Integer
2244 .toString(policy.mActivePasswordNumeric));
2245 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2246 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2247 out.endTag(null, "active-password");
2250 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2251 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2252 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2253 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2256 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2257 String component = policy.mLockTaskPackages.get(i);
2258 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2259 out.attribute(null, "name", component);
2260 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2263 if (policy.mStatusBarDisabled) {
2264 out.startTag(null, TAG_STATUS_BAR);
2265 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2266 out.endTag(null, TAG_STATUS_BAR);
2269 if (policy.doNotAskCredentialsOnBoot) {
2270 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2271 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2274 for (String id : policy.mAffiliationIds) {
2275 out.startTag(null, TAG_AFFILIATION_ID);
2276 out.attribute(null, "id", id);
2277 out.endTag(null, TAG_AFFILIATION_ID);
2280 if (policy.mAdminBroadcastPending) {
2281 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2282 out.attribute(null, ATTR_VALUE,
2283 Boolean.toString(policy.mAdminBroadcastPending));
2284 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2287 if (policy.mInitBundle != null) {
2288 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2289 policy.mInitBundle.saveToXml(out);
2290 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2293 out.endTag(null, "policies");
2297 FileUtils.sync(stream);
2300 sendChangedNotification(userHandle);
2301 } catch (XmlPullParserException | IOException e) {
2302 Slog.w(LOG_TAG, "failed writing file", e);
2304 if (stream != null) {
2307 } catch (IOException ex) {
2314 private void sendChangedNotification(int userHandle) {
2315 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2316 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2317 long ident = mInjector.binderClearCallingIdentity();
2319 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2321 mInjector.binderRestoreCallingIdentity(ident);
2325 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2326 JournaledFile journal = makeJournaledFile(userHandle);
2327 FileInputStream stream = null;
2328 File file = journal.chooseForRead();
2329 boolean needsRewrite = false;
2331 stream = new FileInputStream(file);
2332 XmlPullParser parser = Xml.newPullParser();
2333 parser.setInput(stream, StandardCharsets.UTF_8.name());
2336 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2337 && type != XmlPullParser.START_TAG) {
2339 String tag = parser.getName();
2340 if (!"policies".equals(tag)) {
2341 throw new XmlPullParserException(
2342 "Settings do not start with policies tag: found " + tag);
2345 // Extract the permission provider component name if available
2346 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2347 if (permissionProvider != null) {
2348 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2350 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2351 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2352 policy.mUserSetupComplete = true;
2354 String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2355 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2356 if (deviceProvisioningConfigApplied != null
2357 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2358 policy.mDeviceProvisioningConfigApplied = true;
2360 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2361 if (!TextUtils.isEmpty(provisioningState)) {
2362 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2364 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2365 if (!TextUtils.isEmpty(permissionPolicy)) {
2366 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2368 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2369 ATTR_DELEGATED_CERT_INSTALLER);
2370 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2371 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2373 type = parser.next();
2374 int outerDepth = parser.getDepth();
2375 policy.mLockTaskPackages.clear();
2376 policy.mAdminList.clear();
2377 policy.mAdminMap.clear();
2378 policy.mAffiliationIds.clear();
2379 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2380 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2381 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2384 tag = parser.getName();
2385 if ("admin".equals(tag)) {
2386 String name = parser.getAttributeValue(null, "name");
2388 DeviceAdminInfo dai = findAdmin(
2389 ComponentName.unflattenFromString(name), userHandle,
2390 /* throwForMissionPermission= */ false);
2392 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2394 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2395 + dai.getActivityInfo().applicationInfo.uid + " for user "
2399 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2400 ap.readFromXml(parser);
2401 policy.mAdminMap.put(ap.info.getComponent(), ap);
2403 } catch (RuntimeException e) {
2404 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2406 } else if ("failed-password-attempts".equals(tag)) {
2407 policy.mFailedPasswordAttempts = Integer.parseInt(
2408 parser.getAttributeValue(null, "value"));
2409 } else if ("password-owner".equals(tag)) {
2410 policy.mPasswordOwner = Integer.parseInt(
2411 parser.getAttributeValue(null, "value"));
2412 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2413 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2414 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2415 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2416 } else if (TAG_STATUS_BAR.equals(tag)) {
2417 policy.mStatusBarDisabled = Boolean.parseBoolean(
2418 parser.getAttributeValue(null, ATTR_DISABLED));
2419 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2420 policy.doNotAskCredentialsOnBoot = true;
2421 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2422 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2423 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2424 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2425 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2426 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2427 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2428 } else if ("active-password".equals(tag)) {
2429 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2430 // Remove this from FBE devices
2431 needsRewrite = true;
2433 policy.mActivePasswordQuality = Integer.parseInt(
2434 parser.getAttributeValue(null, "quality"));
2435 policy.mActivePasswordLength = Integer.parseInt(
2436 parser.getAttributeValue(null, "length"));
2437 policy.mActivePasswordUpperCase = Integer.parseInt(
2438 parser.getAttributeValue(null, "uppercase"));
2439 policy.mActivePasswordLowerCase = Integer.parseInt(
2440 parser.getAttributeValue(null, "lowercase"));
2441 policy.mActivePasswordLetters = Integer.parseInt(
2442 parser.getAttributeValue(null, "letters"));
2443 policy.mActivePasswordNumeric = Integer.parseInt(
2444 parser.getAttributeValue(null, "numeric"));
2445 policy.mActivePasswordSymbols = Integer.parseInt(
2446 parser.getAttributeValue(null, "symbols"));
2447 policy.mActivePasswordNonLetter = Integer.parseInt(
2448 parser.getAttributeValue(null, "nonletter"));
2451 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2452 XmlUtils.skipCurrentTag(parser);
2455 } catch (FileNotFoundException e) {
2456 // Don't be noisy, this is normal if we haven't defined any policies.
2457 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2458 | IndexOutOfBoundsException e) {
2459 Slog.w(LOG_TAG, "failed parsing " + file, e);
2462 if (stream != null) {
2465 } catch (IOException e) {
2469 // Generate a list of admins from the admin map
2470 policy.mAdminList.addAll(policy.mAdminMap.values());
2472 // Might need to upgrade the file by rewriting it
2474 saveSettingsLocked(userHandle);
2477 validatePasswordOwnerLocked(policy);
2478 updateMaximumTimeToLockLocked(userHandle);
2479 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2480 if (policy.mStatusBarDisabled) {
2481 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2485 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2486 long ident = mInjector.binderClearCallingIdentity();
2488 mInjector.getIActivityManager()
2489 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2490 } catch (RemoteException e) {
2491 // Not gonna happen.
2493 mInjector.binderRestoreCallingIdentity(ident);
2497 private void updateDeviceOwnerLocked() {
2498 long ident = mInjector.binderClearCallingIdentity();
2500 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2501 // user id and also protect all other DAs too.
2502 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2503 if (deviceOwnerComponent != null) {
2504 mInjector.getIActivityManager()
2505 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2507 } catch (RemoteException e) {
2508 // Not gonna happen.
2510 mInjector.binderRestoreCallingIdentity(ident);
2514 static void validateQualityConstant(int quality) {
2516 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2517 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2518 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2519 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2520 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2521 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2522 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2523 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2524 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2527 throw new IllegalArgumentException("Invalid quality constant: 0x"
2528 + Integer.toHexString(quality));
2531 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2532 if (policy.mPasswordOwner >= 0) {
2533 boolean haveOwner = false;
2534 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2535 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2541 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2542 + " no longer active; disabling");
2543 policy.mPasswordOwner = -1;
2549 void systemReady(int phase) {
2554 case SystemService.PHASE_LOCK_SETTINGS_READY:
2555 onLockSettingsReady();
2557 case SystemService.PHASE_BOOT_COMPLETED:
2558 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2563 private void onLockSettingsReady() {
2564 getUserData(UserHandle.USER_SYSTEM);
2568 onStartUser(UserHandle.USER_SYSTEM);
2570 // Register an observer for watching for user setup complete.
2571 new SetupContentObserver(mHandler).register();
2572 // Initialize the user setup state, to handle the upgrade case.
2573 updateUserSetupComplete();
2575 List<String> packageList;
2576 synchronized (this) {
2577 packageList = getKeepUninstalledPackagesLocked();
2579 if (packageList != null) {
2580 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2583 synchronized (this) {
2584 // push the force-ephemeral-users policy to the user manager.
2585 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2586 if (deviceOwner != null) {
2587 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2592 private void ensureDeviceOwnerUserStarted() {
2594 synchronized (this) {
2595 if (!mOwners.hasDeviceOwner()) {
2598 userId = mOwners.getDeviceOwnerUserId();
2601 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2603 if (userId != UserHandle.USER_SYSTEM) {
2605 mInjector.getIActivityManager().startUserInBackground(userId);
2607 // STOPSHIP Prevent the DO user from being killed.
2609 } catch (RemoteException e) {
2610 Slog.w(LOG_TAG, "Exception starting user", e);
2615 private void onStartUser(int userId) {
2616 updateScreenCaptureDisabledInWindowManager(userId,
2617 getScreenCaptureDisabled(null, userId));
2618 pushUserRestrictions(userId);
2621 private void cleanUpOldUsers() {
2622 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2624 Set<Integer> usersWithProfileOwners;
2625 Set<Integer> usersWithData;
2626 synchronized(this) {
2627 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2628 usersWithData = new ArraySet<>();
2629 for (int i = 0; i < mUserData.size(); i++) {
2630 usersWithData.add(mUserData.keyAt(i));
2633 List<UserInfo> allUsers = mUserManager.getUsers();
2635 Set<Integer> deletedUsers = new ArraySet<>();
2636 deletedUsers.addAll(usersWithProfileOwners);
2637 deletedUsers.addAll(usersWithData);
2638 for (UserInfo userInfo : allUsers) {
2639 deletedUsers.remove(userInfo.id);
2641 for (Integer userId : deletedUsers) {
2642 removeUserData(userId);
2646 private void handlePasswordExpirationNotification(int userHandle) {
2647 synchronized (this) {
2648 final long now = System.currentTimeMillis();
2650 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2651 userHandle, /* parent */ false);
2652 final int N = admins.size();
2653 for (int i = 0; i < N; i++) {
2654 ActiveAdmin admin = admins.get(i);
2655 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2656 && admin.passwordExpirationTimeout > 0L
2657 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2658 && admin.passwordExpirationDate > 0L) {
2659 sendAdminCommandLocked(admin,
2660 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2663 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2667 private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2669 protected Void doInBackground(Integer... params) {
2670 int userHandle = params[0];
2672 if (userHandle == UserHandle.USER_ALL) {
2673 for (UserInfo userInfo : mUserManager.getUsers(true)) {
2674 manageNotification(userInfo.getUserHandle());
2677 manageNotification(UserHandle.of(userHandle));
2682 private void manageNotification(UserHandle userHandle) {
2683 if (!mUserManager.isUserUnlocked(userHandle)) {
2687 // Call out to KeyChain to check for CAs which are waiting for approval.
2688 final List<String> pendingCertificates;
2690 pendingCertificates = getInstalledCaCertificates(userHandle);
2691 } catch (RemoteException | RuntimeException e) {
2692 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2696 synchronized (DevicePolicyManagerService.this) {
2697 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2699 // Remove deleted certificates. Flush xml if necessary.
2700 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2701 saveSettingsLocked(userHandle.getIdentifier());
2703 // Trim to approved certificates.
2704 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2707 if (pendingCertificates.isEmpty()) {
2708 mInjector.getNotificationManager().cancelAsUser(
2709 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2713 // Build and show a warning notification
2716 int parentUserId = userHandle.getIdentifier();
2717 if (getProfileOwner(userHandle.getIdentifier()) != null) {
2718 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2719 getProfileOwnerName(userHandle.getIdentifier()));
2720 smallIconId = R.drawable.stat_sys_certificate_info;
2721 parentUserId = getProfileParentId(userHandle.getIdentifier());
2722 } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
2723 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2724 getDeviceOwnerName());
2725 smallIconId = R.drawable.stat_sys_certificate_info;
2727 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2728 smallIconId = android.R.drawable.stat_sys_warning;
2731 final int numberOfCertificates = pendingCertificates.size();
2732 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2733 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2734 dialogIntent.setPackage("com.android.settings");
2735 dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
2736 dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
2737 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2738 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
2739 new UserHandle(parentUserId));
2741 final Context userContext;
2743 final String packageName = mContext.getPackageName();
2744 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
2745 } catch (PackageManager.NameNotFoundException e) {
2746 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2749 final Notification noti = new Notification.Builder(userContext)
2750 .setSmallIcon(smallIconId)
2751 .setContentTitle(mContext.getResources().getQuantityText(
2752 R.plurals.ssl_ca_cert_warning, numberOfCertificates))
2753 .setContentText(contentText)
2754 .setContentIntent(notifyIntent)
2755 .setPriority(Notification.PRIORITY_HIGH)
2757 .setColor(mContext.getColor(
2758 com.android.internal.R.color.system_notification_accent_color))
2761 mInjector.getNotificationManager().notifyAsUser(
2762 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2765 private List<String> getInstalledCaCertificates(UserHandle userHandle)
2766 throws RemoteException, RuntimeException {
2767 KeyChainConnection conn = null;
2769 conn = KeyChain.bindAsUser(mContext, userHandle);
2770 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
2771 List<String> result = new ArrayList<>(aliases.size());
2772 for (int i = 0; i < aliases.size(); i++) {
2773 result.add(aliases.get(i).string);
2776 } catch (InterruptedException e) {
2777 Thread.currentThread().interrupt();
2779 } catch (AssertionError e) {
2780 throw new RuntimeException(e);
2790 * @param adminReceiver The admin to add
2791 * @param refreshing true = update an active admin, no error
2794 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2798 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2801 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2802 Bundle onEnableData) {
2803 mContext.enforceCallingOrSelfPermission(
2804 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2805 enforceFullCrossUsersPermission(userHandle);
2807 DevicePolicyData policy = getUserData(userHandle);
2808 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2809 /* throwForMissionPermission= */ true);
2811 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2813 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2814 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2817 synchronized (this) {
2818 long ident = mInjector.binderClearCallingIdentity();
2821 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
2822 throw new IllegalArgumentException("Admin is already added");
2824 if (policy.mRemovingAdmins.contains(adminReceiver)) {
2825 throw new IllegalArgumentException(
2826 "Trying to set an admin which is being removed");
2828 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2829 policy.mAdminMap.put(adminReceiver, newAdmin);
2830 int replaceIndex = -1;
2831 final int N = policy.mAdminList.size();
2832 for (int i=0; i < N; i++) {
2833 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2834 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2839 if (replaceIndex == -1) {
2840 policy.mAdminList.add(newAdmin);
2841 enableIfNecessary(info.getPackageName(), userHandle);
2843 policy.mAdminList.set(replaceIndex, newAdmin);
2845 saveSettingsLocked(userHandle);
2846 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2847 onEnableData, null);
2849 mInjector.binderRestoreCallingIdentity(ident);
2855 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2859 enforceFullCrossUsersPermission(userHandle);
2860 synchronized (this) {
2861 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2866 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2870 enforceFullCrossUsersPermission(userHandle);
2871 synchronized (this) {
2872 DevicePolicyData policyData = getUserData(userHandle);
2873 return policyData.mRemovingAdmins.contains(adminReceiver);
2878 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2882 enforceFullCrossUsersPermission(userHandle);
2883 synchronized (this) {
2884 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2885 if (administrator == null) {
2886 throw new SecurityException("No active admin " + adminReceiver);
2888 return administrator.info.usesPolicy(policyId);
2893 @SuppressWarnings("unchecked")
2894 public List<ComponentName> getActiveAdmins(int userHandle) {
2896 return Collections.EMPTY_LIST;
2899 enforceFullCrossUsersPermission(userHandle);
2900 synchronized (this) {
2901 DevicePolicyData policy = getUserData(userHandle);
2902 final int N = policy.mAdminList.size();
2906 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2907 for (int i=0; i<N; i++) {
2908 res.add(policy.mAdminList.get(i).info.getComponent());
2915 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2919 enforceFullCrossUsersPermission(userHandle);
2920 synchronized (this) {
2921 DevicePolicyData policy = getUserData(userHandle);
2922 final int N = policy.mAdminList.size();
2923 for (int i=0; i<N; i++) {
2924 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2932 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
2936 Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
2937 enforceShell("forceRemoveActiveAdmin");
2938 long ident = mInjector.binderClearCallingIdentity();
2940 final ApplicationInfo ai;
2942 ai = mIPackageManager.getApplicationInfo(adminReceiver.getPackageName(),
2944 } catch (RemoteException e) {
2945 throw new IllegalStateException(e);
2948 throw new IllegalStateException("Couldn't find package to remove admin "
2949 + adminReceiver.getPackageName() + " " + userHandle);
2951 if ((ai.flags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
2952 throw new SecurityException("Attempt to remove non-test admin " + adminReceiver
2953 + adminReceiver + " " + userHandle);
2955 // If admin is a device or profile owner tidy that up first.
2956 synchronized (this) {
2957 if (isDeviceOwner(adminReceiver, userHandle)) {
2958 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
2960 if (isProfileOwner(adminReceiver, userHandle)) {
2961 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
2962 userHandle, /* parent */ false);
2963 clearProfileOwnerLocked(admin, userHandle);
2966 // Remove the admin skipping sending the broadcast.
2967 removeAdminArtifacts(adminReceiver, userHandle);
2969 mInjector.binderRestoreCallingIdentity(ident);
2973 private void enforceShell(String method) {
2974 final int callingUid = Binder.getCallingUid();
2975 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
2976 throw new SecurityException("Non-shell user attempted to call " + method);
2981 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
2985 enforceFullCrossUsersPermission(userHandle);
2986 enforceUserUnlocked(userHandle);
2987 synchronized (this) {
2988 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2989 if (admin == null) {
2992 // Active device/profile owners must remain active admins.
2993 if (isDeviceOwner(adminReceiver, userHandle)
2994 || isProfileOwner(adminReceiver, userHandle)) {
2995 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
2999 if (admin.getUid() != mInjector.binderGetCallingUid()) {
3000 mContext.enforceCallingOrSelfPermission(
3001 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3003 long ident = mInjector.binderClearCallingIdentity();
3005 removeActiveAdminLocked(adminReceiver, userHandle);
3007 mInjector.binderRestoreCallingIdentity(ident);
3013 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3014 ComponentName profileOwner = getProfileOwner(userHandle);
3015 // Profile challenge is supported on N or newer release.
3016 return profileOwner != null &&
3017 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3021 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3025 Preconditions.checkNotNull(who, "ComponentName is null");
3026 validateQualityConstant(quality);
3028 synchronized (this) {
3029 ActiveAdmin ap = getActiveAdminForCallerLocked(
3030 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3031 if (ap.passwordQuality != quality) {
3032 ap.passwordQuality = quality;
3033 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3039 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3041 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3043 enforceFullCrossUsersPermission(userHandle);
3044 synchronized (this) {
3045 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3048 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3049 return admin != null ? admin.passwordQuality : mode;
3052 // Return the strictest policy across all participating admins.
3053 List<ActiveAdmin> admins =
3054 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3055 final int N = admins.size();
3056 for (int i = 0; i < N; i++) {
3057 ActiveAdmin admin = admins.get(i);
3058 if (mode < admin.passwordQuality) {
3059 mode = admin.passwordQuality;
3066 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3067 int userHandle, boolean parent) {
3068 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3069 // If this user has a separate challenge, only return its restrictions.
3070 return getUserDataUnchecked(userHandle).mAdminList;
3072 // Return all admins for this user and the profiles that are visible from this
3073 // user that do not use a separate work challenge.
3074 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3075 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3076 DevicePolicyData policy = getUserData(userInfo.id);
3077 if (!userInfo.isManagedProfile()) {
3078 admins.addAll(policy.mAdminList);
3080 // For managed profiles, we always include the policies set on the parent
3081 // profile. Additionally, we include the ones set on the managed profile
3082 // if no separate challenge is in place.
3083 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3084 final int N = policy.mAdminList.size();
3085 for (int i = 0; i < N; i++) {
3086 ActiveAdmin admin = policy.mAdminList.get(i);
3087 if (admin.hasParentActiveAdmin()) {
3088 admins.add(admin.getParentActiveAdmin());
3090 if (!hasSeparateChallenge) {
3100 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3101 long ident = mInjector.binderClearCallingIdentity();
3103 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3105 mInjector.binderRestoreCallingIdentity(ident);
3110 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3114 Preconditions.checkNotNull(who, "ComponentName is null");
3115 synchronized (this) {
3116 ActiveAdmin ap = getActiveAdminForCallerLocked(
3117 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3118 if (ap.minimumPasswordLength != length) {
3119 ap.minimumPasswordLength = length;
3120 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3126 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3130 enforceFullCrossUsersPermission(userHandle);
3131 synchronized (this) {
3135 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3136 return admin != null ? admin.minimumPasswordLength : length;
3139 // Return the strictest policy across all participating admins.
3140 List<ActiveAdmin> admins =
3141 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3142 final int N = admins.size();
3143 for (int i = 0; i < N; i++) {
3144 ActiveAdmin admin = admins.get(i);
3145 if (length < admin.minimumPasswordLength) {
3146 length = admin.minimumPasswordLength;
3154 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3158 Preconditions.checkNotNull(who, "ComponentName is null");
3159 synchronized (this) {
3160 ActiveAdmin ap = getActiveAdminForCallerLocked(
3161 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3162 if (ap.passwordHistoryLength != length) {
3163 ap.passwordHistoryLength = length;
3164 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3170 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3174 enforceFullCrossUsersPermission(userHandle);
3175 synchronized (this) {
3179 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3180 return admin != null ? admin.passwordHistoryLength : length;
3183 // Return the strictest policy across all participating admins.
3184 List<ActiveAdmin> admins =
3185 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3186 final int N = admins.size();
3187 for (int i = 0; i < N; i++) {
3188 ActiveAdmin admin = admins.get(i);
3189 if (length < admin.passwordHistoryLength) {
3190 length = admin.passwordHistoryLength;
3199 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3203 Preconditions.checkNotNull(who, "ComponentName is null");
3204 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3205 final int userHandle = mInjector.userHandleGetCallingUserId();
3206 synchronized (this) {
3207 ActiveAdmin ap = getActiveAdminForCallerLocked(
3208 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3209 // Calling this API automatically bumps the expiration date
3210 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3211 ap.passwordExpirationDate = expiration;
3212 ap.passwordExpirationTimeout = timeout;
3214 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3215 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3216 .format(new Date(expiration)));
3218 saveSettingsLocked(userHandle);
3220 // in case this is the first one, set the alarm on the appropriate user.
3221 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3226 * Return a single admin's expiration cycle time, or the min of all cycle times.
3227 * Returns 0 if not configured.
3230 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3234 enforceFullCrossUsersPermission(userHandle);
3235 synchronized (this) {
3239 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3240 return admin != null ? admin.passwordExpirationTimeout : timeout;
3243 // Return the strictest policy across all participating admins.
3244 List<ActiveAdmin> admins =
3245 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3246 final int N = admins.size();
3247 for (int i = 0; i < N; i++) {
3248 ActiveAdmin admin = admins.get(i);
3249 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3250 && timeout > admin.passwordExpirationTimeout)) {
3251 timeout = admin.passwordExpirationTimeout;
3259 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3260 final int userId = UserHandle.getCallingUserId();
3261 List<String> changedProviders = null;
3263 synchronized (this) {
3264 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3265 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3266 if (activeAdmin.crossProfileWidgetProviders == null) {
3267 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3269 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3270 if (!providers.contains(packageName)) {
3271 providers.add(packageName);
3272 changedProviders = new ArrayList<>(providers);
3273 saveSettingsLocked(userId);
3277 if (changedProviders != null) {
3278 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3286 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3287 final int userId = UserHandle.getCallingUserId();
3288 List<String> changedProviders = null;
3290 synchronized (this) {
3291 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3292 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3293 if (activeAdmin.crossProfileWidgetProviders == null) {
3296 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3297 if (providers.remove(packageName)) {
3298 changedProviders = new ArrayList<>(providers);
3299 saveSettingsLocked(userId);
3303 if (changedProviders != null) {
3304 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3312 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3313 synchronized (this) {
3314 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3315 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3316 if (activeAdmin.crossProfileWidgetProviders == null
3317 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3320 if (mInjector.binderIsCallingUidMyUid()) {
3321 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3323 return activeAdmin.crossProfileWidgetProviders;
3329 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3330 * Returns 0 if not configured.
3332 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3336 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3337 return admin != null ? admin.passwordExpirationDate : timeout;
3340 // Return the strictest policy across all participating admins.
3341 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3342 final int N = admins.size();
3343 for (int i = 0; i < N; i++) {
3344 ActiveAdmin admin = admins.get(i);
3345 if (timeout == 0L || (admin.passwordExpirationDate != 0
3346 && timeout > admin.passwordExpirationDate)) {
3347 timeout = admin.passwordExpirationDate;
3354 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3358 enforceFullCrossUsersPermission(userHandle);
3359 synchronized (this) {
3360 return getPasswordExpirationLocked(who, userHandle, parent);
3365 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3369 Preconditions.checkNotNull(who, "ComponentName is null");
3370 synchronized (this) {
3371 ActiveAdmin ap = getActiveAdminForCallerLocked(
3372 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3373 if (ap.minimumPasswordUpperCase != length) {
3374 ap.minimumPasswordUpperCase = length;
3375 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3381 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3385 enforceFullCrossUsersPermission(userHandle);
3386 synchronized (this) {
3390 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3391 return admin != null ? admin.minimumPasswordUpperCase : length;
3394 // Return the strictest policy across all participating admins.
3395 List<ActiveAdmin> admins =
3396 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3397 final int N = admins.size();
3398 for (int i = 0; i < N; i++) {
3399 ActiveAdmin admin = admins.get(i);
3400 if (length < admin.minimumPasswordUpperCase) {
3401 length = admin.minimumPasswordUpperCase;
3409 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3410 Preconditions.checkNotNull(who, "ComponentName is null");
3411 synchronized (this) {
3412 ActiveAdmin ap = getActiveAdminForCallerLocked(
3413 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3414 if (ap.minimumPasswordLowerCase != length) {
3415 ap.minimumPasswordLowerCase = length;
3416 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3422 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3426 enforceFullCrossUsersPermission(userHandle);
3427 synchronized (this) {
3431 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3432 return admin != null ? admin.minimumPasswordLowerCase : length;
3435 // Return the strictest policy across all participating admins.
3436 List<ActiveAdmin> admins =
3437 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3438 final int N = admins.size();
3439 for (int i = 0; i < N; i++) {
3440 ActiveAdmin admin = admins.get(i);
3441 if (length < admin.minimumPasswordLowerCase) {
3442 length = admin.minimumPasswordLowerCase;
3450 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3454 Preconditions.checkNotNull(who, "ComponentName is null");
3455 synchronized (this) {
3456 ActiveAdmin ap = getActiveAdminForCallerLocked(
3457 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3458 if (ap.minimumPasswordLetters != length) {
3459 ap.minimumPasswordLetters = length;
3460 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3466 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3470 enforceFullCrossUsersPermission(userHandle);
3471 synchronized (this) {
3475 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3476 return admin != null ? admin.minimumPasswordLetters : length;
3479 // Return the strictest policy across all participating admins.
3480 List<ActiveAdmin> admins =
3481 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3482 final int N = admins.size();
3483 for (int i = 0; i < N; i++) {
3484 ActiveAdmin admin = admins.get(i);
3485 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3488 if (length < admin.minimumPasswordLetters) {
3489 length = admin.minimumPasswordLetters;
3497 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3501 Preconditions.checkNotNull(who, "ComponentName is null");
3502 synchronized (this) {
3503 ActiveAdmin ap = getActiveAdminForCallerLocked(
3504 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3505 if (ap.minimumPasswordNumeric != length) {
3506 ap.minimumPasswordNumeric = length;
3507 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3513 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3517 enforceFullCrossUsersPermission(userHandle);
3518 synchronized (this) {
3522 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3523 return admin != null ? admin.minimumPasswordNumeric : length;
3526 // Return the strictest policy across all participating admins.
3527 List<ActiveAdmin> admins =
3528 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3529 final int N = admins.size();
3530 for (int i = 0; i < N; i++) {
3531 ActiveAdmin admin = admins.get(i);
3532 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3535 if (length < admin.minimumPasswordNumeric) {
3536 length = admin.minimumPasswordNumeric;
3544 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3548 Preconditions.checkNotNull(who, "ComponentName is null");
3549 synchronized (this) {
3550 ActiveAdmin ap = getActiveAdminForCallerLocked(
3551 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3552 if (ap.minimumPasswordSymbols != length) {
3553 ap.minimumPasswordSymbols = length;
3554 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3560 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3564 enforceFullCrossUsersPermission(userHandle);
3565 synchronized (this) {
3569 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3570 return admin != null ? admin.minimumPasswordSymbols : length;
3573 // Return the strictest policy across all participating admins.
3574 List<ActiveAdmin> admins =
3575 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3576 final int N = admins.size();
3577 for (int i = 0; i < N; i++) {
3578 ActiveAdmin admin = admins.get(i);
3579 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3582 if (length < admin.minimumPasswordSymbols) {
3583 length = admin.minimumPasswordSymbols;
3591 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3595 Preconditions.checkNotNull(who, "ComponentName is null");
3596 synchronized (this) {
3597 ActiveAdmin ap = getActiveAdminForCallerLocked(
3598 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3599 if (ap.minimumPasswordNonLetter != length) {
3600 ap.minimumPasswordNonLetter = length;
3601 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3607 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3611 enforceFullCrossUsersPermission(userHandle);
3612 synchronized (this) {
3616 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3617 return admin != null ? admin.minimumPasswordNonLetter : length;
3620 // Return the strictest policy across all participating admins.
3621 List<ActiveAdmin> admins =
3622 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3623 final int N = admins.size();
3624 for (int i = 0; i < N; i++) {
3625 ActiveAdmin admin = admins.get(i);
3626 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3629 if (length < admin.minimumPasswordNonLetter) {
3630 length = admin.minimumPasswordNonLetter;
3638 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3642 enforceFullCrossUsersPermission(userHandle);
3644 synchronized (this) {
3645 // This API can only be called by an active device admin,
3646 // so try to retrieve it to check that the caller is one.
3647 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3648 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3649 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3654 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3658 enforceFullCrossUsersPermission(userHandle);
3659 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3661 synchronized (this) {
3662 int targetUser = getProfileParentId(userHandle);
3663 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3664 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3668 private boolean isActivePasswordSufficientForUserLocked(
3669 DevicePolicyData policy, int userHandle, boolean parent) {
3670 enforceUserUnlocked(userHandle, parent);
3672 if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle, parent)
3673 || policy.mActivePasswordLength < getPasswordMinimumLength(
3674 null, userHandle, parent)) {
3677 if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3680 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3681 null, userHandle, parent)
3682 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3683 null, userHandle, parent)
3684 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3685 null, userHandle, parent)
3686 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3687 null, userHandle, parent)
3688 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3689 null, userHandle, parent)
3690 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3691 null, userHandle, parent);
3695 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3696 enforceFullCrossUsersPermission(userHandle);
3697 synchronized (this) {
3698 if (!isCallerWithSystemUid()) {
3699 // This API can only be called by an active device admin,
3700 // so try to retrieve it to check that the caller is one.
3701 getActiveAdminForCallerLocked(
3702 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3705 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3707 return policy.mFailedPasswordAttempts;
3712 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3716 Preconditions.checkNotNull(who, "ComponentName is null");
3717 synchronized (this) {
3718 // This API can only be called by an active device admin,
3719 // so try to retrieve it to check that the caller is one.
3720 getActiveAdminForCallerLocked(
3721 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3722 ActiveAdmin ap = getActiveAdminForCallerLocked(
3723 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3724 if (ap.maximumFailedPasswordsForWipe != num) {
3725 ap.maximumFailedPasswordsForWipe = num;
3726 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3732 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3736 enforceFullCrossUsersPermission(userHandle);
3737 synchronized (this) {
3738 ActiveAdmin admin = (who != null)
3739 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3740 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3741 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3746 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3748 return UserHandle.USER_NULL;
3750 enforceFullCrossUsersPermission(userHandle);
3751 synchronized (this) {
3752 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3753 userHandle, parent);
3754 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3759 * Returns the admin with the strictest policy on maximum failed passwords for:
3761 * <li>this user if it has a separate profile challenge, or
3762 * <li>this user and all profiles that don't have their own challenge otherwise.
3764 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3765 * the primary profile.
3766 * Returns {@code null} if no participating admin has that policy set.
3768 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3769 int userHandle, boolean parent) {
3771 ActiveAdmin strictestAdmin = null;
3773 // Return the strictest policy across all participating admins.
3774 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3775 final int N = admins.size();
3776 for (int i = 0; i < N; i++) {
3777 ActiveAdmin admin = admins.get(i);
3778 if (admin.maximumFailedPasswordsForWipe ==
3779 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3780 continue; // No max number of failed passwords policy set for this profile.
3783 // We always favor the primary profile if several profiles have the same value set.
3784 int userId = admin.getUserHandle().getIdentifier();
3786 count > admin.maximumFailedPasswordsForWipe ||
3787 (count == admin.maximumFailedPasswordsForWipe &&
3788 getUserInfo(userId).isPrimary())) {
3789 count = admin.maximumFailedPasswordsForWipe;
3790 strictestAdmin = admin;
3793 return strictestAdmin;
3796 private UserInfo getUserInfo(@UserIdInt int userId) {
3797 final long token = mInjector.binderClearCallingIdentity();
3799 return mUserManager.getUserInfo(userId);
3801 mInjector.binderRestoreCallingIdentity(token);
3806 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3810 final int callingUid = mInjector.binderGetCallingUid();
3811 final int userHandle = mInjector.userHandleGetCallingUserId();
3813 String password = passwordOrNull != null ? passwordOrNull : "";
3815 // Password resetting to empty/null is not allowed for managed profiles.
3816 if (TextUtils.isEmpty(password)) {
3817 enforceNotManagedProfile(userHandle, "clear the active password");
3821 synchronized (this) {
3822 // If caller has PO (or DO) it can change the password, so see if that's the case first.
3823 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3824 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3826 if (admin != null) {
3827 preN = getTargetSdk(admin.info.getPackageName(),
3828 userHandle) <= android.os.Build.VERSION_CODES.M;
3830 // Otherwise, make sure the caller has any active admin with the right policy.
3831 admin = getActiveAdminForCallerLocked(null,
3832 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3833 preN = getTargetSdk(admin.info.getPackageName(),
3834 userHandle) <= android.os.Build.VERSION_CODES.M;
3836 // As of N, password resetting to empty/null is not allowed anymore.
3837 // TODO Should we allow DO/PO to set an empty password?
3838 if (TextUtils.isEmpty(password)) {
3840 throw new SecurityException("Cannot call with null password");
3842 Slog.e(LOG_TAG, "Cannot call with null password");
3846 // As of N, password cannot be changed by the admin if it is already set.
3847 if (isLockScreenSecureUnchecked(userHandle)) {
3849 throw new SecurityException("Admin cannot change current password");
3851 Slog.e(LOG_TAG, "Admin cannot change current password");
3856 // Do not allow to reset password when current user has a managed profile
3857 if (!isManagedProfile(userHandle)) {
3858 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3859 if (userInfo.isManagedProfile()) {
3861 throw new IllegalStateException(
3862 "Cannot reset password on user has managed profile");
3864 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
3870 // Do not allow to reset password when user is locked
3871 if (!mUserManager.isUserUnlocked(userHandle)) {
3873 throw new IllegalStateException("Cannot reset password when user is locked");
3875 Slog.e(LOG_TAG, "Cannot reset password when user is locked");
3880 quality = getPasswordQuality(null, userHandle, /* parent */ false);
3881 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
3882 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3884 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
3885 int realQuality = LockPatternUtils.computePasswordQuality(password);
3886 if (realQuality < quality
3887 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3888 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
3889 + Integer.toHexString(realQuality)
3890 + " does not meet required quality 0x"
3891 + Integer.toHexString(quality));
3894 quality = Math.max(realQuality, quality);
3896 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
3897 if (password.length() < length) {
3898 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
3899 + " does not meet required length " + length);
3902 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3909 for (int i = 0; i < password.length(); i++) {
3910 char c = password.charAt(i);
3911 if (c >= 'A' && c <= 'Z') {
3914 } else if (c >= 'a' && c <= 'z') {
3917 } else if (c >= '0' && c <= '9') {
3925 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
3926 if(letters < neededLetters) {
3927 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
3928 + " does not meet required number of letters " + neededLetters);
3931 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
3932 if (numbers < neededNumbers) {
3933 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
3934 + " does not meet required number of numerical digits "
3938 int neededLowerCase = getPasswordMinimumLowerCase(
3939 null, userHandle, /* parent */ false);
3940 if (lowercase < neededLowerCase) {
3941 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
3942 + " does not meet required number of lowercase letters "
3946 int neededUpperCase = getPasswordMinimumUpperCase(
3947 null, userHandle, /* parent */ false);
3948 if (uppercase < neededUpperCase) {
3949 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
3950 + " does not meet required number of uppercase letters "
3954 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
3955 if (symbols < neededSymbols) {
3956 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
3957 + " does not meet required number of special symbols " + neededSymbols);
3960 int neededNonLetter = getPasswordMinimumNonLetter(
3961 null, userHandle, /* parent */ false);
3962 if (nonletter < neededNonLetter) {
3963 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
3964 + " does not meet required number of non-letter characters "
3971 DevicePolicyData policy = getUserData(userHandle);
3972 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
3973 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
3977 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
3978 boolean doNotAskCredentialsOnBoot =
3979 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
3980 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
3981 setDoNotAskCredentialsOnBoot();
3984 // Don't do this with the lock held, because it is going to call
3985 // back in to the service.
3986 final long ident = mInjector.binderClearCallingIdentity();
3988 if (!TextUtils.isEmpty(password)) {
3989 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
3991 mLockPatternUtils.clearLock(userHandle);
3993 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
3995 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
3996 UserHandle.USER_ALL);
3998 synchronized (this) {
3999 int newOwner = requireEntry ? callingUid : -1;
4000 if (policy.mPasswordOwner != newOwner) {
4001 policy.mPasswordOwner = newOwner;
4002 saveSettingsLocked(userHandle);
4006 mInjector.binderRestoreCallingIdentity(ident);
4012 private boolean isLockScreenSecureUnchecked(int userId) {
4013 long ident = mInjector.binderClearCallingIdentity();
4015 return mLockPatternUtils.isSecure(userId);
4017 mInjector.binderRestoreCallingIdentity(ident);
4021 private void setDoNotAskCredentialsOnBoot() {
4022 synchronized (this) {
4023 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4024 if (!policyData.doNotAskCredentialsOnBoot) {
4025 policyData.doNotAskCredentialsOnBoot = true;
4026 saveSettingsLocked(UserHandle.USER_SYSTEM);
4032 public boolean getDoNotAskCredentialsOnBoot() {
4033 mContext.enforceCallingOrSelfPermission(
4034 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4035 synchronized (this) {
4036 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4037 return policyData.doNotAskCredentialsOnBoot;
4042 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4046 Preconditions.checkNotNull(who, "ComponentName is null");
4047 final int userHandle = mInjector.userHandleGetCallingUserId();
4048 synchronized (this) {
4049 ActiveAdmin ap = getActiveAdminForCallerLocked(
4050 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4051 if (ap.maximumTimeToUnlock != timeMs) {
4052 ap.maximumTimeToUnlock = timeMs;
4053 saveSettingsLocked(userHandle);
4054 updateMaximumTimeToLockLocked(userHandle);
4059 void updateMaximumTimeToLockLocked(int userHandle) {
4060 // Calculate the min timeout for all profiles - including the ones with a separate
4061 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4062 // challenge only and keep the screen on. However there is no easy way of doing that at the
4063 // moment so we set the screen off timeout regardless of whether it affects the parent user
4064 // or the profile challenge only.
4065 long timeMs = Long.MAX_VALUE;
4066 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4067 for (int profileId : profileIds) {
4068 DevicePolicyData policy = getUserDataUnchecked(profileId);
4069 final int N = policy.mAdminList.size();
4070 for (int i = 0; i < N; i++) {
4071 ActiveAdmin admin = policy.mAdminList.get(i);
4072 if (admin.maximumTimeToUnlock > 0
4073 && timeMs > admin.maximumTimeToUnlock) {
4074 timeMs = admin.maximumTimeToUnlock;
4076 // If userInfo.id is a managed profile, we also need to look at
4077 // the policies set on the parent.
4078 if (admin.hasParentActiveAdmin()) {
4079 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4080 if (parentAdmin.maximumTimeToUnlock > 0
4081 && timeMs > parentAdmin.maximumTimeToUnlock) {
4082 timeMs = parentAdmin.maximumTimeToUnlock;
4088 // We only store the last maximum time to lock on the parent profile. So if calling from a
4089 // managed profile, retrieve the policy for the parent.
4090 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4091 if (policy.mLastMaximumTimeToLock == timeMs) {
4094 policy.mLastMaximumTimeToLock = timeMs;
4096 final long ident = mInjector.binderClearCallingIdentity();
4098 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4099 // Make sure KEEP_SCREEN_ON is disabled, since that
4100 // would allow bypassing of the maximum time to lock.
4101 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4104 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4105 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4107 mInjector.binderRestoreCallingIdentity(ident);
4112 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4116 enforceFullCrossUsersPermission(userHandle);
4117 synchronized (this) {
4119 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4120 return admin != null ? admin.maximumTimeToUnlock : 0;
4122 // Return the strictest policy across all participating admins.
4123 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4124 userHandle, parent);
4125 return getMaximumTimeToLockPolicyFromAdmins(admins);
4130 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4134 enforceFullCrossUsersPermission(userHandle);
4135 synchronized (this) {
4136 // All admins for this user.
4137 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4138 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4139 DevicePolicyData policy = getUserData(userInfo.id);
4140 admins.addAll(policy.mAdminList);
4141 // If it is a managed profile, it may have parent active admins
4142 if (userInfo.isManagedProfile()) {
4143 for (ActiveAdmin admin : policy.mAdminList) {
4144 if (admin.hasParentActiveAdmin()) {
4145 admins.add(admin.getParentActiveAdmin());
4150 return getMaximumTimeToLockPolicyFromAdmins(admins);
4154 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4156 final int N = admins.size();
4157 for (int i = 0; i < N; i++) {
4158 ActiveAdmin admin = admins.get(i);
4160 time = admin.maximumTimeToUnlock;
4161 } else if (admin.maximumTimeToUnlock != 0
4162 && time > admin.maximumTimeToUnlock) {
4163 time = admin.maximumTimeToUnlock;
4170 public void lockNow(boolean parent) {
4174 synchronized (this) {
4175 // This API can only be called by an active device admin,
4176 // so try to retrieve it to check that the caller is one.
4177 getActiveAdminForCallerLocked(
4178 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4180 int userToLock = mInjector.userHandleGetCallingUserId();
4182 // Unless this is a managed profile with work challenge enabled, lock all users.
4183 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4184 userToLock = UserHandle.USER_ALL;
4186 final long ident = mInjector.binderClearCallingIdentity();
4188 mLockPatternUtils.requireStrongAuth(
4189 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4190 if (userToLock == UserHandle.USER_ALL) {
4191 // Power off the display
4192 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4193 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4194 mInjector.getIWindowManager().lockNow(null);
4196 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4198 } catch (RemoteException e) {
4200 mInjector.binderRestoreCallingIdentity(ident);
4206 public void enforceCanManageCaCerts(ComponentName who) {
4208 if (!isCallerDelegatedCertInstaller()) {
4209 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4212 synchronized (this) {
4213 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4218 private void enforceCanManageInstalledKeys(ComponentName who) {
4220 if (!isCallerDelegatedCertInstaller()) {
4221 throw new SecurityException("who == null, but caller is not cert installer");
4224 synchronized (this) {
4225 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4230 private boolean isCallerDelegatedCertInstaller() {
4231 final int callingUid = mInjector.binderGetCallingUid();
4232 final int userHandle = UserHandle.getUserId(callingUid);
4233 synchronized (this) {
4234 final DevicePolicyData policy = getUserData(userHandle);
4235 if (policy.mDelegatedCertInstallerPackage == null) {
4240 int uid = mContext.getPackageManager().getPackageUidAsUser(
4241 policy.mDelegatedCertInstallerPackage, userHandle);
4242 return uid == callingUid;
4243 } catch (NameNotFoundException e) {
4250 public boolean approveCaCert(String alias, int userId, boolean approval) {
4251 enforceManageUsers();
4252 synchronized (this) {
4253 Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4254 boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4258 saveSettingsLocked(userId);
4260 new MonitoringCertNotificationTask().execute(userId);
4265 public boolean isCaCertApproved(String alias, int userId) {
4266 enforceManageUsers();
4267 synchronized (this) {
4268 return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4272 private void removeCaApprovalsIfNeeded(int userId) {
4273 for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4274 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4275 if (userInfo.isManagedProfile()){
4276 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4279 synchronized (this) {
4280 getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4281 saveSettingsLocked(userInfo.id);
4284 new MonitoringCertNotificationTask().execute(userInfo.id);
4290 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4291 enforceCanManageCaCerts(admin);
4295 X509Certificate cert = parseCert(certBuffer);
4296 pemCert = Credentials.convertToPem(cert);
4297 } catch (CertificateException ce) {
4298 Log.e(LOG_TAG, "Problem converting cert", ce);
4300 } catch (IOException ioe) {
4301 Log.e(LOG_TAG, "Problem reading cert", ioe);
4305 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4306 final long id = mInjector.binderClearCallingIdentity();
4308 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4310 keyChainConnection.getService().installCaCertificate(pemCert);
4312 } catch (RemoteException e) {
4313 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4315 keyChainConnection.close();
4317 } catch (InterruptedException e1) {
4318 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4319 Thread.currentThread().interrupt();
4321 mInjector.binderRestoreCallingIdentity(id);
4326 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4327 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4328 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4333 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4334 enforceCanManageCaCerts(admin);
4336 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4337 final long id = mInjector.binderClearCallingIdentity();
4339 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4341 for (int i = 0 ; i < aliases.length; i++) {
4342 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4344 } catch (RemoteException e) {
4345 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4347 keyChainConnection.close();
4349 } catch (InterruptedException ie) {
4350 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4351 Thread.currentThread().interrupt();
4353 mInjector.binderRestoreCallingIdentity(id);
4358 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4359 String alias, boolean requestAccess) {
4360 enforceCanManageInstalledKeys(who);
4362 final int callingUid = mInjector.binderGetCallingUid();
4363 final long id = mInjector.binderClearCallingIdentity();
4365 final KeyChainConnection keyChainConnection =
4366 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4368 IKeyChainService keyChain = keyChainConnection.getService();
4369 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4372 if (requestAccess) {
4373 keyChain.setGrant(callingUid, alias, true);
4376 } catch (RemoteException e) {
4377 Log.e(LOG_TAG, "Installing certificate", e);
4379 keyChainConnection.close();
4381 } catch (InterruptedException e) {
4382 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4383 Thread.currentThread().interrupt();
4385 mInjector.binderRestoreCallingIdentity(id);
4391 public boolean removeKeyPair(ComponentName who, String alias) {
4392 enforceCanManageInstalledKeys(who);
4394 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4395 final long id = Binder.clearCallingIdentity();
4397 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4399 IKeyChainService keyChain = keyChainConnection.getService();
4400 return keyChain.removeKeyPair(alias);
4401 } catch (RemoteException e) {
4402 Log.e(LOG_TAG, "Removing keypair", e);
4404 keyChainConnection.close();
4406 } catch (InterruptedException e) {
4407 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4408 Thread.currentThread().interrupt();
4410 Binder.restoreCallingIdentity(id);
4416 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4417 final IBinder response) {
4418 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4419 if (!isCallerWithSystemUid()) {
4423 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4424 // If there is a profile owner, redirect to that; otherwise query the device owner.
4425 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4426 if (aliasChooser == null && caller.isSystem()) {
4427 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4428 if (deviceOwnerAdmin != null) {
4429 aliasChooser = deviceOwnerAdmin.info.getComponent();
4432 if (aliasChooser == null) {
4433 sendPrivateKeyAliasResponse(null, response);
4437 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4438 intent.setComponent(aliasChooser);
4439 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4440 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4441 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4442 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4443 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4445 final long id = mInjector.binderClearCallingIdentity();
4447 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4449 public void onReceive(Context context, Intent intent) {
4450 final String chosenAlias = getResultData();
4451 sendPrivateKeyAliasResponse(chosenAlias, response);
4453 }, null, Activity.RESULT_OK, null, null);
4455 mInjector.binderRestoreCallingIdentity(id);
4459 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4460 final IKeyChainAliasCallback keyChainAliasResponse =
4461 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4462 new AsyncTask<Void, Void, Void>() {
4464 protected Void doInBackground(Void... unused) {
4466 keyChainAliasResponse.alias(alias);
4467 } catch (Exception e) {
4468 // Catch everything (not just RemoteException): caller could throw a
4469 // RuntimeException back across processes.
4470 Log.e(LOG_TAG, "error while responding to callback", e);
4478 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4479 throws SecurityException {
4480 int userHandle = UserHandle.getCallingUserId();
4481 synchronized (this) {
4482 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4483 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4484 if (installerPackage != null &&
4485 !isPackageInstalledForUser(installerPackage, userHandle)) {
4486 throw new IllegalArgumentException("Package " + installerPackage
4487 + " is not installed on the current user");
4490 DevicePolicyData policy = getUserData(userHandle);
4491 policy.mDelegatedCertInstallerPackage = installerPackage;
4492 saveSettingsLocked(userHandle);
4497 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4498 int userHandle = UserHandle.getCallingUserId();
4499 synchronized (this) {
4500 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4501 DevicePolicyData policy = getUserData(userHandle);
4502 return policy.mDelegatedCertInstallerPackage;
4507 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4508 * not installed and therefore not available.
4510 * @throws SecurityException if the caller is not a profile or device owner.
4511 * @throws UnsupportedException if the package does not support being set as always-on.
4514 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4515 throws SecurityException {
4516 synchronized (this) {
4517 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4520 final int userId = mInjector.userHandleGetCallingUserId();
4521 final long token = mInjector.binderClearCallingIdentity();
4523 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4526 ConnectivityManager connectivityManager = (ConnectivityManager)
4527 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4528 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4529 throw new UnsupportedOperationException();
4532 mInjector.binderRestoreCallingIdentity(token);
4538 public String getAlwaysOnVpnPackage(ComponentName admin)
4539 throws SecurityException {
4540 synchronized (this) {
4541 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4544 final int userId = mInjector.userHandleGetCallingUserId();
4545 final long token = mInjector.binderClearCallingIdentity();
4547 ConnectivityManager connectivityManager = (ConnectivityManager)
4548 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4549 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4551 mInjector.binderRestoreCallingIdentity(token);
4555 private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
4556 if (wipeExtRequested) {
4557 StorageManager sm = (StorageManager) mContext.getSystemService(
4558 Context.STORAGE_SERVICE);
4559 sm.wipeAdoptableDisks();
4562 RecoverySystem.rebootWipeUserData(mContext, reason);
4563 } catch (IOException | SecurityException e) {
4564 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4569 public void wipeData(int flags) {
4573 final int userHandle = mInjector.userHandleGetCallingUserId();
4574 enforceFullCrossUsersPermission(userHandle);
4576 final String source;
4577 synchronized (this) {
4578 // This API can only be called by an active device admin,
4579 // so try to retrieve it to check that the caller is one.
4580 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4581 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4582 source = admin.info.getComponent().flattenToShortString();
4584 long ident = mInjector.binderClearCallingIdentity();
4586 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4587 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4588 throw new SecurityException(
4589 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4591 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4592 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4593 if (manager != null) {
4598 mInjector.binderRestoreCallingIdentity(ident);
4601 final boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4602 wipeDeviceNoLock(wipeExtRequested, userHandle,
4603 "DevicePolicyManager.wipeData() from " + source);
4606 private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
4607 final long ident = mInjector.binderClearCallingIdentity();
4609 if (userHandle == UserHandle.USER_SYSTEM) {
4610 wipeDataNoLock(wipeExtRequested, reason);
4612 mHandler.post(new Runnable() {
4616 IActivityManager am = mInjector.getIActivityManager();
4617 if (am.getCurrentUser().id == userHandle) {
4618 am.switchUser(UserHandle.USER_SYSTEM);
4621 boolean isManagedProfile = isManagedProfile(userHandle);
4622 if (!mUserManager.removeUser(userHandle)) {
4623 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4624 } else if (isManagedProfile) {
4625 sendWipeProfileNotification();
4627 } catch (RemoteException re) {
4634 mInjector.binderRestoreCallingIdentity(ident);
4638 private void sendWipeProfileNotification() {
4639 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4640 Notification notification = new Notification.Builder(mContext)
4641 .setSmallIcon(android.R.drawable.stat_sys_warning)
4642 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4643 .setContentText(contentText)
4644 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4645 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4647 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4650 private void clearWipeProfileNotification() {
4651 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4655 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4659 enforceFullCrossUsersPermission(userHandle);
4660 mContext.enforceCallingOrSelfPermission(
4661 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4663 synchronized (this) {
4664 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4665 if (admin == null) {
4666 result.sendResult(null);
4669 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4670 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4671 intent.setComponent(admin.info.getComponent());
4672 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4673 null, new BroadcastReceiver() {
4675 public void onReceive(Context context, Intent intent) {
4676 result.sendResult(getResultExtras(false));
4678 }, null, Activity.RESULT_OK, null, null);
4683 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4684 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4688 enforceFullCrossUsersPermission(userHandle);
4689 mContext.enforceCallingOrSelfPermission(
4690 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4692 // If the managed profile doesn't have a separate password, set the metrics to default
4693 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
4694 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4704 validateQualityConstant(quality);
4705 DevicePolicyData policy = getUserData(userHandle);
4706 synchronized (this) {
4707 policy.mActivePasswordQuality = quality;
4708 policy.mActivePasswordLength = length;
4709 policy.mActivePasswordLetters = letters;
4710 policy.mActivePasswordLowerCase = lowercase;
4711 policy.mActivePasswordUpperCase = uppercase;
4712 policy.mActivePasswordNumeric = numbers;
4713 policy.mActivePasswordSymbols = symbols;
4714 policy.mActivePasswordNonLetter = nonletter;
4719 public void reportPasswordChanged(int userId) {
4723 enforceFullCrossUsersPermission(userId);
4725 // Managed Profile password can only be changed when it has a separate challenge.
4726 if (!isSeparateProfileChallengeEnabled(userId)) {
4727 enforceNotManagedProfile(userId, "set the active password");
4730 mContext.enforceCallingOrSelfPermission(
4731 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4733 DevicePolicyData policy = getUserData(userId);
4735 long ident = mInjector.binderClearCallingIdentity();
4737 synchronized (this) {
4738 policy.mFailedPasswordAttempts = 0;
4739 saveSettingsLocked(userId);
4740 updatePasswordExpirationsLocked(userId);
4741 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
4743 // Send a broadcast to each profile using this password as its primary unlock.
4744 sendAdminCommandForLockscreenPoliciesLocked(
4745 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4746 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
4748 removeCaApprovalsIfNeeded(userId);
4750 mInjector.binderRestoreCallingIdentity(ident);
4755 * Called any time the device password is updated. Resets all password expiration clocks.
4757 private void updatePasswordExpirationsLocked(int userHandle) {
4758 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4759 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4760 userHandle, /* parent */ false);
4761 final int N = admins.size();
4762 for (int i = 0; i < N; i++) {
4763 ActiveAdmin admin = admins.get(i);
4764 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4765 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4766 long timeout = admin.passwordExpirationTimeout;
4767 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4768 admin.passwordExpirationDate = expiration;
4771 for (int affectedUserId : affectedUserIds) {
4772 saveSettingsLocked(affectedUserId);
4777 public void reportFailedPasswordAttempt(int userHandle) {
4778 enforceFullCrossUsersPermission(userHandle);
4779 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4780 enforceNotManagedProfile(userHandle,
4781 "report failed password attempt if separate profile challenge is not in place");
4783 mContext.enforceCallingOrSelfPermission(
4784 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4786 final long ident = mInjector.binderClearCallingIdentity();
4788 boolean wipeData = false;
4790 synchronized (this) {
4791 DevicePolicyData policy = getUserData(userHandle);
4792 policy.mFailedPasswordAttempts++;
4793 saveSettingsLocked(userHandle);
4795 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4796 userHandle, /* parent */ false);
4797 int max = strictestAdmin != null
4798 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4799 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4800 // Wipe the user/profile associated with the policy that was violated. This
4801 // is not necessarily calling user: if the policy that fired was from a
4802 // managed profile rather than the main user profile, we wipe former only.
4804 identifier = strictestAdmin.getUserHandle().getIdentifier();
4807 sendAdminCommandForLockscreenPoliciesLocked(
4808 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
4809 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4813 // Call without holding lock.
4814 wipeDeviceNoLock(false, identifier,
4815 "reportFailedPasswordAttempt()");
4818 mInjector.binderRestoreCallingIdentity(ident);
4821 if (mInjector.securityLogIsLoggingEnabled()) {
4822 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4823 /*method strength*/ 1);
4828 public void reportSuccessfulPasswordAttempt(int userHandle) {
4829 enforceFullCrossUsersPermission(userHandle);
4830 mContext.enforceCallingOrSelfPermission(
4831 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4833 synchronized (this) {
4834 DevicePolicyData policy = getUserData(userHandle);
4835 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
4836 long ident = mInjector.binderClearCallingIdentity();
4838 policy.mFailedPasswordAttempts = 0;
4839 policy.mPasswordOwner = -1;
4840 saveSettingsLocked(userHandle);
4842 sendAdminCommandForLockscreenPoliciesLocked(
4843 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
4844 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4847 mInjector.binderRestoreCallingIdentity(ident);
4852 if (mInjector.securityLogIsLoggingEnabled()) {
4853 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4854 /*method strength*/ 1);
4859 public void reportFailedFingerprintAttempt(int userHandle) {
4860 enforceFullCrossUsersPermission(userHandle);
4861 mContext.enforceCallingOrSelfPermission(
4862 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4863 if (mInjector.securityLogIsLoggingEnabled()) {
4864 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4865 /*method strength*/ 0);
4870 public void reportSuccessfulFingerprintAttempt(int userHandle) {
4871 enforceFullCrossUsersPermission(userHandle);
4872 mContext.enforceCallingOrSelfPermission(
4873 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4874 if (mInjector.securityLogIsLoggingEnabled()) {
4875 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4876 /*method strength*/ 0);
4881 public void reportKeyguardDismissed(int userHandle) {
4882 enforceFullCrossUsersPermission(userHandle);
4883 mContext.enforceCallingOrSelfPermission(
4884 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4886 if (mInjector.securityLogIsLoggingEnabled()) {
4887 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
4892 public void reportKeyguardSecured(int userHandle) {
4893 enforceFullCrossUsersPermission(userHandle);
4894 mContext.enforceCallingOrSelfPermission(
4895 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4897 if (mInjector.securityLogIsLoggingEnabled()) {
4898 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
4903 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
4904 String exclusionList) {
4908 synchronized(this) {
4909 Preconditions.checkNotNull(who, "ComponentName is null");
4911 // Only check if system user has set global proxy. We don't allow other users to set it.
4912 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4913 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4914 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
4916 // Scan through active admins and find if anyone has already
4917 // set the global proxy.
4918 Set<ComponentName> compSet = policy.mAdminMap.keySet();
4919 for (ComponentName component : compSet) {
4920 ActiveAdmin ap = policy.mAdminMap.get(component);
4921 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
4922 // Another admin already sets the global proxy
4923 // Return it to the caller.
4928 // If the user is not system, don't set the global proxy. Fail silently.
4929 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
4930 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
4931 + UserHandle.getCallingUserId() + " is not permitted.");
4934 if (proxySpec == null) {
4935 admin.specifiesGlobalProxy = false;
4936 admin.globalProxySpec = null;
4937 admin.globalProxyExclusionList = null;
4940 admin.specifiesGlobalProxy = true;
4941 admin.globalProxySpec = proxySpec;
4942 admin.globalProxyExclusionList = exclusionList;
4945 // Reset the global proxy accordingly
4946 // Do this using system permissions, as apps cannot write to secure settings
4947 long origId = mInjector.binderClearCallingIdentity();
4949 resetGlobalProxyLocked(policy);
4951 mInjector.binderRestoreCallingIdentity(origId);
4958 public ComponentName getGlobalProxyAdmin(int userHandle) {
4962 enforceFullCrossUsersPermission(userHandle);
4963 synchronized(this) {
4964 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4965 // Scan through active admins and find if anyone has already
4966 // set the global proxy.
4967 final int N = policy.mAdminList.size();
4968 for (int i = 0; i < N; i++) {
4969 ActiveAdmin ap = policy.mAdminList.get(i);
4970 if (ap.specifiesGlobalProxy) {
4971 // Device admin sets the global proxy
4972 // Return it to the caller.
4973 return ap.info.getComponent();
4977 // No device admin sets the global proxy.
4982 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
4983 synchronized (this) {
4984 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4986 long token = mInjector.binderClearCallingIdentity();
4988 ConnectivityManager connectivityManager = (ConnectivityManager)
4989 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4990 connectivityManager.setGlobalProxy(proxyInfo);
4992 mInjector.binderRestoreCallingIdentity(token);
4996 private void resetGlobalProxyLocked(DevicePolicyData policy) {
4997 final int N = policy.mAdminList.size();
4998 for (int i = 0; i < N; i++) {
4999 ActiveAdmin ap = policy.mAdminList.get(i);
5000 if (ap.specifiesGlobalProxy) {
5001 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5005 // No device admins defining global proxies - reset global proxy settings to none
5006 saveGlobalProxyLocked(null, null);
5009 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5010 if (exclusionList == null) {
5013 if (proxySpec == null) {
5016 // Remove white spaces
5017 proxySpec = proxySpec.trim();
5018 String data[] = proxySpec.split(":");
5019 int proxyPort = 8080;
5020 if (data.length > 1) {
5022 proxyPort = Integer.parseInt(data[1]);
5023 } catch (NumberFormatException e) {}
5025 exclusionList = exclusionList.trim();
5027 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5028 if (!proxyProperties.isValid()) {
5029 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5032 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5033 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5034 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5039 * Set the storage encryption request for a single admin. Returns the new total request
5040 * status (for all admins).
5043 public int setStorageEncryption(ComponentName who, boolean encrypt) {
5045 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5047 Preconditions.checkNotNull(who, "ComponentName is null");
5048 final int userHandle = UserHandle.getCallingUserId();
5049 synchronized (this) {
5050 // Check for permissions
5051 // Only system user can set storage encryption
5052 if (userHandle != UserHandle.USER_SYSTEM) {
5053 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5054 + UserHandle.getCallingUserId() + " is not permitted.");
5058 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5059 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5061 // Quick exit: If the filesystem does not support encryption, we can exit early.
5062 if (!isEncryptionSupported()) {
5063 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5066 // (1) Record the value for the admin so it's sticky
5067 if (ap.encryptionRequested != encrypt) {
5068 ap.encryptionRequested = encrypt;
5069 saveSettingsLocked(userHandle);
5072 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5073 // (2) Compute "max" for all admins
5074 boolean newRequested = false;
5075 final int N = policy.mAdminList.size();
5076 for (int i = 0; i < N; i++) {
5077 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5080 // Notify OS of new request
5081 setEncryptionRequested(newRequested);
5083 // Return the new global request status
5085 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5086 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5091 * Get the current storage encryption request status for a given admin, or aggregate of all
5095 public boolean getStorageEncryption(ComponentName who, int userHandle) {
5099 enforceFullCrossUsersPermission(userHandle);
5100 synchronized (this) {
5101 // Check for permissions if a particular caller is specified
5103 // When checking for a single caller, status is based on caller's request
5104 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5105 return ap != null ? ap.encryptionRequested : false;
5108 // If no particular caller is specified, return the aggregate set of requests.
5109 // This is short circuited by returning true on the first hit.
5110 DevicePolicyData policy = getUserData(userHandle);
5111 final int N = policy.mAdminList.size();
5112 for (int i = 0; i < N; i++) {
5113 if (policy.mAdminList.get(i).encryptionRequested) {
5122 * Get the current encryption status of the device.
5125 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5127 // Ok to return current status.
5129 enforceFullCrossUsersPermission(userHandle);
5131 // It's not critical here, but let's make sure the package name is correct, in case
5132 // we start using it for different purposes.
5133 ensureCallerPackage(callerPackage);
5135 final ApplicationInfo ai;
5137 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5138 } catch (RemoteException e) {
5139 throw new SecurityException(e);
5142 boolean legacyApp = false;
5143 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5147 final int rawStatus = getEncryptionStatus();
5148 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5149 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5155 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
5157 private boolean isEncryptionSupported() {
5158 // Note, this can be implemented as
5159 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5160 // But is provided as a separate internal method if there's a faster way to do a
5161 // simple check for supported-or-not.
5162 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5166 * Hook to low-levels: Reporting the current status of encryption.
5167 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5168 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5169 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5170 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5171 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5173 private int getEncryptionStatus() {
5174 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5175 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5176 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5177 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5178 } else if (mInjector.storageManagerIsEncrypted()) {
5179 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5180 } else if (mInjector.storageManagerIsEncryptable()) {
5181 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5183 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5188 * Hook to low-levels: If needed, record the new admin setting for encryption.
5190 private void setEncryptionRequested(boolean encrypt) {
5194 * Set whether the screen capture is disabled for the user managed by the specified admin.
5197 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5201 Preconditions.checkNotNull(who, "ComponentName is null");
5202 final int userHandle = UserHandle.getCallingUserId();
5203 synchronized (this) {
5204 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5205 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5206 if (ap.disableScreenCapture != disabled) {
5207 ap.disableScreenCapture = disabled;
5208 saveSettingsLocked(userHandle);
5209 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5215 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5216 * active admin (if given admin is null).
5219 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5223 synchronized (this) {
5225 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5226 return (admin != null) ? admin.disableScreenCapture : false;
5229 DevicePolicyData policy = getUserData(userHandle);
5230 final int N = policy.mAdminList.size();
5231 for (int i = 0; i < N; i++) {
5232 ActiveAdmin admin = policy.mAdminList.get(i);
5233 if (admin.disableScreenCapture) {
5241 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5242 final boolean disabled) {
5243 mHandler.post(new Runnable() {
5247 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5248 } catch (RemoteException e) {
5249 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5256 * Set whether auto time is required by the specified admin (must be device owner).
5259 public void setAutoTimeRequired(ComponentName who, boolean required) {
5263 Preconditions.checkNotNull(who, "ComponentName is null");
5264 final int userHandle = UserHandle.getCallingUserId();
5265 synchronized (this) {
5266 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5267 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5268 if (admin.requireAutoTime != required) {
5269 admin.requireAutoTime = required;
5270 saveSettingsLocked(userHandle);
5274 // Turn AUTO_TIME on in settings if it is required
5276 long ident = mInjector.binderClearCallingIdentity();
5278 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5280 mInjector.binderRestoreCallingIdentity(ident);
5286 * Returns whether or not auto time is required by the device owner.
5289 public boolean getAutoTimeRequired() {
5293 synchronized (this) {
5294 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5295 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5300 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5304 Preconditions.checkNotNull(who, "ComponentName is null");
5305 // Allow setting this policy to true only if there is a split system user.
5306 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5307 throw new UnsupportedOperationException(
5308 "Cannot force ephemeral users on systems without split system user.");
5310 boolean removeAllUsers = false;
5311 synchronized (this) {
5312 final ActiveAdmin deviceOwner =
5313 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5314 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5315 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5316 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5317 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5318 removeAllUsers = forceEphemeralUsers;
5321 if (removeAllUsers) {
5322 long identitity = mInjector.binderClearCallingIdentity();
5324 mUserManagerInternal.removeAllUsers();
5326 mInjector.binderRestoreCallingIdentity(identitity);
5332 public boolean getForceEphemeralUsers(ComponentName who) {
5336 Preconditions.checkNotNull(who, "ComponentName is null");
5337 synchronized (this) {
5338 final ActiveAdmin deviceOwner =
5339 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5340 return deviceOwner.forceEphemeralUsers;
5344 private boolean isDeviceOwnerManagedSingleUserDevice() {
5345 synchronized (this) {
5346 if (!mOwners.hasDeviceOwner()) {
5350 final long callingIdentity = mInjector.binderClearCallingIdentity();
5352 if (mInjector.userManagerIsSplitSystemUser()) {
5353 // In split system user mode, only allow the case where the device owner is managing
5354 // the only non-system user of the device
5355 return (mUserManager.getUserCount() == 2
5356 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5358 return mUserManager.getUserCount() == 1;
5361 mInjector.binderRestoreCallingIdentity(callingIdentity);
5365 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5366 synchronized (this) {
5367 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5369 if (!isDeviceOwnerManagedSingleUserDevice()) {
5370 throw new SecurityException(
5371 "There should only be one user, managed by Device Owner");
5376 public boolean requestBugreport(ComponentName who) {
5380 Preconditions.checkNotNull(who, "ComponentName is null");
5381 ensureDeviceOwnerManagingSingleUser(who);
5383 if (mRemoteBugreportServiceIsActive.get()
5384 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5385 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5389 final long callingIdentity = mInjector.binderClearCallingIdentity();
5391 ActivityManagerNative.getDefault().requestBugReport(
5392 ActivityManager.BUGREPORT_OPTION_REMOTE);
5394 mRemoteBugreportServiceIsActive.set(true);
5395 mRemoteBugreportSharingAccepted.set(false);
5396 registerRemoteBugreportReceivers();
5397 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5398 RemoteBugreportUtils.buildNotification(mContext,
5399 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5400 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5401 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5403 } catch (RemoteException re) {
5404 // should never happen
5405 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5408 mInjector.binderRestoreCallingIdentity(callingIdentity);
5412 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5413 Intent intent = new Intent(action);
5414 intent.setComponent(mOwners.getDeviceOwnerComponent());
5415 if (extras != null) {
5416 intent.putExtras(extras);
5418 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5421 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5422 return mOwners.getDeviceOwnerRemoteBugreportUri();
5425 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5426 String bugreportHash) {
5427 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5430 private void registerRemoteBugreportReceivers() {
5432 IntentFilter filterFinished = new IntentFilter(
5433 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5434 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5435 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5436 } catch (IntentFilter.MalformedMimeTypeException e) {
5437 // should never happen, as setting a constant
5438 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5440 IntentFilter filterConsent = new IntentFilter();
5441 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5442 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5443 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5446 private void onBugreportFinished(Intent intent) {
5447 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5448 mRemoteBugreportServiceIsActive.set(false);
5449 Uri bugreportUri = intent.getData();
5450 String bugreportUriString = null;
5451 if (bugreportUri != null) {
5452 bugreportUriString = bugreportUri.toString();
5454 String bugreportHash = intent.getStringExtra(
5455 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5456 if (mRemoteBugreportSharingAccepted.get()) {
5457 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5458 mInjector.getNotificationManager().cancel(LOG_TAG,
5459 RemoteBugreportUtils.NOTIFICATION_ID);
5461 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5462 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5463 RemoteBugreportUtils.buildNotification(mContext,
5464 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5467 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5470 private void onBugreportFailed() {
5471 mRemoteBugreportServiceIsActive.set(false);
5472 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5473 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5474 mRemoteBugreportSharingAccepted.set(false);
5475 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5476 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5477 Bundle extras = new Bundle();
5478 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5479 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5480 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5481 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5482 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5485 private void onBugreportSharingAccepted() {
5486 mRemoteBugreportSharingAccepted.set(true);
5487 String bugreportUriString = null;
5488 String bugreportHash = null;
5489 synchronized (this) {
5490 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5491 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5493 if (bugreportUriString != null) {
5494 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5495 } else if (mRemoteBugreportServiceIsActive.get()) {
5496 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5497 RemoteBugreportUtils.buildNotification(mContext,
5498 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5503 private void onBugreportSharingDeclined() {
5504 if (mRemoteBugreportServiceIsActive.get()) {
5505 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5506 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5507 mRemoteBugreportServiceIsActive.set(false);
5508 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5509 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5511 mRemoteBugreportSharingAccepted.set(false);
5512 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5513 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5516 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5517 String bugreportHash) {
5518 ParcelFileDescriptor pfd = null;
5520 if (bugreportUriString == null) {
5521 throw new FileNotFoundException();
5523 Uri bugreportUri = Uri.parse(bugreportUriString);
5524 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5526 synchronized (this) {
5527 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5528 intent.setComponent(mOwners.getDeviceOwnerComponent());
5529 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5530 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5531 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
5532 bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5533 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5535 } catch (FileNotFoundException e) {
5536 Bundle extras = new Bundle();
5537 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5538 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5539 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5545 } catch (IOException ex) {
5548 mRemoteBugreportSharingAccepted.set(false);
5549 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5554 * Disables all device cameras according to the specified admin.
5557 public void setCameraDisabled(ComponentName who, boolean disabled) {
5561 Preconditions.checkNotNull(who, "ComponentName is null");
5562 final int userHandle = mInjector.userHandleGetCallingUserId();
5563 synchronized (this) {
5564 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5565 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5566 if (ap.disableCamera != disabled) {
5567 ap.disableCamera = disabled;
5568 saveSettingsLocked(userHandle);
5571 // Tell the user manager that the restrictions have changed.
5572 pushUserRestrictions(userHandle);
5576 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5580 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5581 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5584 private boolean getCameraDisabled(ComponentName who, int userHandle,
5585 boolean mergeDeviceOwnerRestriction) {
5589 synchronized (this) {
5591 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5592 return (admin != null) ? admin.disableCamera : false;
5594 // First, see if DO has set it. If so, it's device-wide.
5595 if (mergeDeviceOwnerRestriction) {
5596 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5597 if (deviceOwner != null && deviceOwner.disableCamera) {
5602 // Then check each device admin on the user.
5603 DevicePolicyData policy = getUserData(userHandle);
5604 // Determine whether or not the device camera is disabled for any active admins.
5605 final int N = policy.mAdminList.size();
5606 for (int i = 0; i < N; i++) {
5607 ActiveAdmin admin = policy.mAdminList.get(i);
5608 if (admin.disableCamera) {
5617 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5621 Preconditions.checkNotNull(who, "ComponentName is null");
5622 final int userHandle = mInjector.userHandleGetCallingUserId();
5623 if (isManagedProfile(userHandle)) {
5625 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5627 which = which & PROFILE_KEYGUARD_FEATURES;
5630 synchronized (this) {
5631 ActiveAdmin ap = getActiveAdminForCallerLocked(
5632 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5633 if (ap.disabledKeyguardFeatures != which) {
5634 ap.disabledKeyguardFeatures = which;
5635 saveSettingsLocked(userHandle);
5641 * Gets the disabled state for features in keyguard for the given admin,
5642 * or the aggregate of all active admins if who is null.
5645 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5649 enforceFullCrossUsersPermission(userHandle);
5650 final long ident = mInjector.binderClearCallingIdentity();
5652 synchronized (this) {
5654 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5655 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5658 final List<ActiveAdmin> admins;
5659 if (!parent && isManagedProfile(userHandle)) {
5660 // If we are being asked about a managed profile, just return keyguard features
5661 // disabled by admins in the profile.
5662 admins = getUserDataUnchecked(userHandle).mAdminList;
5664 // Otherwise return those set by admins in the user and its profiles.
5665 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5668 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5669 final int N = admins.size();
5670 for (int i = 0; i < N; i++) {
5671 ActiveAdmin admin = admins.get(i);
5672 int userId = admin.getUserHandle().getIdentifier();
5673 boolean isRequestedUser = !parent && (userId == userHandle);
5674 if (isRequestedUser || !isManagedProfile(userId)) {
5675 // If we are being asked explicitly about this user
5676 // return all disabled features even if its a managed profile.
5677 which |= admin.disabledKeyguardFeatures;
5679 // Otherwise a managed profile is only allowed to disable
5680 // some features on the parent user.
5681 which |= (admin.disabledKeyguardFeatures
5682 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5688 mInjector.binderRestoreCallingIdentity(ident);
5693 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5697 Preconditions.checkNotNull(who, "ComponentName is null");
5698 Preconditions.checkNotNull(packageList, "packageList is null");
5699 final int userHandle = UserHandle.getCallingUserId();
5700 synchronized (this) {
5701 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5702 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5703 admin.keepUninstalledPackages = packageList;
5704 saveSettingsLocked(userHandle);
5705 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5710 public List<String> getKeepUninstalledPackages(ComponentName who) {
5711 Preconditions.checkNotNull(who, "ComponentName is null");
5715 // TODO In split system user mode, allow apps on user 0 to query the list
5716 synchronized (this) {
5717 // Check if this is the device owner who is calling
5718 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5719 return getKeepUninstalledPackagesLocked();
5723 private List<String> getKeepUninstalledPackagesLocked() {
5724 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5725 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5729 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5734 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5735 throw new IllegalArgumentException("Invalid component " + admin
5736 + " for device owner");
5738 synchronized (this) {
5739 enforceCanSetDeviceOwnerLocked(userId);
5740 if (getActiveAdminUncheckedLocked(admin, userId) == null
5741 || getUserData(userId).mRemovingAdmins.contains(admin)) {
5742 throw new IllegalArgumentException("Not active admin: " + admin);
5745 // Shutting down backup manager service permanently.
5746 long ident = mInjector.binderClearCallingIdentity();
5748 if (mInjector.getIBackupManager() != null) {
5749 mInjector.getIBackupManager()
5750 .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5752 } catch (RemoteException e) {
5753 throw new IllegalStateException("Failed deactivating backup service.", e);
5755 mInjector.binderRestoreCallingIdentity(ident);
5758 mOwners.setDeviceOwner(admin, ownerName, userId);
5759 mOwners.writeDeviceOwner();
5760 updateDeviceOwnerLocked();
5761 setDeviceOwnerSystemPropertyLocked();
5762 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5764 ident = mInjector.binderClearCallingIdentity();
5766 // TODO Send to system too?
5767 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5769 mInjector.binderRestoreCallingIdentity(ident);
5775 public boolean isDeviceOwner(ComponentName who, int userId) {
5776 synchronized (this) {
5777 return mOwners.hasDeviceOwner()
5778 && mOwners.getDeviceOwnerUserId() == userId
5779 && mOwners.getDeviceOwnerComponent().equals(who);
5783 public boolean isProfileOwner(ComponentName who, int userId) {
5784 final ComponentName profileOwner = getProfileOwner(userId);
5785 return who != null && who.equals(profileOwner);
5789 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5793 if (!callingUserOnly) {
5794 enforceManageUsers();
5796 synchronized (this) {
5797 if (!mOwners.hasDeviceOwner()) {
5800 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
5801 mOwners.getDeviceOwnerUserId()) {
5804 return mOwners.getDeviceOwnerComponent();
5809 public int getDeviceOwnerUserId() {
5811 return UserHandle.USER_NULL;
5813 enforceManageUsers();
5814 synchronized (this) {
5815 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
5820 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
5824 public String getDeviceOwnerName() {
5828 enforceManageUsers();
5829 synchronized (this) {
5830 if (!mOwners.hasDeviceOwner()) {
5833 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
5834 // Should setDeviceOwner/ProfileOwner still take a name?
5835 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
5836 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
5840 // Returns the active device owner or null if there is no device owner.
5842 ActiveAdmin getDeviceOwnerAdminLocked() {
5843 ComponentName component = mOwners.getDeviceOwnerComponent();
5844 if (component == null) {
5848 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
5849 final int n = policy.mAdminList.size();
5850 for (int i = 0; i < n; i++) {
5851 ActiveAdmin admin = policy.mAdminList.get(i);
5852 if (component.equals(admin.info.getComponent())) {
5856 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
5861 public void clearDeviceOwner(String packageName) {
5862 Preconditions.checkNotNull(packageName, "packageName is null");
5863 final int callingUid = mInjector.binderGetCallingUid();
5865 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
5866 UserHandle.getUserId(callingUid));
5867 if (uid != callingUid) {
5868 throw new SecurityException("Invalid packageName");
5870 } catch (NameNotFoundException e) {
5871 throw new SecurityException(e);
5873 synchronized (this) {
5874 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
5875 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
5876 if (!mOwners.hasDeviceOwner()
5877 || !deviceOwnerComponent.getPackageName().equals(packageName)
5878 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
5879 throw new SecurityException(
5880 "clearDeviceOwner can only be called by the device owner");
5882 enforceUserUnlocked(deviceOwnerUserId);
5884 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
5885 long ident = mInjector.binderClearCallingIdentity();
5887 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
5888 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
5890 mInjector.binderRestoreCallingIdentity(ident);
5895 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
5896 if (admin != null) {
5897 admin.disableCamera = false;
5898 admin.userRestrictions = null;
5899 admin.forceEphemeralUsers = false;
5900 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
5902 clearUserPoliciesLocked(userId);
5904 mOwners.clearDeviceOwner();
5905 mOwners.writeDeviceOwner();
5906 updateDeviceOwnerLocked();
5907 disableSecurityLoggingIfNotCompliant();
5909 // Reactivate backup service.
5910 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
5911 } catch (RemoteException e) {
5912 throw new IllegalStateException("Failed reactivating backup service.", e);
5917 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
5922 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
5923 throw new IllegalArgumentException("Component " + who
5924 + " not installed for userId:" + userHandle);
5926 synchronized (this) {
5927 enforceCanSetProfileOwnerLocked(userHandle);
5929 if (getActiveAdminUncheckedLocked(who, userHandle) == null
5930 || getUserData(userHandle).mRemovingAdmins.contains(who)) {
5931 throw new IllegalArgumentException("Not active admin: " + who);
5934 mOwners.setProfileOwner(who, ownerName, userHandle);
5935 mOwners.writeProfileOwner(userHandle);
5941 public void clearProfileOwner(ComponentName who) {
5945 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
5946 final int userId = callingUser.getIdentifier();
5947 enforceNotManagedProfile(userId, "clear profile owner");
5948 enforceUserUnlocked(userId);
5949 // Check if this is the profile owner who is calling
5950 final ActiveAdmin admin =
5951 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5952 synchronized (this) {
5953 final long ident = mInjector.binderClearCallingIdentity();
5955 clearProfileOwnerLocked(admin, userId);
5956 removeActiveAdminLocked(who, userId);
5958 mInjector.binderRestoreCallingIdentity(ident);
5963 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
5964 if (admin != null) {
5965 admin.disableCamera = false;
5966 admin.userRestrictions = null;
5968 clearUserPoliciesLocked(userId);
5969 mOwners.removeProfileOwner(userId);
5970 mOwners.writeProfileOwner(userId);
5974 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
5975 Preconditions.checkNotNull(who, "ComponentName is null");
5980 synchronized (this) {
5981 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5982 long token = mInjector.binderClearCallingIdentity();
5984 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
5986 mInjector.binderRestoreCallingIdentity(token);
5992 public CharSequence getDeviceOwnerLockScreenInfo() {
5993 return mLockPatternUtils.getDeviceOwnerInfo();
5996 private void clearUserPoliciesLocked(int userId) {
5997 // Reset some of the user-specific policies
5998 DevicePolicyData policy = getUserData(userId);
5999 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6000 policy.mDelegatedCertInstallerPackage = null;
6001 policy.mApplicationRestrictionsManagingPackage = null;
6002 policy.mStatusBarDisabled = false;
6003 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6004 saveSettingsLocked(userId);
6007 mIPackageManager.updatePermissionFlagsForAllApps(
6008 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6009 0 /* flagValues */, userId);
6010 pushUserRestrictions(userId);
6011 } catch (RemoteException re) {
6012 // Shouldn't happen.
6017 public boolean hasUserSetupCompleted() {
6018 return hasUserSetupCompleted(UserHandle.getCallingUserId());
6021 private boolean hasUserSetupCompleted(int userHandle) {
6025 return getUserData(userHandle).mUserSetupComplete;
6029 public int getUserProvisioningState() {
6031 return DevicePolicyManager.STATE_USER_UNMANAGED;
6033 int userHandle = mInjector.userHandleGetCallingUserId();
6034 return getUserProvisioningState(userHandle);
6037 private int getUserProvisioningState(int userHandle) {
6038 return getUserData(userHandle).mUserProvisioningState;
6042 public void setUserProvisioningState(int newState, int userHandle) {
6047 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6048 && getManagedUserId(userHandle) == -1) {
6049 // No managed device, user or profile, so setting provisioning state makes no sense.
6050 throw new IllegalStateException("Not allowed to change provisioning state unless a "
6051 + "device or profile owner is set.");
6054 synchronized (this) {
6055 boolean transitionCheckNeeded = true;
6057 // Calling identity/permission checks.
6058 final int callingUid = mInjector.binderGetCallingUid();
6059 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6060 // ADB shell can only move directly from un-managed to finalized as part of directly
6061 // setting profile-owner or device-owner.
6062 if (getUserProvisioningState(userHandle) !=
6063 DevicePolicyManager.STATE_USER_UNMANAGED
6064 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6065 throw new IllegalStateException("Not allowed to change provisioning state "
6066 + "unless current provisioning state is unmanaged, and new state is "
6069 transitionCheckNeeded = false;
6071 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6072 enforceCanManageProfileAndDeviceOwners();
6075 final DevicePolicyData policyData = getUserData(userHandle);
6076 if (transitionCheckNeeded) {
6077 // Optional state transition check for non-ADB case.
6078 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6080 policyData.mUserProvisioningState = newState;
6081 saveSettingsLocked(userHandle);
6085 private void checkUserProvisioningStateTransition(int currentState, int newState) {
6086 // Valid transitions for normal use-cases.
6087 switch (currentState) {
6088 case DevicePolicyManager.STATE_USER_UNMANAGED:
6089 // Can move to any state from unmanaged (except itself as an edge case)..
6090 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6094 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6095 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6096 // Can only move to finalized from these states.
6097 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6101 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6102 // Current user has a managed-profile, but current user is not managed, so
6103 // rather than moving to finalized state, go back to unmanaged once
6104 // profile provisioning is complete.
6105 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6109 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6110 // Cannot transition out of finalized.
6114 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6115 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6116 + "from state [" + currentState + "]");
6120 public void setProfileEnabled(ComponentName who) {
6124 Preconditions.checkNotNull(who, "ComponentName is null");
6125 synchronized (this) {
6126 // Check if this is the profile owner who is calling
6127 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6128 final int userId = UserHandle.getCallingUserId();
6129 enforceManagedProfile(userId, "enable the profile");
6131 long id = mInjector.binderClearCallingIdentity();
6133 mUserManager.setUserEnabled(userId);
6134 UserInfo parent = mUserManager.getProfileParent(userId);
6135 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6136 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6137 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6138 Intent.FLAG_RECEIVER_FOREGROUND);
6139 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6141 mInjector.binderRestoreCallingIdentity(id);
6147 public void setProfileName(ComponentName who, String profileName) {
6148 Preconditions.checkNotNull(who, "ComponentName is null");
6149 int userId = UserHandle.getCallingUserId();
6150 // Check if this is the profile owner (includes device owner).
6151 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6153 long id = mInjector.binderClearCallingIdentity();
6155 mUserManager.setUserName(userId, profileName);
6157 mInjector.binderRestoreCallingIdentity(id);
6162 public ComponentName getProfileOwner(int userHandle) {
6167 synchronized (this) {
6168 return mOwners.getProfileOwnerComponent(userHandle);
6172 // Returns the active profile owner for this user or null if the current user has no
6175 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6176 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6177 if (profileOwner == null) {
6180 DevicePolicyData policy = getUserData(userHandle);
6181 final int n = policy.mAdminList.size();
6182 for (int i = 0; i < n; i++) {
6183 ActiveAdmin admin = policy.mAdminList.get(i);
6184 if (profileOwner.equals(admin.info.getComponent())) {
6192 public String getProfileOwnerName(int userHandle) {
6196 enforceManageUsers();
6197 ComponentName profileOwner = getProfileOwner(userHandle);
6198 if (profileOwner == null) {
6201 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6205 * Canonical name for a given package.
6207 private String getApplicationLabel(String packageName, int userHandle) {
6208 long token = mInjector.binderClearCallingIdentity();
6210 final Context userContext;
6212 UserHandle handle = new UserHandle(userHandle);
6213 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6214 } catch (PackageManager.NameNotFoundException nnfe) {
6215 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6218 ApplicationInfo appInfo = userContext.getApplicationInfo();
6219 CharSequence result = null;
6220 if (appInfo != null) {
6221 PackageManager pm = userContext.getPackageManager();
6222 result = pm.getApplicationLabel(appInfo);
6224 return result != null ? result.toString() : null;
6226 mInjector.binderRestoreCallingIdentity(token);
6231 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6233 * The profile owner can only be set before the user setup phase has completed,
6236 * - adb if there are not accounts.
6238 private void enforceCanSetProfileOwnerLocked(int userHandle) {
6239 UserInfo info = getUserInfo(userHandle);
6241 // User doesn't exist.
6242 throw new IllegalArgumentException(
6243 "Attempted to set profile owner for invalid userId: " + userHandle);
6245 if (info.isGuest()) {
6246 throw new IllegalStateException("Cannot set a profile owner on a guest");
6248 if (mOwners.hasProfileOwner(userHandle)) {
6249 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6250 + "is already set.");
6252 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6253 throw new IllegalStateException("Trying to set the profile owner, but the user "
6254 + "already has a device owner.");
6256 int callingUid = mInjector.binderGetCallingUid();
6257 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6258 if (hasUserSetupCompleted(userHandle) &&
6259 AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) {
6260 throw new IllegalStateException("Not allowed to set the profile owner because "
6261 + "there are already some accounts on the profile");
6265 enforceCanManageProfileAndDeviceOwners();
6266 if (hasUserSetupCompleted(userHandle) && !isCallerWithSystemUid()) {
6267 throw new IllegalStateException("Cannot set the profile owner on a user which is "
6268 + "already set-up");
6273 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6276 private void enforceCanSetDeviceOwnerLocked(int userId) {
6277 int callingUid = mInjector.binderGetCallingUid();
6278 boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6280 enforceCanManageProfileAndDeviceOwners();
6283 final int code = checkSetDeviceOwnerPreCondition(userId, isAdb);
6287 case CODE_HAS_DEVICE_OWNER:
6288 throw new IllegalStateException(
6289 "Trying to set the device owner, but device owner is already set.");
6290 case CODE_USER_HAS_PROFILE_OWNER:
6291 throw new IllegalStateException("Trying to set the device owner, but the user "
6292 + "already has a profile owner.");
6293 case CODE_USER_NOT_RUNNING:
6294 throw new IllegalStateException("User not running: " + userId);
6295 case CODE_NOT_SYSTEM_USER:
6296 throw new IllegalStateException("User is not system user");
6297 case CODE_USER_SETUP_COMPLETED:
6298 throw new IllegalStateException(
6299 "Cannot set the device owner if the device is already set-up");
6300 case CODE_NONSYSTEM_USER_EXISTS:
6301 throw new IllegalStateException("Not allowed to set the device owner because there "
6302 + "are already several users on the device");
6303 case CODE_ACCOUNTS_NOT_EMPTY:
6304 throw new IllegalStateException("Not allowed to set the device owner because there "
6305 + "are already some accounts on the device");
6307 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6311 private void enforceUserUnlocked(int userId) {
6312 // Since we're doing this operation on behalf of an app, we only
6313 // want to use the actual "unlocked" state.
6314 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6315 "User must be running and unlocked");
6318 private void enforceUserUnlocked(int userId, boolean parent) {
6320 enforceUserUnlocked(getProfileParentId(userId));
6322 enforceUserUnlocked(userId);
6326 private void enforceManageUsers() {
6327 final int callingUid = mInjector.binderGetCallingUid();
6328 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6329 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6333 private void enforceFullCrossUsersPermission(int userHandle) {
6334 enforceSystemUserOrPermission(userHandle,
6335 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6338 private void enforceCrossUsersPermission(int userHandle) {
6339 enforceSystemUserOrPermission(userHandle,
6340 android.Manifest.permission.INTERACT_ACROSS_USERS);
6343 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6344 if (userHandle < 0) {
6345 throw new IllegalArgumentException("Invalid userId " + userHandle);
6347 final int callingUid = mInjector.binderGetCallingUid();
6348 if (userHandle == UserHandle.getUserId(callingUid)) {
6351 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6352 mContext.enforceCallingOrSelfPermission(permission,
6353 "Must be system or have " + permission + " permission");
6357 private void enforceManagedProfile(int userHandle, String message) {
6358 if(!isManagedProfile(userHandle)) {
6359 throw new SecurityException("You can not " + message + " outside a managed profile.");
6363 private void enforceNotManagedProfile(int userHandle, String message) {
6364 if(isManagedProfile(userHandle)) {
6365 throw new SecurityException("You can not " + message + " for a managed profile.");
6369 private void ensureCallerPackage(@Nullable String packageName) {
6370 if (packageName == null) {
6371 Preconditions.checkState(isCallerWithSystemUid(),
6372 "Only caller can omit package name");
6374 final int callingUid = mInjector.binderGetCallingUid();
6375 final int userId = mInjector.userHandleGetCallingUserId();
6377 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6378 packageName, 0, userId);
6379 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6380 } catch (RemoteException e) {
6386 private boolean isCallerWithSystemUid() {
6387 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6390 private int getProfileParentId(int userHandle) {
6391 final long ident = mInjector.binderClearCallingIdentity();
6393 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6394 return parentUser != null ? parentUser.id : userHandle;
6396 mInjector.binderRestoreCallingIdentity(ident);
6400 private int getCredentialOwner(int userHandle, boolean parent) {
6401 final long ident = mInjector.binderClearCallingIdentity();
6404 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6405 if (parentProfile != null) {
6406 userHandle = parentProfile.id;
6409 return mUserManager.getCredentialOwnerProfile(userHandle);
6411 mInjector.binderRestoreCallingIdentity(ident);
6415 private boolean isManagedProfile(int userHandle) {
6416 return getUserInfo(userHandle).isManagedProfile();
6419 private void enableIfNecessary(String packageName, int userId) {
6421 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6422 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6424 if (ai.enabledSetting
6425 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6426 mIPackageManager.setApplicationEnabledSetting(packageName,
6427 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6428 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6430 } catch (RemoteException e) {
6435 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6436 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6437 != PackageManager.PERMISSION_GRANTED) {
6439 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6440 + mInjector.binderGetCallingPid()
6441 + ", uid=" + mInjector.binderGetCallingUid());
6445 synchronized (this) {
6446 pw.println("Current Device Policy Manager state:");
6447 mOwners.dump(" ", pw);
6448 int userCount = mUserData.size();
6449 for (int u = 0; u < userCount; u++) {
6450 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6452 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6453 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6454 final int N = policy.mAdminList.size();
6455 for (int i=0; i<N; i++) {
6456 ActiveAdmin ap = policy.mAdminList.get(i);
6458 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6463 if (!policy.mRemovingAdmins.isEmpty()) {
6464 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6465 + policy.mRemovingAdmins);
6469 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6472 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6476 private String getEncryptionStatusName(int encryptionStatus) {
6477 switch (encryptionStatus) {
6478 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6480 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6481 return "block default key";
6482 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6484 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6486 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6487 return "unsupported";
6488 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6489 return "activating";
6496 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6497 ComponentName activity) {
6498 Preconditions.checkNotNull(who, "ComponentName is null");
6499 final int userHandle = UserHandle.getCallingUserId();
6500 synchronized (this) {
6501 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6503 long id = mInjector.binderClearCallingIdentity();
6505 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6506 } catch (RemoteException re) {
6509 mInjector.binderRestoreCallingIdentity(id);
6515 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6516 Preconditions.checkNotNull(who, "ComponentName is null");
6517 final int userHandle = UserHandle.getCallingUserId();
6518 synchronized (this) {
6519 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6521 long id = mInjector.binderClearCallingIdentity();
6523 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6524 } catch (RemoteException re) {
6527 mInjector.binderRestoreCallingIdentity(id);
6533 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6534 String packageName) {
6535 Preconditions.checkNotNull(admin, "ComponentName is null");
6537 final int userHandle = mInjector.userHandleGetCallingUserId();
6538 synchronized (this) {
6539 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6540 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6543 DevicePolicyData policy = getUserData(userHandle);
6544 policy.mApplicationRestrictionsManagingPackage = packageName;
6545 saveSettingsLocked(userHandle);
6551 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6552 Preconditions.checkNotNull(admin, "ComponentName is null");
6554 final int userHandle = mInjector.userHandleGetCallingUserId();
6555 synchronized (this) {
6556 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6557 DevicePolicyData policy = getUserData(userHandle);
6558 return policy.mApplicationRestrictionsManagingPackage;
6563 public boolean isCallerApplicationRestrictionsManagingPackage() {
6564 final int callingUid = mInjector.binderGetCallingUid();
6565 final int userHandle = UserHandle.getUserId(callingUid);
6566 synchronized (this) {
6567 final DevicePolicyData policy = getUserData(userHandle);
6568 if (policy.mApplicationRestrictionsManagingPackage == null) {
6573 int uid = mContext.getPackageManager().getPackageUidAsUser(
6574 policy.mApplicationRestrictionsManagingPackage, userHandle);
6575 return uid == callingUid;
6576 } catch (NameNotFoundException e) {
6582 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6584 synchronized (this) {
6585 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6587 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6588 throw new SecurityException(
6589 "No admin component given, and caller cannot manage application restrictions "
6590 + "for other apps.");
6595 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6596 enforceCanManageApplicationRestrictions(who);
6598 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6599 final long id = mInjector.binderClearCallingIdentity();
6601 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6603 mInjector.binderRestoreCallingIdentity(id);
6608 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6609 PersistableBundle args, boolean parent) {
6613 Preconditions.checkNotNull(admin, "admin is null");
6614 Preconditions.checkNotNull(agent, "agent is null");
6615 final int userHandle = UserHandle.getCallingUserId();
6616 synchronized (this) {
6617 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6618 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6619 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6620 saveSettingsLocked(userHandle);
6625 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6626 ComponentName agent, int userHandle, boolean parent) {
6630 Preconditions.checkNotNull(agent, "agent null");
6631 enforceFullCrossUsersPermission(userHandle);
6633 synchronized (this) {
6634 final String componentName = agent.flattenToString();
6635 if (admin != null) {
6636 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6637 if (ap == null) return null;
6638 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6639 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6640 List<PersistableBundle> result = new ArrayList<>();
6641 result.add(trustAgentInfo.options);
6645 // Return strictest policy for this user and profiles that are visible from this user.
6646 List<PersistableBundle> result = null;
6647 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6648 // of the options. If any admin doesn't have options, discard options for the rest
6650 List<ActiveAdmin> admins =
6651 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6652 boolean allAdminsHaveOptions = true;
6653 final int N = admins.size();
6654 for (int i = 0; i < N; i++) {
6655 final ActiveAdmin active = admins.get(i);
6657 final boolean disablesTrust = (active.disabledKeyguardFeatures
6658 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6659 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6660 if (info != null && info.options != null && !info.options.isEmpty()) {
6661 if (disablesTrust) {
6662 if (result == null) {
6663 result = new ArrayList<>();
6665 result.add(info.options);
6667 Log.w(LOG_TAG, "Ignoring admin " + active.info
6668 + " because it has trust options but doesn't declare "
6669 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6671 } else if (disablesTrust) {
6672 allAdminsHaveOptions = false;
6676 return allAdminsHaveOptions ? result : null;
6681 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6682 Preconditions.checkNotNull(who, "ComponentName is null");
6683 synchronized (this) {
6684 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6686 int userHandle = UserHandle.getCallingUserId();
6687 DevicePolicyData userData = getUserData(userHandle);
6688 userData.mRestrictionsProvider = permissionProvider;
6689 saveSettingsLocked(userHandle);
6694 public ComponentName getRestrictionsProvider(int userHandle) {
6695 synchronized (this) {
6696 if (!isCallerWithSystemUid()) {
6697 throw new SecurityException("Only the system can query the permission provider");
6699 DevicePolicyData userData = getUserData(userHandle);
6700 return userData != null ? userData.mRestrictionsProvider : null;
6705 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6706 Preconditions.checkNotNull(who, "ComponentName is null");
6707 int callingUserId = UserHandle.getCallingUserId();
6708 synchronized (this) {
6709 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6711 long id = mInjector.binderClearCallingIdentity();
6713 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6714 if (parent == null) {
6715 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6719 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6720 mIPackageManager.addCrossProfileIntentFilter(
6721 filter, who.getPackageName(), callingUserId, parent.id, 0);
6723 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6724 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6725 parent.id, callingUserId, 0);
6727 } catch (RemoteException re) {
6730 mInjector.binderRestoreCallingIdentity(id);
6736 public void clearCrossProfileIntentFilters(ComponentName who) {
6737 Preconditions.checkNotNull(who, "ComponentName is null");
6738 int callingUserId = UserHandle.getCallingUserId();
6739 synchronized (this) {
6740 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6741 long id = mInjector.binderClearCallingIdentity();
6743 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6744 if (parent == null) {
6745 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6749 // Removing those that go from the managed profile to the parent.
6750 mIPackageManager.clearCrossProfileIntentFilters(
6751 callingUserId, who.getPackageName());
6752 // And those that go from the parent to the managed profile.
6753 // If we want to support multiple managed profiles, we will have to only remove
6754 // those that have callingUserId as their target.
6755 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6756 } catch (RemoteException re) {
6759 mInjector.binderRestoreCallingIdentity(id);
6765 * @return true if all packages in enabledPackages are either in the list
6766 * permittedList or are a system app.
6768 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6769 List<String> permittedList, int userIdToCheck) {
6770 long id = mInjector.binderClearCallingIdentity();
6772 // If we have an enabled packages list for a managed profile the packages
6773 // we should check are installed for the parent user.
6774 UserInfo user = getUserInfo(userIdToCheck);
6775 if (user.isManagedProfile()) {
6776 userIdToCheck = user.profileGroupId;
6779 for (String enabledPackage : enabledPackages) {
6780 boolean systemService = false;
6782 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
6783 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
6784 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6785 } catch (RemoteException e) {
6786 Log.i(LOG_TAG, "Can't talk to package managed", e);
6788 if (!systemService && !permittedList.contains(enabledPackage)) {
6793 mInjector.binderRestoreCallingIdentity(id);
6798 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
6799 // Not using AccessibilityManager.getInstance because that guesses
6800 // at the user you require based on callingUid and caches for a given
6802 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
6803 IAccessibilityManager service = iBinder == null
6804 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
6805 return new AccessibilityManager(mContext, service, userId);
6809 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
6813 Preconditions.checkNotNull(who, "ComponentName is null");
6815 if (packageList != null) {
6816 int userId = UserHandle.getCallingUserId();
6817 List<AccessibilityServiceInfo> enabledServices = null;
6818 long id = mInjector.binderClearCallingIdentity();
6820 UserInfo user = getUserInfo(userId);
6821 if (user.isManagedProfile()) {
6822 userId = user.profileGroupId;
6824 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
6825 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
6826 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
6828 mInjector.binderRestoreCallingIdentity(id);
6831 if (enabledServices != null) {
6832 List<String> enabledPackages = new ArrayList<String>();
6833 for (AccessibilityServiceInfo service : enabledServices) {
6834 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
6836 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6838 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
6839 + "because it contains already enabled accesibility services.");
6845 synchronized (this) {
6846 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6847 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6848 admin.permittedAccessiblityServices = packageList;
6849 saveSettingsLocked(UserHandle.getCallingUserId());
6855 public List getPermittedAccessibilityServices(ComponentName who) {
6859 Preconditions.checkNotNull(who, "ComponentName is null");
6861 synchronized (this) {
6862 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6863 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6864 return admin.permittedAccessiblityServices;
6869 public List getPermittedAccessibilityServicesForUser(int userId) {
6873 synchronized (this) {
6874 List<String> result = null;
6875 // If we have multiple profiles we return the intersection of the
6876 // permitted lists. This can happen in cases where we have a device
6877 // and profile owner.
6878 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
6879 for (int profileId : profileIds) {
6880 // Just loop though all admins, only device or profiles
6881 // owners can have permitted lists set.
6882 DevicePolicyData policy = getUserDataUnchecked(profileId);
6883 final int N = policy.mAdminList.size();
6884 for (int j = 0; j < N; j++) {
6885 ActiveAdmin admin = policy.mAdminList.get(j);
6886 List<String> fromAdmin = admin.permittedAccessiblityServices;
6887 if (fromAdmin != null) {
6888 if (result == null) {
6889 result = new ArrayList<>(fromAdmin);
6891 result.retainAll(fromAdmin);
6897 // If we have a permitted list add all system accessibility services.
6898 if (result != null) {
6899 long id = mInjector.binderClearCallingIdentity();
6901 UserInfo user = getUserInfo(userId);
6902 if (user.isManagedProfile()) {
6903 userId = user.profileGroupId;
6905 AccessibilityManager accessibilityManager =
6906 getAccessibilityManagerForUser(userId);
6907 List<AccessibilityServiceInfo> installedServices =
6908 accessibilityManager.getInstalledAccessibilityServiceList();
6910 if (installedServices != null) {
6911 for (AccessibilityServiceInfo service : installedServices) {
6912 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
6913 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
6914 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6915 result.add(serviceInfo.packageName);
6920 mInjector.binderRestoreCallingIdentity(id);
6929 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
6934 Preconditions.checkNotNull(who, "ComponentName is null");
6935 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
6936 if (!isCallerWithSystemUid()){
6937 throw new SecurityException(
6938 "Only the system can query if an accessibility service is disabled by admin");
6940 synchronized (this) {
6941 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6942 if (admin == null) {
6945 if (admin.permittedAccessiblityServices == null) {
6948 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
6949 admin.permittedAccessiblityServices, userHandle);
6953 private boolean checkCallerIsCurrentUserOrProfile() {
6954 int callingUserId = UserHandle.getCallingUserId();
6955 long token = mInjector.binderClearCallingIdentity();
6957 UserInfo currentUser;
6958 UserInfo callingUser = getUserInfo(callingUserId);
6960 currentUser = mInjector.getIActivityManager().getCurrentUser();
6961 } catch (RemoteException e) {
6962 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
6966 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
6967 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
6968 + "of a user that isn't the foreground user.");
6971 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
6972 Slog.e(LOG_TAG, "Cannot set permitted input methods "
6973 + "of a user that isn't the foreground user.");
6977 mInjector.binderRestoreCallingIdentity(token);
6983 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
6987 Preconditions.checkNotNull(who, "ComponentName is null");
6989 // TODO When InputMethodManager supports per user calls remove
6990 // this restriction.
6991 if (!checkCallerIsCurrentUserOrProfile()) {
6995 if (packageList != null) {
6996 // InputMethodManager fetches input methods for current user.
6997 // So this can only be set when calling user is the current user
6998 // or parent is current user in case of managed profiles.
6999 InputMethodManager inputMethodManager =
7000 mContext.getSystemService(InputMethodManager.class);
7001 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7003 if (enabledImes != null) {
7004 List<String> enabledPackages = new ArrayList<String>();
7005 for (InputMethodInfo ime : enabledImes) {
7006 enabledPackages.add(ime.getPackageName());
7008 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7009 mInjector.binderGetCallingUserHandle().getIdentifier())) {
7010 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7011 + "because it contains already enabled input method.");
7017 synchronized (this) {
7018 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7019 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7020 admin.permittedInputMethods = packageList;
7021 saveSettingsLocked(UserHandle.getCallingUserId());
7027 public List getPermittedInputMethods(ComponentName who) {
7031 Preconditions.checkNotNull(who, "ComponentName is null");
7033 synchronized (this) {
7034 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7035 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7036 return admin.permittedInputMethods;
7041 public List getPermittedInputMethodsForCurrentUser() {
7042 UserInfo currentUser;
7044 currentUser = mInjector.getIActivityManager().getCurrentUser();
7045 } catch (RemoteException e) {
7046 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7047 // Activity managed is dead, just allow all IMEs
7051 int userId = currentUser.id;
7052 synchronized (this) {
7053 List<String> result = null;
7054 // If we have multiple profiles we return the intersection of the
7055 // permitted lists. This can happen in cases where we have a device
7056 // and profile owner.
7057 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7058 for (int profileId : profileIds) {
7059 // Just loop though all admins, only device or profiles
7060 // owners can have permitted lists set.
7061 DevicePolicyData policy = getUserDataUnchecked(profileId);
7062 final int N = policy.mAdminList.size();
7063 for (int j = 0; j < N; j++) {
7064 ActiveAdmin admin = policy.mAdminList.get(j);
7065 List<String> fromAdmin = admin.permittedInputMethods;
7066 if (fromAdmin != null) {
7067 if (result == null) {
7068 result = new ArrayList<String>(fromAdmin);
7070 result.retainAll(fromAdmin);
7076 // If we have a permitted list add all system input methods.
7077 if (result != null) {
7078 InputMethodManager inputMethodManager =
7079 mContext.getSystemService(InputMethodManager.class);
7080 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7081 long id = mInjector.binderClearCallingIdentity();
7084 for (InputMethodInfo ime : imes) {
7085 ServiceInfo serviceInfo = ime.getServiceInfo();
7086 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7087 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7088 result.add(serviceInfo.packageName);
7093 mInjector.binderRestoreCallingIdentity(id);
7101 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7106 Preconditions.checkNotNull(who, "ComponentName is null");
7107 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7108 if (!isCallerWithSystemUid()) {
7109 throw new SecurityException(
7110 "Only the system can query if an input method is disabled by admin");
7112 synchronized (this) {
7113 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7114 if (admin == null) {
7117 if (admin.permittedInputMethods == null) {
7120 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7121 admin.permittedInputMethods, userHandle);
7125 private void sendAdminEnabledBroadcastLocked(int userHandle) {
7126 DevicePolicyData policyData = getUserData(userHandle);
7127 if (policyData.mAdminBroadcastPending) {
7128 // Send the initialization data to profile owner and delete the data
7129 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7130 if (admin != null) {
7131 PersistableBundle initBundle = policyData.mInitBundle;
7132 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7133 initBundle == null ? null : new Bundle(initBundle), null);
7135 policyData.mInitBundle = null;
7136 policyData.mAdminBroadcastPending = false;
7137 saveSettingsLocked(userHandle);
7142 public UserHandle createAndManageUser(ComponentName admin, String name,
7143 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7144 Preconditions.checkNotNull(admin, "admin is null");
7145 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7146 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7147 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7148 + admin + " are not in the same package");
7150 // Only allow the system user to use this method
7151 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7152 throw new SecurityException("createAndManageUser was called from non-system user");
7154 if (!mInjector.userManagerIsSplitSystemUser()
7155 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7156 throw new IllegalArgumentException(
7157 "Ephemeral users are only supported on systems with a split system user.");
7160 UserHandle user = null;
7161 synchronized (this) {
7162 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7164 final long id = mInjector.binderClearCallingIdentity();
7166 int userInfoFlags = 0;
7167 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7168 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7170 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7172 if (userInfo != null) {
7173 user = userInfo.getUserHandle();
7176 mInjector.binderRestoreCallingIdentity(id);
7183 final long id = mInjector.binderClearCallingIdentity();
7185 final String adminPkg = admin.getPackageName();
7187 final int userHandle = user.getIdentifier();
7189 // Install the profile owner if not present.
7190 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7191 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7193 } catch (RemoteException e) {
7194 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7195 + "removing created user", e);
7196 mUserManager.removeUser(user.getIdentifier());
7200 setActiveAdmin(profileOwner, true, userHandle);
7201 // User is not started yet, the broadcast by setActiveAdmin will not be received.
7202 // So we store adminExtras for broadcasting when the user starts for first time.
7203 synchronized(this) {
7204 DevicePolicyData policyData = getUserData(userHandle);
7205 policyData.mInitBundle = adminExtras;
7206 policyData.mAdminBroadcastPending = true;
7207 saveSettingsLocked(userHandle);
7209 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7210 setProfileOwner(profileOwner, ownerName, userHandle);
7212 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7213 Settings.Secure.putIntForUser(mContext.getContentResolver(),
7214 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7219 mInjector.binderRestoreCallingIdentity(id);
7224 public boolean removeUser(ComponentName who, UserHandle userHandle) {
7225 Preconditions.checkNotNull(who, "ComponentName is null");
7226 synchronized (this) {
7227 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7229 long id = mInjector.binderClearCallingIdentity();
7231 return mUserManager.removeUser(userHandle.getIdentifier());
7233 mInjector.binderRestoreCallingIdentity(id);
7239 public boolean switchUser(ComponentName who, UserHandle userHandle) {
7240 Preconditions.checkNotNull(who, "ComponentName is null");
7241 synchronized (this) {
7242 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7244 long id = mInjector.binderClearCallingIdentity();
7246 int userId = UserHandle.USER_SYSTEM;
7247 if (userHandle != null) {
7248 userId = userHandle.getIdentifier();
7250 return mInjector.getIActivityManager().switchUser(userId);
7251 } catch (RemoteException e) {
7252 Log.e(LOG_TAG, "Couldn't switch user", e);
7255 mInjector.binderRestoreCallingIdentity(id);
7261 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7262 enforceCanManageApplicationRestrictions(who);
7264 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7265 final long id = mInjector.binderClearCallingIdentity();
7267 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7268 // if no restrictions were saved, mUserManager.getApplicationRestrictions
7269 // returns null, but DPM method should return an empty Bundle as per JavaDoc
7270 return bundle != null ? bundle : Bundle.EMPTY;
7272 mInjector.binderRestoreCallingIdentity(id);
7277 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7278 boolean suspended) {
7279 Preconditions.checkNotNull(who, "ComponentName is null");
7280 int callingUserId = UserHandle.getCallingUserId();
7281 synchronized (this) {
7282 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7284 long id = mInjector.binderClearCallingIdentity();
7286 return mIPackageManager.setPackagesSuspendedAsUser(
7287 packageNames, suspended, callingUserId);
7288 } catch (RemoteException re) {
7289 // Shouldn't happen.
7290 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7292 mInjector.binderRestoreCallingIdentity(id);
7294 return packageNames;
7299 public boolean isPackageSuspended(ComponentName who, String packageName) {
7300 Preconditions.checkNotNull(who, "ComponentName is null");
7301 int callingUserId = UserHandle.getCallingUserId();
7302 synchronized (this) {
7303 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7305 long id = mInjector.binderClearCallingIdentity();
7307 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7308 } catch (RemoteException re) {
7309 // Shouldn't happen.
7310 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7312 mInjector.binderRestoreCallingIdentity(id);
7319 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7320 Preconditions.checkNotNull(who, "ComponentName is null");
7321 if (!UserRestrictionsUtils.isValidRestriction(key)) {
7325 final int userHandle = mInjector.userHandleGetCallingUserId();
7326 synchronized (this) {
7327 ActiveAdmin activeAdmin =
7328 getActiveAdminForCallerLocked(who,
7329 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7330 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7331 if (isDeviceOwner) {
7332 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7333 throw new SecurityException("Device owner cannot set user restriction " + key);
7335 } else { // profile owner
7336 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7337 throw new SecurityException("Profile owner cannot set user restriction " + key);
7341 // Save the restriction to ActiveAdmin.
7342 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7343 saveSettingsLocked(userHandle);
7345 pushUserRestrictions(userHandle);
7347 sendChangedNotification(userHandle);
7351 private void pushUserRestrictions(int userId) {
7352 synchronized (this) {
7353 final Bundle global;
7354 final Bundle local = new Bundle();
7355 if (mOwners.isDeviceOwnerUserId(userId)) {
7356 global = new Bundle();
7358 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7359 if (deviceOwner == null) {
7360 return; // Shouldn't happen.
7363 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7365 // DO can disable camera globally.
7366 if (deviceOwner.disableCamera) {
7367 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7372 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7373 if (profileOwner != null) {
7374 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7377 // Also merge in *local* camera restriction.
7378 if (getCameraDisabled(/* who= */ null,
7379 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7380 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7382 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7387 public Bundle getUserRestrictions(ComponentName who) {
7391 Preconditions.checkNotNull(who, "ComponentName is null");
7392 synchronized (this) {
7393 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7394 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7395 return activeAdmin.userRestrictions;
7400 public boolean setApplicationHidden(ComponentName who, String packageName,
7402 Preconditions.checkNotNull(who, "ComponentName is null");
7403 int callingUserId = UserHandle.getCallingUserId();
7404 synchronized (this) {
7405 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7407 long id = mInjector.binderClearCallingIdentity();
7409 return mIPackageManager.setApplicationHiddenSettingAsUser(
7410 packageName, hidden, callingUserId);
7411 } catch (RemoteException re) {
7413 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7415 mInjector.binderRestoreCallingIdentity(id);
7422 public boolean isApplicationHidden(ComponentName who, String packageName) {
7423 Preconditions.checkNotNull(who, "ComponentName is null");
7424 int callingUserId = UserHandle.getCallingUserId();
7425 synchronized (this) {
7426 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7428 long id = mInjector.binderClearCallingIdentity();
7430 return mIPackageManager.getApplicationHiddenSettingAsUser(
7431 packageName, callingUserId);
7432 } catch (RemoteException re) {
7434 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7436 mInjector.binderRestoreCallingIdentity(id);
7443 public void enableSystemApp(ComponentName who, String packageName) {
7444 Preconditions.checkNotNull(who, "ComponentName is null");
7445 synchronized (this) {
7446 // This API can only be called by an active device admin,
7447 // so try to retrieve it to check that the caller is one.
7448 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7450 int userId = UserHandle.getCallingUserId();
7451 long id = mInjector.binderClearCallingIdentity();
7455 Slog.v(LOG_TAG, "installing " + packageName + " for "
7459 int parentUserId = getProfileParentId(userId);
7460 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7461 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7465 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7467 } catch (RemoteException re) {
7469 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7471 mInjector.binderRestoreCallingIdentity(id);
7477 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7478 Preconditions.checkNotNull(who, "ComponentName is null");
7479 synchronized (this) {
7480 // This API can only be called by an active device admin,
7481 // so try to retrieve it to check that the caller is one.
7482 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7484 int userId = UserHandle.getCallingUserId();
7485 long id = mInjector.binderClearCallingIdentity();
7488 int parentUserId = getProfileParentId(userId);
7489 List<ResolveInfo> activitiesToEnable = mIPackageManager
7490 .queryIntentActivities(intent,
7491 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7492 PackageManager.MATCH_DIRECT_BOOT_AWARE
7493 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7498 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7500 int numberOfAppsInstalled = 0;
7501 if (activitiesToEnable != null) {
7502 for (ResolveInfo info : activitiesToEnable) {
7503 if (info.activityInfo != null) {
7504 String packageName = info.activityInfo.packageName;
7505 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7506 numberOfAppsInstalled++;
7507 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7509 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7515 return numberOfAppsInstalled;
7516 } catch (RemoteException e) {
7518 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7521 mInjector.binderRestoreCallingIdentity(id);
7526 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7527 throws RemoteException {
7528 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7530 if (appInfo == null) {
7531 throw new IllegalArgumentException("The application " + packageName +
7532 " is not present on this device");
7534 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7538 public void setAccountManagementDisabled(ComponentName who, String accountType,
7543 Preconditions.checkNotNull(who, "ComponentName is null");
7544 synchronized (this) {
7545 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7546 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7548 ap.accountTypesWithManagementDisabled.add(accountType);
7550 ap.accountTypesWithManagementDisabled.remove(accountType);
7552 saveSettingsLocked(UserHandle.getCallingUserId());
7557 public String[] getAccountTypesWithManagementDisabled() {
7558 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7562 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7563 enforceFullCrossUsersPermission(userId);
7567 synchronized (this) {
7568 DevicePolicyData policy = getUserData(userId);
7569 final int N = policy.mAdminList.size();
7570 ArraySet<String> resultSet = new ArraySet<>();
7571 for (int i = 0; i < N; i++) {
7572 ActiveAdmin admin = policy.mAdminList.get(i);
7573 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7575 return resultSet.toArray(new String[resultSet.size()]);
7580 public void setUninstallBlocked(ComponentName who, String packageName,
7581 boolean uninstallBlocked) {
7582 Preconditions.checkNotNull(who, "ComponentName is null");
7583 final int userId = UserHandle.getCallingUserId();
7584 synchronized (this) {
7585 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7587 long id = mInjector.binderClearCallingIdentity();
7589 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7590 } catch (RemoteException re) {
7591 // Shouldn't happen.
7592 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7594 mInjector.binderRestoreCallingIdentity(id);
7600 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7601 // This function should return true if and only if the package is blocked by
7602 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7603 // when the package is a system app, or when it is an active device admin.
7604 final int userId = UserHandle.getCallingUserId();
7606 synchronized (this) {
7608 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7611 long id = mInjector.binderClearCallingIdentity();
7613 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7614 } catch (RemoteException re) {
7615 // Shouldn't happen.
7616 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7618 mInjector.binderRestoreCallingIdentity(id);
7625 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7629 Preconditions.checkNotNull(who, "ComponentName is null");
7630 synchronized (this) {
7631 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7632 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7633 if (admin.disableCallerId != disabled) {
7634 admin.disableCallerId = disabled;
7635 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7641 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7645 Preconditions.checkNotNull(who, "ComponentName is null");
7646 synchronized (this) {
7647 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7648 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7649 return admin.disableCallerId;
7654 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7655 enforceCrossUsersPermission(userId);
7656 synchronized (this) {
7657 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7658 return (admin != null) ? admin.disableCallerId : false;
7663 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7667 Preconditions.checkNotNull(who, "ComponentName is null");
7668 synchronized (this) {
7669 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7670 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7671 if (admin.disableContactsSearch != disabled) {
7672 admin.disableContactsSearch = disabled;
7673 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7679 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7683 Preconditions.checkNotNull(who, "ComponentName is null");
7684 synchronized (this) {
7685 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7686 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7687 return admin.disableContactsSearch;
7692 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7693 enforceCrossUsersPermission(userId);
7694 synchronized (this) {
7695 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7696 return (admin != null) ? admin.disableContactsSearch : false;
7701 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7702 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7703 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7704 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7705 final int callingUserId = UserHandle.getCallingUserId();
7707 final long ident = mInjector.binderClearCallingIdentity();
7709 synchronized (this) {
7710 final int managedUserId = getManagedUserId(callingUserId);
7711 if (managedUserId < 0) {
7714 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7717 "Cross-profile contacts access disabled for user " + managedUserId);
7721 ContactsInternal.startQuickContactWithErrorToastForUser(
7722 mContext, intent, new UserHandle(managedUserId));
7725 mInjector.binderRestoreCallingIdentity(ident);
7730 * @return true if cross-profile QuickContact is disabled
7732 private boolean isCrossProfileQuickContactDisabled(int userId) {
7733 return getCrossProfileCallerIdDisabledForUser(userId)
7734 && getCrossProfileContactsSearchDisabledForUser(userId);
7738 * @return the user ID of the managed user that is linked to the current user, if any.
7741 public int getManagedUserId(int callingUserId) {
7743 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7746 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7747 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7748 continue; // Caller user self, or not a managed profile. Skip.
7751 Log.v(LOG_TAG, "Managed user=" + ui.id);
7756 Log.v(LOG_TAG, "Managed user not found.");
7762 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7766 Preconditions.checkNotNull(who, "ComponentName is null");
7767 synchronized (this) {
7768 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7769 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7770 if (admin.disableBluetoothContactSharing != disabled) {
7771 admin.disableBluetoothContactSharing = disabled;
7772 saveSettingsLocked(UserHandle.getCallingUserId());
7778 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
7782 Preconditions.checkNotNull(who, "ComponentName is null");
7783 synchronized (this) {
7784 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7785 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7786 return admin.disableBluetoothContactSharing;
7791 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
7792 // TODO: Should there be a check to make sure this relationship is
7793 // within a profile group?
7794 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
7795 synchronized (this) {
7796 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7797 return (admin != null) ? admin.disableBluetoothContactSharing : false;
7802 * Sets which packages may enter lock task mode.
7804 * <p>This function can only be called by the device owner or alternatively by the profile owner
7805 * in case the user is affiliated.
7807 * @param packages The list of packages allowed to enter lock task mode.
7810 public void setLockTaskPackages(ComponentName who, String[] packages)
7811 throws SecurityException {
7812 Preconditions.checkNotNull(who, "ComponentName is null");
7813 synchronized (this) {
7814 ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
7815 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
7816 ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
7817 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
7818 if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
7819 int userHandle = mInjector.userHandleGetCallingUserId();
7820 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
7822 throw new SecurityException("Admin " + who +
7823 " is neither the device owner or affiliated user's profile owner.");
7828 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
7829 DevicePolicyData policy = getUserData(userHandle);
7830 policy.mLockTaskPackages = packages;
7832 // Store the settings persistently.
7833 saveSettingsLocked(userHandle);
7834 updateLockTaskPackagesLocked(packages, userHandle);
7838 * This function returns the list of components allowed to start the task lock mode.
7841 public String[] getLockTaskPackages(ComponentName who) {
7842 Preconditions.checkNotNull(who, "ComponentName is null");
7843 synchronized (this) {
7844 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7845 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
7846 final List<String> packages = getLockTaskPackagesLocked(userHandle);
7847 return packages.toArray(new String[packages.size()]);
7851 private List<String> getLockTaskPackagesLocked(int userHandle) {
7852 final DevicePolicyData policy = getUserData(userHandle);
7853 return policy.mLockTaskPackages;
7857 * This function lets the caller know whether the given package is allowed to start the
7859 * @param pkg The package to check
7862 public boolean isLockTaskPermitted(String pkg) {
7863 // Get current user's devicepolicy
7864 int uid = mInjector.binderGetCallingUid();
7865 int userHandle = UserHandle.getUserId(uid);
7866 DevicePolicyData policy = getUserData(userHandle);
7867 synchronized (this) {
7868 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
7869 String lockTaskPackage = policy.mLockTaskPackages.get(i);
7871 // If the given package equals one of the packages stored our list,
7872 // we allow this package to start lock task mode.
7873 if (lockTaskPackage.equals(pkg)) {
7882 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
7883 if (!isCallerWithSystemUid()) {
7884 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
7886 synchronized (this) {
7887 final DevicePolicyData policy = getUserData(userHandle);
7888 Bundle adminExtras = new Bundle();
7889 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
7890 for (ActiveAdmin admin : policy.mAdminList) {
7891 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
7892 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
7893 if (ownsDevice || ownsProfile) {
7895 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
7898 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
7906 public void setGlobalSetting(ComponentName who, String setting, String value) {
7907 Preconditions.checkNotNull(who, "ComponentName is null");
7909 synchronized (this) {
7910 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7912 // Some settings are no supported any more. However we do not want to throw a
7913 // SecurityException to avoid breaking apps.
7914 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
7915 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
7919 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
7920 throw new SecurityException(String.format(
7921 "Permission denial: device owners cannot update %1$s", setting));
7924 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
7925 // ignore if it contradicts an existing policy
7926 long timeMs = getMaximumTimeToLock(
7927 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
7928 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
7933 long id = mInjector.binderClearCallingIdentity();
7935 mInjector.settingsGlobalPutString(setting, value);
7937 mInjector.binderRestoreCallingIdentity(id);
7943 public void setSecureSetting(ComponentName who, String setting, String value) {
7944 Preconditions.checkNotNull(who, "ComponentName is null");
7945 int callingUserId = mInjector.userHandleGetCallingUserId();
7947 synchronized (this) {
7948 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7950 if (isDeviceOwner(who, callingUserId)) {
7951 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
7952 throw new SecurityException(String.format(
7953 "Permission denial: Device owners cannot update %1$s", setting));
7955 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
7956 throw new SecurityException(String.format(
7957 "Permission denial: Profile owners cannot update %1$s", setting));
7960 long id = mInjector.binderClearCallingIdentity();
7962 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
7964 mInjector.binderRestoreCallingIdentity(id);
7970 public void setMasterVolumeMuted(ComponentName who, boolean on) {
7971 Preconditions.checkNotNull(who, "ComponentName is null");
7972 synchronized (this) {
7973 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7974 setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
7979 public boolean isMasterVolumeMuted(ComponentName who) {
7980 Preconditions.checkNotNull(who, "ComponentName is null");
7981 synchronized (this) {
7982 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7984 AudioManager audioManager =
7985 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
7986 return audioManager.isMasterMute();
7991 public void setUserIcon(ComponentName who, Bitmap icon) {
7992 synchronized (this) {
7993 Preconditions.checkNotNull(who, "ComponentName is null");
7994 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7996 int userId = UserHandle.getCallingUserId();
7997 long id = mInjector.binderClearCallingIdentity();
7999 mUserManagerInternal.setUserIcon(userId, icon);
8001 mInjector.binderRestoreCallingIdentity(id);
8007 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8008 Preconditions.checkNotNull(who, "ComponentName is null");
8009 synchronized (this) {
8010 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8012 final int userId = UserHandle.getCallingUserId();
8014 long ident = mInjector.binderClearCallingIdentity();
8016 // disallow disabling the keyguard if a password is currently set
8017 if (disabled && mLockPatternUtils.isSecure(userId)) {
8020 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8022 mInjector.binderRestoreCallingIdentity(ident);
8028 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8029 int userId = UserHandle.getCallingUserId();
8030 synchronized (this) {
8031 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8032 DevicePolicyData policy = getUserData(userId);
8033 if (policy.mStatusBarDisabled != disabled) {
8034 if (!setStatusBarDisabledInternal(disabled, userId)) {
8037 policy.mStatusBarDisabled = disabled;
8038 saveSettingsLocked(userId);
8044 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8045 long ident = mInjector.binderClearCallingIdentity();
8047 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8048 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8049 if (statusBarService != null) {
8050 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8051 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8052 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8053 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8056 } catch (RemoteException e) {
8057 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8059 mInjector.binderRestoreCallingIdentity(ident);
8065 * We need to update the internal state of whether a user has completed setup once. After
8066 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
8067 * as we don't trust any apps that might try to reset it.
8069 * Unfortunately, we don't know which user's setup state was changed, so we write all of
8072 void updateUserSetupComplete() {
8073 List<UserInfo> users = mUserManager.getUsers(true);
8074 final int N = users.size();
8075 for (int i = 0; i < N; i++) {
8076 int userHandle = users.get(i).id;
8077 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8079 DevicePolicyData policy = getUserData(userHandle);
8080 if (!policy.mUserSetupComplete) {
8081 policy.mUserSetupComplete = true;
8082 synchronized (this) {
8083 saveSettingsLocked(userHandle);
8090 private class SetupContentObserver extends ContentObserver {
8092 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8093 Settings.Secure.USER_SETUP_COMPLETE);
8094 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8095 Settings.Global.DEVICE_PROVISIONED);
8097 public SetupContentObserver(Handler handler) {
8102 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8103 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8107 public void onChange(boolean selfChange, Uri uri) {
8108 if (mUserSetupComplete.equals(uri)) {
8109 updateUserSetupComplete();
8110 } else if (mDeviceProvisioned.equals(uri)) {
8111 synchronized (DevicePolicyManagerService.this) {
8112 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8113 // is delayed until device is marked as provisioned.
8114 setDeviceOwnerSystemPropertyLocked();
8121 final class LocalService extends DevicePolicyManagerInternal {
8122 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8125 public List<String> getCrossProfileWidgetProviders(int profileId) {
8126 synchronized (DevicePolicyManagerService.this) {
8127 if (mOwners == null) {
8128 return Collections.emptyList();
8130 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8131 if (ownerComponent == null) {
8132 return Collections.emptyList();
8135 DevicePolicyData policy = getUserDataUnchecked(profileId);
8136 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8138 if (admin == null || admin.crossProfileWidgetProviders == null
8139 || admin.crossProfileWidgetProviders.isEmpty()) {
8140 return Collections.emptyList();
8143 return admin.crossProfileWidgetProviders;
8148 public void addOnCrossProfileWidgetProvidersChangeListener(
8149 OnCrossProfileWidgetProvidersChangeListener listener) {
8150 synchronized (DevicePolicyManagerService.this) {
8151 if (mWidgetProviderListeners == null) {
8152 mWidgetProviderListeners = new ArrayList<>();
8154 if (!mWidgetProviderListeners.contains(listener)) {
8155 mWidgetProviderListeners.add(listener);
8161 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8162 synchronized(DevicePolicyManagerService.this) {
8163 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8167 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8168 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8169 synchronized (DevicePolicyManagerService.this) {
8170 listeners = new ArrayList<>(mWidgetProviderListeners);
8172 final int listenerCount = listeners.size();
8173 for (int i = 0; i < listenerCount; i++) {
8174 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8175 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8180 public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
8181 Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8182 intent.putExtra(Intent.EXTRA_USER_ID, userId);
8183 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8185 // This method is called from AM with its lock held, so don't take the DPMS lock.
8188 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8189 if (profileOwner != null) {
8190 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
8194 final Pair<Integer, ComponentName> deviceOwner =
8195 mOwners.getDeviceOwnerUserIdAndComponent();
8196 if (deviceOwner != null && deviceOwner.first == userId) {
8197 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
8201 // We're not specifying the device admin because there isn't one.
8207 * Returns true if specified admin is allowed to limit passwords and has a
8208 * {@code passwordQuality} of at least {@code minPasswordQuality}
8210 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8211 if (admin.passwordQuality < minPasswordQuality) {
8214 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8218 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8219 if (policy != null && !policy.isValid()) {
8220 throw new IllegalArgumentException("Invalid system update policy.");
8222 synchronized (this) {
8223 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8224 if (policy == null) {
8225 mOwners.clearSystemUpdatePolicy();
8227 mOwners.setSystemUpdatePolicy(policy);
8229 mOwners.writeDeviceOwner();
8231 mContext.sendBroadcastAsUser(
8232 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8237 public SystemUpdatePolicy getSystemUpdatePolicy() {
8238 if (UserManager.isDeviceInDemoMode(mContext)) {
8239 // Pretending to have an automatic update policy when the device is in retail demo
8240 // mode. This will allow the device to download and install an ota without
8241 // any user interaction.
8242 return SystemUpdatePolicy.createAutomaticInstallPolicy();
8244 synchronized (this) {
8245 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
8246 if (policy != null && !policy.isValid()) {
8247 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8255 * Checks if the caller of the method is the device owner app.
8257 * @param callerUid UID of the caller.
8258 * @return true if the caller is the device owner app
8261 boolean isCallerDeviceOwner(int callerUid) {
8262 synchronized (this) {
8263 if (!mOwners.hasDeviceOwner()) {
8266 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8269 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8271 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8273 for (String pkg : pkgs) {
8274 if (deviceOwnerPackageName.equals(pkg)) {
8284 public void notifyPendingSystemUpdate(long updateReceivedTime) {
8285 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8286 "Only the system update service can broadcast update information");
8288 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8289 Slog.w(LOG_TAG, "Only the system update service in the system user " +
8290 "can broadcast update information.");
8293 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8294 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8295 updateReceivedTime);
8297 synchronized (this) {
8298 final String deviceOwnerPackage =
8299 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8301 if (deviceOwnerPackage == null) {
8304 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8306 ActivityInfo[] receivers = null;
8308 receivers = mContext.getPackageManager().getPackageInfo(
8309 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8310 } catch (NameNotFoundException e) {
8311 Log.e(LOG_TAG, "Cannot find device owner package", e);
8313 if (receivers != null) {
8314 long ident = mInjector.binderClearCallingIdentity();
8316 for (int i = 0; i < receivers.length; i++) {
8317 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8318 intent.setComponent(new ComponentName(deviceOwnerPackage,
8319 receivers[i].name));
8320 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8324 mInjector.binderRestoreCallingIdentity(ident);
8331 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8332 int userId = UserHandle.getCallingUserId();
8333 synchronized (this) {
8334 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8335 DevicePolicyData userPolicy = getUserData(userId);
8336 if (userPolicy.mPermissionPolicy != policy) {
8337 userPolicy.mPermissionPolicy = policy;
8338 saveSettingsLocked(userId);
8344 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8345 int userId = UserHandle.getCallingUserId();
8346 synchronized (this) {
8347 DevicePolicyData userPolicy = getUserData(userId);
8348 return userPolicy.mPermissionPolicy;
8353 public boolean setPermissionGrantState(ComponentName admin, String packageName,
8354 String permission, int grantState) throws RemoteException {
8355 UserHandle user = mInjector.binderGetCallingUserHandle();
8356 synchronized (this) {
8357 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8358 long ident = mInjector.binderClearCallingIdentity();
8360 if (getTargetSdk(packageName, user.getIdentifier())
8361 < android.os.Build.VERSION_CODES.M) {
8364 final PackageManager packageManager = mContext.getPackageManager();
8365 switch (grantState) {
8366 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8367 packageManager.grantRuntimePermission(packageName, permission, user);
8368 packageManager.updatePermissionFlags(permission, packageName,
8369 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8370 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8373 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8374 packageManager.revokeRuntimePermission(packageName,
8376 packageManager.updatePermissionFlags(permission, packageName,
8377 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8378 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8381 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8382 packageManager.updatePermissionFlags(permission, packageName,
8383 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8387 } catch (SecurityException se) {
8390 mInjector.binderRestoreCallingIdentity(ident);
8396 public int getPermissionGrantState(ComponentName admin, String packageName,
8397 String permission) throws RemoteException {
8398 PackageManager packageManager = mContext.getPackageManager();
8400 UserHandle user = mInjector.binderGetCallingUserHandle();
8401 synchronized (this) {
8402 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8403 long ident = mInjector.binderClearCallingIdentity();
8405 int granted = mIPackageManager.checkPermission(permission,
8406 packageName, user.getIdentifier());
8407 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8408 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8409 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8410 // Not controlled by policy
8411 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8413 // Policy controlled so return result based on permission grant state
8414 return granted == PackageManager.PERMISSION_GRANTED
8415 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8416 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8419 mInjector.binderRestoreCallingIdentity(ident);
8424 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8426 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8428 return (pi != null) && (pi.applicationInfo.flags != 0);
8429 } catch (RemoteException re) {
8430 throw new RuntimeException("Package manager has died", re);
8435 public boolean isProvisioningAllowed(String action) {
8440 final int callingUserId = mInjector.userHandleGetCallingUserId();
8441 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8442 if (!hasFeatureManagedUsers()) {
8445 synchronized (this) {
8446 if (mOwners.hasDeviceOwner()) {
8447 if (!mInjector.userManagerIsSplitSystemUser()) {
8448 // Only split-system-user systems support managed-profiles in combination with
8452 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8453 // Only system device-owner supports managed-profiles. Non-system device-owner
8457 if (callingUserId == UserHandle.USER_SYSTEM) {
8458 // Managed-profiles cannot be setup on the system user, only regular users.
8463 if (getProfileOwner(callingUserId) != null) {
8464 // Managed user cannot have a managed profile.
8467 final long ident = mInjector.binderClearCallingIdentity();
8469 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8473 mInjector.binderRestoreCallingIdentity(ident);
8476 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8477 return isDeviceOwnerProvisioningAllowed(callingUserId);
8478 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8479 if (!hasFeatureManagedUsers()) {
8482 if (!mInjector.userManagerIsSplitSystemUser()) {
8483 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8486 if (callingUserId == UserHandle.USER_SYSTEM) {
8487 // System user cannot be a managed user.
8490 if (hasUserSetupCompleted(callingUserId)) {
8494 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8495 if (!mInjector.userManagerIsSplitSystemUser()) {
8496 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8499 return isDeviceOwnerProvisioningAllowed(callingUserId);
8501 throw new IllegalArgumentException("Unknown provisioning action " + action);
8505 * The device owner can only be set before the setup phase of the primary user has completed,
8506 * except for adb command if no accounts or additional users are present on the device.
8508 private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreCondition(
8509 int deviceOwnerUserId, boolean isAdb) {
8510 if (mOwners.hasDeviceOwner()) {
8511 return CODE_HAS_DEVICE_OWNER;
8513 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8514 return CODE_USER_HAS_PROFILE_OWNER;
8516 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8517 return CODE_USER_NOT_RUNNING;
8520 // if shell command runs after user setup completed check device status. Otherwise, OK.
8521 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8522 if (!mInjector.userManagerIsSplitSystemUser()) {
8523 if (mUserManager.getUserCount() > 1) {
8524 return CODE_NONSYSTEM_USER_EXISTS;
8526 if (AccountManager.get(mContext).getAccounts().length > 0) {
8527 return CODE_ACCOUNTS_NOT_EMPTY;
8530 // STOPSHIP Do proper check in split user mode
8535 if (!mInjector.userManagerIsSplitSystemUser()) {
8536 // In non-split user mode, DO has to be user 0
8537 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8538 return CODE_NOT_SYSTEM_USER;
8540 // In non-split user mode, only provision DO before setup wizard completes
8541 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8542 return CODE_USER_SETUP_COMPLETED;
8545 // STOPSHIP Do proper check in split user mode
8551 private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8552 return CODE_OK == checkSetDeviceOwnerPreCondition(deviceOwnerUserId, /* isAdb */ false);
8555 private boolean hasFeatureManagedUsers() {
8557 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8558 } catch (RemoteException e) {
8564 public String getWifiMacAddress(ComponentName admin) {
8565 // Make sure caller has DO.
8566 synchronized (this) {
8567 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8570 final long ident = mInjector.binderClearCallingIdentity();
8572 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8573 if (wifiInfo == null) {
8576 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8578 mInjector.binderRestoreCallingIdentity(ident);
8583 * Returns the target sdk version number that the given packageName was built for
8584 * in the given user.
8586 private int getTargetSdk(String packageName, int userId) {
8587 final ApplicationInfo ai;
8589 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8590 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8591 return targetSdkVersion;
8592 } catch (RemoteException e) {
8599 public boolean isManagedProfile(ComponentName admin) {
8600 synchronized (this) {
8601 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8603 final int callingUserId = mInjector.userHandleGetCallingUserId();
8604 final UserInfo user = getUserInfo(callingUserId);
8605 return user != null && user.isManagedProfile();
8609 public boolean isSystemOnlyUser(ComponentName admin) {
8610 synchronized (this) {
8611 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8613 final int callingUserId = mInjector.userHandleGetCallingUserId();
8614 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8618 public void reboot(ComponentName admin) {
8619 Preconditions.checkNotNull(admin);
8620 // Make sure caller has DO.
8621 synchronized (this) {
8622 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8624 long ident = mInjector.binderClearCallingIdentity();
8626 // Make sure there are no ongoing calls on the device.
8627 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8628 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8630 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8632 mInjector.binderRestoreCallingIdentity(ident);
8637 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8641 Preconditions.checkNotNull(who, "ComponentName is null");
8642 final int userHandle = mInjector.userHandleGetCallingUserId();
8643 synchronized (this) {
8644 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8645 mInjector.binderGetCallingUid());
8646 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8647 admin.shortSupportMessage = message;
8648 saveSettingsLocked(userHandle);
8654 public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8658 Preconditions.checkNotNull(who, "ComponentName is null");
8659 synchronized (this) {
8660 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8661 mInjector.binderGetCallingUid());
8662 return admin.shortSupportMessage;
8667 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8671 Preconditions.checkNotNull(who, "ComponentName is null");
8672 final int userHandle = mInjector.userHandleGetCallingUserId();
8673 synchronized (this) {
8674 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8675 mInjector.binderGetCallingUid());
8676 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8677 admin.longSupportMessage = message;
8678 saveSettingsLocked(userHandle);
8684 public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8688 Preconditions.checkNotNull(who, "ComponentName is null");
8689 synchronized (this) {
8690 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8691 mInjector.binderGetCallingUid());
8692 return admin.longSupportMessage;
8697 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8701 Preconditions.checkNotNull(who, "ComponentName is null");
8702 if (!isCallerWithSystemUid()) {
8703 throw new SecurityException("Only the system can query support message for user");
8705 synchronized (this) {
8706 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8707 if (admin != null) {
8708 return admin.shortSupportMessage;
8715 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8719 Preconditions.checkNotNull(who, "ComponentName is null");
8720 if (!isCallerWithSystemUid()) {
8721 throw new SecurityException("Only the system can query support message for user");
8723 synchronized (this) {
8724 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8725 if (admin != null) {
8726 return admin.longSupportMessage;
8733 public void setOrganizationColor(@NonNull ComponentName who, int color) {
8737 Preconditions.checkNotNull(who, "ComponentName is null");
8738 final int userHandle = mInjector.userHandleGetCallingUserId();
8739 enforceManagedProfile(userHandle, "set organization color");
8740 synchronized (this) {
8741 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8742 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8743 admin.organizationColor = color;
8744 saveSettingsLocked(userHandle);
8749 public void setOrganizationColorForUser(int color, int userId) {
8753 enforceFullCrossUsersPermission(userId);
8754 enforceManageUsers();
8755 enforceManagedProfile(userId, "set organization color");
8756 synchronized (this) {
8757 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8758 admin.organizationColor = color;
8759 saveSettingsLocked(userId);
8764 public int getOrganizationColor(@NonNull ComponentName who) {
8766 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8768 Preconditions.checkNotNull(who, "ComponentName is null");
8769 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
8770 synchronized (this) {
8771 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8772 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8773 return admin.organizationColor;
8778 public int getOrganizationColorForUser(int userHandle) {
8780 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8782 enforceFullCrossUsersPermission(userHandle);
8783 enforceManagedProfile(userHandle, "get organization color");
8784 synchronized (this) {
8785 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8786 return (profileOwner != null)
8787 ? profileOwner.organizationColor
8788 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
8793 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
8797 Preconditions.checkNotNull(who, "ComponentName is null");
8798 final int userHandle = mInjector.userHandleGetCallingUserId();
8799 enforceManagedProfile(userHandle, "set organization name");
8800 synchronized (this) {
8801 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8802 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8803 if (!TextUtils.equals(admin.organizationName, text)) {
8804 admin.organizationName = (text == null || text.length() == 0)
8805 ? null : text.toString();
8806 saveSettingsLocked(userHandle);
8812 public CharSequence getOrganizationName(@NonNull ComponentName who) {
8816 Preconditions.checkNotNull(who, "ComponentName is null");
8817 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
8818 synchronized(this) {
8819 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8820 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8821 return admin.organizationName;
8826 public CharSequence getOrganizationNameForUser(int userHandle) {
8830 enforceFullCrossUsersPermission(userHandle);
8831 enforceManagedProfile(userHandle, "get organization name");
8832 synchronized (this) {
8833 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8834 return (profileOwner != null)
8835 ? profileOwner.organizationName
8841 public void setAffiliationIds(ComponentName admin, List<String> ids) {
8842 final Set<String> affiliationIds = new ArraySet<String>(ids);
8843 final int callingUserId = mInjector.userHandleGetCallingUserId();
8845 synchronized (this) {
8846 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8847 getUserData(callingUserId).mAffiliationIds = affiliationIds;
8848 saveSettingsLocked(callingUserId);
8849 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
8850 // Affiliation ids specified by the device owner are additionally stored in
8851 // UserHandle.USER_SYSTEM's DevicePolicyData.
8852 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
8853 saveSettingsLocked(UserHandle.USER_SYSTEM);
8859 public boolean isAffiliatedUser() {
8860 final int callingUserId = mInjector.userHandleGetCallingUserId();
8862 synchronized (this) {
8863 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
8864 // The user that the DO is installed on is always affiliated.
8867 final ComponentName profileOwner = getProfileOwner(callingUserId);
8868 if (profileOwner == null
8869 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
8872 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
8873 final Set<String> deviceAffiliationIds =
8874 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
8875 for (String id : userAffiliationIds) {
8876 if (deviceAffiliationIds.contains(id)) {
8884 private synchronized void disableSecurityLoggingIfNotCompliant() {
8885 if (!isDeviceOwnerManagedSingleUserDevice()) {
8886 mInjector.securityLogSetLoggingEnabledProperty(false);
8887 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user device.");
8892 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
8893 Preconditions.checkNotNull(admin);
8894 ensureDeviceOwnerManagingSingleUser(admin);
8896 synchronized (this) {
8897 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
8900 mInjector.securityLogSetLoggingEnabledProperty(enabled);
8902 mSecurityLogMonitor.start();
8904 mSecurityLogMonitor.stop();
8910 public boolean isSecurityLoggingEnabled(ComponentName admin) {
8911 Preconditions.checkNotNull(admin);
8912 synchronized (this) {
8913 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8914 return mInjector.securityLogGetLoggingEnabledProperty();
8919 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
8920 Preconditions.checkNotNull(admin);
8921 ensureDeviceOwnerManagingSingleUser(admin);
8923 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
8927 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
8929 SecurityLog.readPreviousEvents(output);
8930 return new ParceledListSlice<SecurityEvent>(output);
8931 } catch (IOException e) {
8932 Slog.w(LOG_TAG, "Fail to read previous events" , e);
8933 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
8938 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
8939 Preconditions.checkNotNull(admin);
8940 ensureDeviceOwnerManagingSingleUser(admin);
8942 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
8943 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
8946 private void enforceCanManageDeviceAdmin() {
8947 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
8951 private void enforceCanManageProfileAndDeviceOwners() {
8952 mContext.enforceCallingOrSelfPermission(
8953 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
8957 public boolean isUninstallInQueue(final String packageName) {
8958 enforceCanManageDeviceAdmin();
8959 final int userId = mInjector.userHandleGetCallingUserId();
8960 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8961 synchronized (this) {
8962 return mPackagesToRemove.contains(packageUserPair);
8967 public void uninstallPackageWithActiveAdmins(final String packageName) {
8968 enforceCanManageDeviceAdmin();
8969 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
8971 final int userId = mInjector.userHandleGetCallingUserId();
8973 enforceUserUnlocked(userId);
8975 final ComponentName profileOwner = getProfileOwner(userId);
8976 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
8977 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
8980 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
8981 if (getDeviceOwnerUserId() == userId && deviceOwner != null
8982 && packageName.equals(deviceOwner.getPackageName())) {
8983 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
8986 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8987 synchronized (this) {
8988 mPackagesToRemove.add(packageUserPair);
8991 // All active admins on the user.
8992 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
8994 // Active admins in the target package.
8995 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
8996 if (allActiveAdmins != null) {
8997 for (ComponentName activeAdmin : allActiveAdmins) {
8998 if (packageName.equals(activeAdmin.getPackageName())) {
8999 packageActiveAdmins.add(activeAdmin);
9000 removeActiveAdmin(activeAdmin, userId);
9004 if (packageActiveAdmins.size() == 0) {
9005 startUninstallIntent(packageName, userId);
9007 mHandler.postDelayed(new Runnable() {
9010 for (ComponentName activeAdmin : packageActiveAdmins) {
9011 removeAdminArtifacts(activeAdmin, userId);
9013 startUninstallIntent(packageName, userId);
9015 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9020 public boolean isDeviceProvisioned() {
9021 return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9024 private void removePackageIfRequired(final String packageName, final int userId) {
9025 if (!packageHasActiveAdmins(packageName, userId)) {
9026 // Will not do anything if uninstall was not requested or was already started.
9027 startUninstallIntent(packageName, userId);
9031 private void startUninstallIntent(final String packageName, final int userId) {
9032 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9033 synchronized (this) {
9034 if (!mPackagesToRemove.contains(packageUserPair)) {
9035 // Do nothing if uninstall was not requested or was already started.
9038 mPackagesToRemove.remove(packageUserPair);
9041 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9042 // Package does not exist. Nothing to do.
9045 } catch (RemoteException re) {
9046 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9049 try { // force stop the package before uninstalling
9050 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9051 } catch (RemoteException re) {
9052 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9054 final Uri packageURI = Uri.parse("package:" + packageName);
9055 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9056 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9057 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9061 * Removes the admin from the policy. Ideally called after the admin's
9062 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9064 * @param adminReceiver The admin to remove
9065 * @param userHandle The user for which this admin has to be removed.
9067 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9068 synchronized (this) {
9069 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9070 if (admin == null) {
9073 final DevicePolicyData policy = getUserData(userHandle);
9074 final boolean doProxyCleanup = admin.info.usesPolicy(
9075 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9076 policy.mAdminList.remove(admin);
9077 policy.mAdminMap.remove(adminReceiver);
9078 validatePasswordOwnerLocked(policy);
9079 if (doProxyCleanup) {
9080 resetGlobalProxyLocked(policy);
9082 saveSettingsLocked(userHandle);
9083 updateMaximumTimeToLockLocked(userHandle);
9084 policy.mRemovingAdmins.remove(adminReceiver);
9086 // The removed admin might have disabled camera, so update user
9088 pushUserRestrictions(userHandle);
9092 public void setDeviceProvisioningConfigApplied() {
9093 enforceManageUsers();
9094 synchronized (this) {
9095 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9096 policy.mDeviceProvisioningConfigApplied = true;
9097 saveSettingsLocked(UserHandle.USER_SYSTEM);
9102 public boolean isDeviceProvisioningConfigApplied() {
9103 enforceManageUsers();
9104 synchronized (this) {
9105 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9106 return policy.mDeviceProvisioningConfigApplied;