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.ActivityManagerInternal;
40 import android.app.ActivityManagerNative;
41 import android.app.AlarmManager;
42 import android.app.AppGlobals;
43 import android.app.IActivityManager;
44 import android.app.Notification;
45 import android.app.NotificationManager;
46 import android.app.PendingIntent;
47 import android.app.StatusBarManager;
48 import android.app.admin.DeviceAdminInfo;
49 import android.app.admin.DeviceAdminReceiver;
50 import android.app.admin.DevicePolicyManager;
51 import android.app.admin.DevicePolicyManagerInternal;
52 import android.app.admin.IDevicePolicyManager;
53 import android.app.admin.SecurityLog;
54 import android.app.admin.SecurityLog.SecurityEvent;
55 import android.app.admin.SystemUpdatePolicy;
56 import android.app.backup.IBackupManager;
57 import android.app.trust.TrustManager;
58 import android.content.BroadcastReceiver;
59 import android.content.ComponentName;
60 import android.content.Context;
61 import android.content.Intent;
62 import android.content.IntentFilter;
63 import android.content.pm.ActivityInfo;
64 import android.content.pm.ApplicationInfo;
65 import android.content.pm.IPackageManager;
66 import android.content.pm.PackageInfo;
67 import android.content.pm.PackageManager;
68 import android.content.pm.PackageManager.NameNotFoundException;
69 import android.content.pm.PackageManagerInternal;
70 import android.content.pm.ParceledListSlice;
71 import android.content.pm.PermissionInfo;
72 import android.content.pm.ResolveInfo;
73 import android.content.pm.ServiceInfo;
74 import android.content.pm.UserInfo;
75 import android.database.ContentObserver;
76 import android.graphics.Bitmap;
77 import android.graphics.Color;
78 import android.media.AudioManager;
79 import android.media.IAudioService;
80 import android.net.ConnectivityManager;
81 import android.net.ProxyInfo;
82 import android.net.Uri;
83 import android.net.wifi.WifiInfo;
84 import android.net.wifi.WifiManager;
85 import android.os.AsyncTask;
86 import android.os.Binder;
87 import android.os.Build;
88 import android.os.Bundle;
89 import android.os.Environment;
90 import android.os.FileUtils;
91 import android.os.Handler;
92 import android.os.IBinder;
93 import android.os.Looper;
94 import android.os.ParcelFileDescriptor;
95 import android.os.PersistableBundle;
96 import android.os.PowerManager;
97 import android.os.PowerManagerInternal;
98 import android.os.Process;
99 import android.os.RecoverySystem;
100 import android.os.RemoteCallback;
101 import android.os.RemoteException;
102 import android.os.ServiceManager;
103 import android.os.SystemClock;
104 import android.os.SystemProperties;
105 import android.os.UserHandle;
106 import android.os.UserManager;
107 import android.os.UserManagerInternal;
108 import android.os.storage.StorageManager;
109 import android.provider.ContactsContract.QuickContact;
110 import android.provider.ContactsInternal;
111 import android.provider.Settings;
112 import android.security.Credentials;
113 import android.security.IKeyChainAliasCallback;
114 import android.security.IKeyChainService;
115 import android.security.KeyChain;
116 import android.security.KeyChain.KeyChainConnection;
117 import android.service.persistentdata.PersistentDataBlockManager;
118 import android.telephony.TelephonyManager;
119 import android.text.TextUtils;
120 import android.util.ArrayMap;
121 import android.util.ArraySet;
122 import android.util.EventLog;
123 import android.util.Log;
124 import android.util.Pair;
125 import android.util.Slog;
126 import android.util.SparseArray;
127 import android.util.Xml;
128 import android.view.IWindowManager;
129 import android.view.accessibility.AccessibilityManager;
130 import android.view.accessibility.IAccessibilityManager;
131 import android.view.inputmethod.InputMethodInfo;
132 import android.view.inputmethod.InputMethodManager;
134 import com.android.internal.R;
135 import com.android.internal.annotations.VisibleForTesting;
136 import com.android.internal.statusbar.IStatusBarService;
137 import com.android.internal.util.FastXmlSerializer;
138 import com.android.internal.util.JournaledFile;
139 import com.android.internal.util.ParcelableString;
140 import com.android.internal.util.Preconditions;
141 import com.android.internal.util.XmlUtils;
142 import com.android.internal.widget.LockPatternUtils;
143 import com.android.server.LocalServices;
144 import com.android.server.SystemService;
145 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
146 import com.android.server.pm.UserRestrictionsUtils;
147 import com.google.android.collect.Sets;
149 import org.xmlpull.v1.XmlPullParser;
150 import org.xmlpull.v1.XmlPullParserException;
151 import org.xmlpull.v1.XmlSerializer;
153 import java.io.ByteArrayInputStream;
155 import java.io.FileDescriptor;
156 import java.io.FileInputStream;
157 import java.io.FileNotFoundException;
158 import java.io.FileOutputStream;
159 import java.io.IOException;
160 import java.io.PrintWriter;
161 import java.lang.annotation.Retention;
162 import java.lang.annotation.RetentionPolicy;
163 import java.nio.charset.StandardCharsets;
164 import java.security.cert.CertificateException;
165 import java.security.cert.CertificateFactory;
166 import java.security.cert.X509Certificate;
167 import java.text.DateFormat;
168 import java.util.ArrayList;
169 import java.util.Arrays;
170 import java.util.Collections;
171 import java.util.Date;
172 import java.util.List;
173 import java.util.Map.Entry;
174 import java.util.Set;
175 import java.util.concurrent.atomic.AtomicBoolean;
178 * Implementation of the device policy APIs.
180 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
182 private static final String LOG_TAG = "DevicePolicyManagerService";
184 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
186 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
188 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
190 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
192 private static final String TAG_STATUS_BAR = "statusbar";
194 private static final String ATTR_DISABLED = "disabled";
196 private static final String ATTR_NAME = "name";
198 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
199 "do-not-ask-credentials-on-boot";
201 private static final String TAG_AFFILIATION_ID = "affiliation-id";
203 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
205 private static final String ATTR_VALUE = "value";
207 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
209 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
211 private static final long MS_PER_DAY = 86400 * 1000;
213 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
215 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
216 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
218 private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
219 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
221 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
222 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
223 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
224 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
225 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
226 "device-provisioning-config-applied";
228 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
229 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
230 = "application-restrictions-manager";
233 * System property whose value is either "true" or "false", indicating whether
235 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
237 private static final int STATUS_BAR_DISABLE_MASK =
238 StatusBarManager.DISABLE_EXPAND |
239 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
240 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
241 StatusBarManager.DISABLE_SEARCH;
243 private static final int STATUS_BAR_DISABLE2_MASK =
244 StatusBarManager.DISABLE2_QUICK_SETTINGS;
246 private static final Set<String> SECURE_SETTINGS_WHITELIST;
247 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
248 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
249 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
251 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
252 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
253 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
254 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
256 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
257 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
258 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
260 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
261 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
262 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
263 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
264 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
265 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
266 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
267 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
268 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
270 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
271 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
272 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
273 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
274 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
275 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
279 * Keyguard features that when set on a managed profile that doesn't have its own challenge will
280 * affect the profile's parent user. These can also be set on the managed profile's parent DPM
283 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
284 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
285 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
288 * Keyguard features that when set on a profile affect the profile content or challenge only.
289 * These cannot be set on the managed profile's parent DPM instance
291 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
292 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
294 /** Keyguard features that are allowed to be set on a managed profile */
295 private static final int PROFILE_KEYGUARD_FEATURES =
296 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
298 private static final int CODE_OK = 0;
299 private static final int CODE_HAS_DEVICE_OWNER = 1;
300 private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
301 private static final int CODE_USER_NOT_RUNNING = 3;
302 private static final int CODE_USER_SETUP_COMPLETED = 4;
303 private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
304 private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
305 private static final int CODE_NOT_SYSTEM_USER = 7;
307 @Retention(RetentionPolicy.SOURCE)
308 @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
309 CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
310 private @interface DeviceOwnerPreConditionCode {}
312 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
314 final Context mContext;
315 final Injector mInjector;
316 final IPackageManager mIPackageManager;
317 final UserManager mUserManager;
318 final UserManagerInternal mUserManagerInternal;
319 final TelephonyManager mTelephonyManager;
320 private final LockPatternUtils mLockPatternUtils;
323 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
324 * is requested for user u.
326 private final Set<Pair<String, Integer>> mPackagesToRemove =
327 new ArraySet<Pair<String, Integer>>();
329 final LocalService mLocalService;
331 // Stores and loads state on device and profile owners.
333 final Owners mOwners;
335 private final Binder mToken = new Binder();
338 * Whether or not device admin feature is supported. If it isn't return defaults for all
343 private final SecurityLogMonitor mSecurityLogMonitor;
345 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
346 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
348 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
351 if(mRemoteBugreportServiceIsActive.get()) {
357 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
360 public void onReceive(Context context, Intent intent) {
361 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
362 && mRemoteBugreportServiceIsActive.get()) {
363 onBugreportFinished(intent);
368 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
371 public void onReceive(Context context, Intent intent) {
372 String action = intent.getAction();
373 mInjector.getNotificationManager().cancel(LOG_TAG,
374 RemoteBugreportUtils.NOTIFICATION_ID);
375 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
376 onBugreportSharingAccepted();
377 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
378 onBugreportSharingDeclined();
380 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
384 public static final class Lifecycle extends SystemService {
385 private DevicePolicyManagerService mService;
387 public Lifecycle(Context context) {
389 mService = new DevicePolicyManagerService(context);
393 public void onStart() {
394 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
398 public void onBootPhase(int phase) {
399 mService.systemReady(phase);
403 public void onStartUser(int userHandle) {
404 mService.onStartUser(userHandle);
408 public static class DevicePolicyData {
409 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
410 int mActivePasswordLength = 0;
411 int mActivePasswordUpperCase = 0;
412 int mActivePasswordLowerCase = 0;
413 int mActivePasswordLetters = 0;
414 int mActivePasswordNumeric = 0;
415 int mActivePasswordSymbols = 0;
416 int mActivePasswordNonLetter = 0;
417 int mFailedPasswordAttempts = 0;
420 int mPasswordOwner = -1;
421 long mLastMaximumTimeToLock = -1;
422 boolean mUserSetupComplete = false;
423 int mUserProvisioningState;
424 int mPermissionPolicy;
426 boolean mDeviceProvisioningConfigApplied = false;
428 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
429 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
430 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
432 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
434 // This is the list of component allowed to start lock task mode.
435 List<String> mLockTaskPackages = new ArrayList<>();
437 boolean mStatusBarDisabled = false;
439 ComponentName mRestrictionsProvider;
441 String mDelegatedCertInstallerPackage;
443 boolean doNotAskCredentialsOnBoot = false;
445 String mApplicationRestrictionsManagingPackage;
447 Set<String> mAffiliationIds = new ArraySet<>();
449 // Used for initialization of users created by createAndManageUsers.
450 boolean mAdminBroadcastPending = false;
451 PersistableBundle mInitBundle = null;
453 public DevicePolicyData(int userHandle) {
454 mUserHandle = userHandle;
458 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
460 final Handler mHandler;
462 BroadcastReceiver mReceiver = new BroadcastReceiver() {
464 public void onReceive(Context context, Intent intent) {
465 final String action = intent.getAction();
466 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
469 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
470 && userHandle == mOwners.getDeviceOwnerUserId()
471 && getDeviceOwnerRemoteBugreportUri() != null) {
472 IntentFilter filterConsent = new IntentFilter();
473 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
474 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
475 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
476 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
477 RemoteBugreportUtils.NOTIFICATION_ID,
478 RemoteBugreportUtils.buildNotification(mContext,
479 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
482 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
483 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
485 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
486 + action + " for user " + userHandle);
488 mHandler.post(new Runnable() {
491 handlePasswordExpirationNotification(userHandle);
495 if (Intent.ACTION_USER_UNLOCKED.equals(action)
496 || Intent.ACTION_USER_STARTED.equals(action)
497 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
498 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
499 new MonitoringCertNotificationTask().execute(userId);
501 if (Intent.ACTION_USER_ADDED.equals(action)) {
502 disableSecurityLoggingIfNotCompliant();
503 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
504 disableSecurityLoggingIfNotCompliant();
505 removeUserData(userHandle);
506 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
507 synchronized (DevicePolicyManagerService.this) {
508 // Reset the policy data
509 mUserData.remove(userHandle);
510 sendAdminEnabledBroadcastLocked(userHandle);
512 handlePackagesChanged(null /* check all admins */, userHandle);
513 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
514 handlePackagesChanged(null /* check all admins */, userHandle);
515 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
516 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
517 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
518 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
519 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
520 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
521 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
522 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
523 clearWipeProfileNotification();
528 static class ActiveAdmin {
529 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
530 private static final String TAG_DISABLE_CAMERA = "disable-camera";
531 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
532 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
533 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
534 = "disable-bt-contacts-sharing";
535 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
536 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
537 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
538 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
539 private static final String TAG_ACCOUNT_TYPE = "account-type";
540 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
541 = "permitted-accessiblity-services";
542 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
543 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
544 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
545 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
546 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
547 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
548 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
549 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
550 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
551 private static final String TAG_PERMITTED_IMES = "permitted-imes";
552 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
553 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
554 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
555 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
556 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
557 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
558 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
559 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
560 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
561 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
562 private static final String ATTR_VALUE = "value";
563 private static final String TAG_PASSWORD_QUALITY = "password-quality";
564 private static final String TAG_POLICIES = "policies";
565 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
566 "cross-profile-widget-providers";
567 private static final String TAG_PROVIDER = "provider";
568 private static final String TAG_PACKAGE_LIST_ITEM = "item";
569 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
570 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
571 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
572 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
573 private static final String TAG_PARENT_ADMIN = "parent-admin";
574 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
575 private static final String TAG_ORGANIZATION_NAME = "organization-name";
577 final DeviceAdminInfo info;
579 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
581 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
582 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
584 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
585 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
587 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
588 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
590 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
591 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
593 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
594 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
596 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
597 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
599 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
600 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
602 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
603 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
605 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
606 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
608 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
609 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
611 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
612 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
614 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
615 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
617 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
619 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
621 boolean encryptionRequested = false;
622 boolean disableCamera = false;
623 boolean disableCallerId = false;
624 boolean disableContactsSearch = false;
625 boolean disableBluetoothContactSharing = true;
626 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
627 boolean requireAutoTime = false; // Can only be set by a device owner.
628 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
630 ActiveAdmin parentAdmin;
631 final boolean isParent;
633 static class TrustAgentInfo {
634 public PersistableBundle options;
635 TrustAgentInfo(PersistableBundle bundle) {
640 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
642 // The list of permitted accessibility services package namesas set by a profile
643 // or device owner. Null means all accessibility services are allowed, empty means
644 // none except system services are allowed.
645 List<String> permittedAccessiblityServices;
647 // The list of permitted input methods package names as set by a profile or device owner.
648 // Null means all input methods are allowed, empty means none except system imes are
650 List<String> permittedInputMethods;
652 // List of package names to keep cached.
653 List<String> keepUninstalledPackages;
655 // TODO: review implementation decisions with frameworks team
656 boolean specifiesGlobalProxy = false;
657 String globalProxySpec = null;
658 String globalProxyExclusionList = null;
660 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
662 List<String> crossProfileWidgetProviders;
664 Bundle userRestrictions;
666 // Support text provided by the admin to display to the user.
667 CharSequence shortSupportMessage = null;
668 CharSequence longSupportMessage = null;
670 // Background color of confirm credentials screen. Default: teal.
671 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
672 int organizationColor = DEF_ORGANIZATION_COLOR;
674 // Default title of confirm credentials screen
675 String organizationName = null;
677 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
682 ActiveAdmin getParentActiveAdmin() {
683 Preconditions.checkState(!isParent);
685 if (parentAdmin == null) {
686 parentAdmin = new ActiveAdmin(info, /* parent */ true);
691 boolean hasParentActiveAdmin() {
692 return parentAdmin != null;
695 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
697 public UserHandle getUserHandle() {
698 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
701 void writeToXml(XmlSerializer out)
702 throws IllegalArgumentException, IllegalStateException, IOException {
703 out.startTag(null, TAG_POLICIES);
704 info.writePoliciesToXml(out);
705 out.endTag(null, TAG_POLICIES);
706 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
707 out.startTag(null, TAG_PASSWORD_QUALITY);
708 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
709 out.endTag(null, TAG_PASSWORD_QUALITY);
710 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
711 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
712 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
713 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
715 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
716 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
717 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
718 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
720 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
721 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
722 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
723 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
725 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
726 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
727 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
728 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
730 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
731 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
732 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
733 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
735 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
736 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
737 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
738 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
740 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
741 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
742 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
743 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
745 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
746 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
747 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
748 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
751 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
752 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
753 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
754 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
756 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
757 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
758 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
759 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
761 if (specifiesGlobalProxy) {
762 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
763 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
764 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
765 if (globalProxySpec != null) {
766 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
767 out.attribute(null, ATTR_VALUE, globalProxySpec);
768 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
770 if (globalProxyExclusionList != null) {
771 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
772 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
773 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
776 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
777 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
778 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
779 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
781 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
782 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
783 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
784 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
786 if (encryptionRequested) {
787 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
788 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
789 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
792 out.startTag(null, TAG_DISABLE_CAMERA);
793 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
794 out.endTag(null, TAG_DISABLE_CAMERA);
796 if (disableCallerId) {
797 out.startTag(null, TAG_DISABLE_CALLER_ID);
798 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
799 out.endTag(null, TAG_DISABLE_CALLER_ID);
801 if (disableContactsSearch) {
802 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
803 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
804 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
806 if (!disableBluetoothContactSharing) {
807 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
808 out.attribute(null, ATTR_VALUE,
809 Boolean.toString(disableBluetoothContactSharing));
810 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
812 if (disableScreenCapture) {
813 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
814 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
815 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
817 if (requireAutoTime) {
818 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
819 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
820 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
822 if (forceEphemeralUsers) {
823 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
824 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
825 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
827 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
828 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
829 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
830 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
832 if (!accountTypesWithManagementDisabled.isEmpty()) {
833 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
834 for (String ac : accountTypesWithManagementDisabled) {
835 out.startTag(null, TAG_ACCOUNT_TYPE);
836 out.attribute(null, ATTR_VALUE, ac);
837 out.endTag(null, TAG_ACCOUNT_TYPE);
839 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
841 if (!trustAgentInfos.isEmpty()) {
842 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
843 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
844 for (Entry<String, TrustAgentInfo> entry : set) {
845 TrustAgentInfo trustAgentInfo = entry.getValue();
846 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
847 out.attribute(null, ATTR_VALUE, entry.getKey());
848 if (trustAgentInfo.options != null) {
849 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
851 trustAgentInfo.options.saveToXml(out);
852 } catch (XmlPullParserException e) {
853 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
855 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
857 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
859 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
861 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
862 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
863 final int providerCount = crossProfileWidgetProviders.size();
864 for (int i = 0; i < providerCount; i++) {
865 String provider = crossProfileWidgetProviders.get(i);
866 out.startTag(null, TAG_PROVIDER);
867 out.attribute(null, ATTR_VALUE, provider);
868 out.endTag(null, TAG_PROVIDER);
870 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
872 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
873 permittedAccessiblityServices);
874 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
875 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
876 if (hasUserRestrictions()) {
877 UserRestrictionsUtils.writeRestrictions(
878 out, userRestrictions, TAG_USER_RESTRICTIONS);
880 if (!TextUtils.isEmpty(shortSupportMessage)) {
881 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
882 out.text(shortSupportMessage.toString());
883 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
885 if (!TextUtils.isEmpty(longSupportMessage)) {
886 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
887 out.text(longSupportMessage.toString());
888 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
890 if (parentAdmin != null) {
891 out.startTag(null, TAG_PARENT_ADMIN);
892 parentAdmin.writeToXml(out);
893 out.endTag(null, TAG_PARENT_ADMIN);
895 if (organizationColor != DEF_ORGANIZATION_COLOR) {
896 out.startTag(null, TAG_ORGANIZATION_COLOR);
897 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
898 out.endTag(null, TAG_ORGANIZATION_COLOR);
900 if (organizationName != null) {
901 out.startTag(null, TAG_ORGANIZATION_NAME);
902 out.text(organizationName);
903 out.endTag(null, TAG_ORGANIZATION_NAME);
907 void writePackageListToXml(XmlSerializer out, String outerTag,
908 List<String> packageList)
909 throws IllegalArgumentException, IllegalStateException, IOException {
910 if (packageList == null) {
914 out.startTag(null, outerTag);
915 for (String packageName : packageList) {
916 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
917 out.attribute(null, ATTR_VALUE, packageName);
918 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
920 out.endTag(null, outerTag);
923 void readFromXml(XmlPullParser parser)
924 throws XmlPullParserException, IOException {
925 int outerDepth = parser.getDepth();
927 while ((type=parser.next()) != END_DOCUMENT
928 && (type != END_TAG || parser.getDepth() > outerDepth)) {
929 if (type == END_TAG || type == TEXT) {
932 String tag = parser.getName();
933 if (TAG_POLICIES.equals(tag)) {
934 info.readPoliciesFromXml(parser);
935 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
936 passwordQuality = Integer.parseInt(
937 parser.getAttributeValue(null, ATTR_VALUE));
938 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
939 minimumPasswordLength = Integer.parseInt(
940 parser.getAttributeValue(null, ATTR_VALUE));
941 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
942 passwordHistoryLength = Integer.parseInt(
943 parser.getAttributeValue(null, ATTR_VALUE));
944 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
945 minimumPasswordUpperCase = Integer.parseInt(
946 parser.getAttributeValue(null, ATTR_VALUE));
947 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
948 minimumPasswordLowerCase = Integer.parseInt(
949 parser.getAttributeValue(null, ATTR_VALUE));
950 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
951 minimumPasswordLetters = Integer.parseInt(
952 parser.getAttributeValue(null, ATTR_VALUE));
953 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
954 minimumPasswordNumeric = Integer.parseInt(
955 parser.getAttributeValue(null, ATTR_VALUE));
956 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
957 minimumPasswordSymbols = Integer.parseInt(
958 parser.getAttributeValue(null, ATTR_VALUE));
959 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
960 minimumPasswordNonLetter = Integer.parseInt(
961 parser.getAttributeValue(null, ATTR_VALUE));
962 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
963 maximumTimeToUnlock = Long.parseLong(
964 parser.getAttributeValue(null, ATTR_VALUE));
965 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
966 maximumFailedPasswordsForWipe = Integer.parseInt(
967 parser.getAttributeValue(null, ATTR_VALUE));
968 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
969 specifiesGlobalProxy = Boolean.parseBoolean(
970 parser.getAttributeValue(null, ATTR_VALUE));
971 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
973 parser.getAttributeValue(null, ATTR_VALUE);
974 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
975 globalProxyExclusionList =
976 parser.getAttributeValue(null, ATTR_VALUE);
977 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
978 passwordExpirationTimeout = Long.parseLong(
979 parser.getAttributeValue(null, ATTR_VALUE));
980 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
981 passwordExpirationDate = Long.parseLong(
982 parser.getAttributeValue(null, ATTR_VALUE));
983 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
984 encryptionRequested = Boolean.parseBoolean(
985 parser.getAttributeValue(null, ATTR_VALUE));
986 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
987 disableCamera = Boolean.parseBoolean(
988 parser.getAttributeValue(null, ATTR_VALUE));
989 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
990 disableCallerId = Boolean.parseBoolean(
991 parser.getAttributeValue(null, ATTR_VALUE));
992 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
993 disableContactsSearch = Boolean.parseBoolean(
994 parser.getAttributeValue(null, ATTR_VALUE));
995 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
996 disableBluetoothContactSharing = Boolean.parseBoolean(parser
997 .getAttributeValue(null, ATTR_VALUE));
998 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
999 disableScreenCapture = Boolean.parseBoolean(
1000 parser.getAttributeValue(null, ATTR_VALUE));
1001 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1002 requireAutoTime = Boolean.parseBoolean(
1003 parser.getAttributeValue(null, ATTR_VALUE));
1004 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1005 forceEphemeralUsers = Boolean.parseBoolean(
1006 parser.getAttributeValue(null, ATTR_VALUE));
1007 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1008 disabledKeyguardFeatures = Integer.parseInt(
1009 parser.getAttributeValue(null, ATTR_VALUE));
1010 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1011 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
1012 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1013 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1014 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1015 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
1016 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1017 permittedAccessiblityServices = readPackageList(parser, tag);
1018 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1019 permittedInputMethods = readPackageList(parser, tag);
1020 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1021 keepUninstalledPackages = readPackageList(parser, tag);
1022 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1023 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
1024 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1025 type = parser.next();
1026 if (type == XmlPullParser.TEXT) {
1027 shortSupportMessage = parser.getText();
1029 Log.w(LOG_TAG, "Missing text when loading short support message");
1031 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1032 type = parser.next();
1033 if (type == XmlPullParser.TEXT) {
1034 longSupportMessage = parser.getText();
1036 Log.w(LOG_TAG, "Missing text when loading long support message");
1038 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1039 Preconditions.checkState(!isParent);
1041 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1042 parentAdmin.readFromXml(parser);
1043 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1044 organizationColor = Integer.parseInt(
1045 parser.getAttributeValue(null, ATTR_VALUE));
1046 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1047 type = parser.next();
1048 if (type == XmlPullParser.TEXT) {
1049 organizationName = parser.getText();
1051 Log.w(LOG_TAG, "Missing text when loading organization name");
1054 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1055 XmlUtils.skipCurrentTag(parser);
1060 private List<String> readPackageList(XmlPullParser parser,
1061 String tag) throws XmlPullParserException, IOException {
1062 List<String> result = new ArrayList<String>();
1063 int outerDepth = parser.getDepth();
1065 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1066 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1067 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1070 String outerTag = parser.getName();
1071 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1072 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1073 if (packageName != null) {
1074 result.add(packageName);
1076 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1079 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1085 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1086 throws XmlPullParserException, IOException {
1087 int outerDepthDAM = parser.getDepth();
1089 Set<String> result = new ArraySet<>();
1090 while ((typeDAM=parser.next()) != END_DOCUMENT
1091 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1092 if (typeDAM == END_TAG || typeDAM == TEXT) {
1095 String tagDAM = parser.getName();
1096 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1097 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1099 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1105 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1106 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1107 int outerDepthDAM = parser.getDepth();
1109 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1110 while ((typeDAM=parser.next()) != END_DOCUMENT
1111 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1112 if (typeDAM == END_TAG || typeDAM == TEXT) {
1115 String tagDAM = parser.getName();
1116 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1117 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1118 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1119 result.put(component, trustAgentInfo);
1121 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1127 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1128 throws XmlPullParserException, IOException {
1129 int outerDepthDAM = parser.getDepth();
1131 TrustAgentInfo result = new TrustAgentInfo(null);
1132 while ((typeDAM=parser.next()) != END_DOCUMENT
1133 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1134 if (typeDAM == END_TAG || typeDAM == TEXT) {
1137 String tagDAM = parser.getName();
1138 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1139 result.options = PersistableBundle.restoreFromXml(parser);
1141 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1147 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1148 throws XmlPullParserException, IOException {
1149 int outerDepthDAM = parser.getDepth();
1151 ArrayList<String> result = null;
1152 while ((typeDAM=parser.next()) != END_DOCUMENT
1153 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1154 if (typeDAM == END_TAG || typeDAM == TEXT) {
1157 String tagDAM = parser.getName();
1158 if (TAG_PROVIDER.equals(tagDAM)) {
1159 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1160 if (result == null) {
1161 result = new ArrayList<>();
1163 result.add(provider);
1165 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1171 boolean hasUserRestrictions() {
1172 return userRestrictions != null && userRestrictions.size() > 0;
1175 Bundle ensureUserRestrictions() {
1176 if (userRestrictions == null) {
1177 userRestrictions = new Bundle();
1179 return userRestrictions;
1182 void dump(String prefix, PrintWriter pw) {
1183 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1184 pw.print(prefix); pw.println("policies:");
1185 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1187 for (int i=0; i<pols.size(); i++) {
1188 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1191 pw.print(prefix); pw.print("passwordQuality=0x");
1192 pw.println(Integer.toHexString(passwordQuality));
1193 pw.print(prefix); pw.print("minimumPasswordLength=");
1194 pw.println(minimumPasswordLength);
1195 pw.print(prefix); pw.print("passwordHistoryLength=");
1196 pw.println(passwordHistoryLength);
1197 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1198 pw.println(minimumPasswordUpperCase);
1199 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1200 pw.println(minimumPasswordLowerCase);
1201 pw.print(prefix); pw.print("minimumPasswordLetters=");
1202 pw.println(minimumPasswordLetters);
1203 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1204 pw.println(minimumPasswordNumeric);
1205 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1206 pw.println(minimumPasswordSymbols);
1207 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1208 pw.println(minimumPasswordNonLetter);
1209 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1210 pw.println(maximumTimeToUnlock);
1211 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1212 pw.println(maximumFailedPasswordsForWipe);
1213 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1214 pw.println(specifiesGlobalProxy);
1215 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1216 pw.println(passwordExpirationTimeout);
1217 pw.print(prefix); pw.print("passwordExpirationDate=");
1218 pw.println(passwordExpirationDate);
1219 if (globalProxySpec != null) {
1220 pw.print(prefix); pw.print("globalProxySpec=");
1221 pw.println(globalProxySpec);
1223 if (globalProxyExclusionList != null) {
1224 pw.print(prefix); pw.print("globalProxyEclusionList=");
1225 pw.println(globalProxyExclusionList);
1227 pw.print(prefix); pw.print("encryptionRequested=");
1228 pw.println(encryptionRequested);
1229 pw.print(prefix); pw.print("disableCamera=");
1230 pw.println(disableCamera);
1231 pw.print(prefix); pw.print("disableCallerId=");
1232 pw.println(disableCallerId);
1233 pw.print(prefix); pw.print("disableContactsSearch=");
1234 pw.println(disableContactsSearch);
1235 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1236 pw.println(disableBluetoothContactSharing);
1237 pw.print(prefix); pw.print("disableScreenCapture=");
1238 pw.println(disableScreenCapture);
1239 pw.print(prefix); pw.print("requireAutoTime=");
1240 pw.println(requireAutoTime);
1241 pw.print(prefix); pw.print("forceEphemeralUsers=");
1242 pw.println(forceEphemeralUsers);
1243 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1244 pw.println(disabledKeyguardFeatures);
1245 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1246 pw.println(crossProfileWidgetProviders);
1247 if (permittedAccessiblityServices != null) {
1248 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1249 pw.println(permittedAccessiblityServices);
1251 if (permittedInputMethods != null) {
1252 pw.print(prefix); pw.print("permittedInputMethods=");
1253 pw.println(permittedInputMethods);
1255 if (keepUninstalledPackages != null) {
1256 pw.print(prefix); pw.print("keepUninstalledPackages=");
1257 pw.println(keepUninstalledPackages);
1259 pw.print(prefix); pw.print("organizationColor=");
1260 pw.println(organizationColor);
1261 if (organizationName != null) {
1262 pw.print(prefix); pw.print("organizationName=");
1263 pw.println(organizationName);
1265 pw.print(prefix); pw.println("userRestrictions:");
1266 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1267 pw.print(prefix); pw.print("isParent=");
1268 pw.println(isParent);
1269 if (parentAdmin != null) {
1270 pw.print(prefix); pw.println("parentAdmin:");
1271 parentAdmin.dump(prefix + " ", pw);
1276 private void handlePackagesChanged(String packageName, int userHandle) {
1277 boolean removed = false;
1278 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1279 DevicePolicyData policy = getUserData(userHandle);
1280 synchronized (this) {
1281 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1282 ActiveAdmin aa = policy.mAdminList.get(i);
1284 // If we're checking all packages or if the specific one we're checking matches,
1285 // then check if the package and receiver still exist.
1286 final String adminPackage = aa.info.getPackageName();
1287 if (packageName == null || packageName.equals(adminPackage)) {
1288 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1289 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1290 PackageManager.MATCH_DIRECT_BOOT_AWARE
1291 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1292 userHandle) == null) {
1294 policy.mAdminList.remove(i);
1295 policy.mAdminMap.remove(aa.info.getComponent());
1298 } catch (RemoteException re) {
1303 validatePasswordOwnerLocked(policy);
1304 saveSettingsLocked(policy.mUserHandle);
1307 // Check if delegated cert installer or app restrictions managing packages are removed.
1308 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1309 policy.mDelegatedCertInstallerPackage = null;
1310 saveSettingsLocked(policy.mUserHandle);
1312 if (isRemovedPackage(
1313 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1314 policy.mApplicationRestrictionsManagingPackage = null;
1315 saveSettingsLocked(policy.mUserHandle);
1319 // The removed admin might have disabled camera, so update user restrictions.
1320 pushUserRestrictions(userHandle);
1324 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1326 return targetPackage != null
1327 && (changedPackage == null || changedPackage.equals(targetPackage))
1328 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1329 } catch (RemoteException e) {
1337 * Unit test will subclass it to inject mocks.
1340 static class Injector {
1342 private final Context mContext;
1344 Injector(Context context) {
1348 Owners newOwners() {
1349 return new Owners(getUserManager(), getUserManagerInternal(),
1350 getPackageManagerInternal());
1353 UserManager getUserManager() {
1354 return UserManager.get(mContext);
1357 UserManagerInternal getUserManagerInternal() {
1358 return LocalServices.getService(UserManagerInternal.class);
1361 PackageManagerInternal getPackageManagerInternal() {
1362 return LocalServices.getService(PackageManagerInternal.class);
1365 NotificationManager getNotificationManager() {
1366 return mContext.getSystemService(NotificationManager.class);
1369 PowerManagerInternal getPowerManagerInternal() {
1370 return LocalServices.getService(PowerManagerInternal.class);
1373 TelephonyManager getTelephonyManager() {
1374 return TelephonyManager.from(mContext);
1377 TrustManager getTrustManager() {
1378 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1381 IWindowManager getIWindowManager() {
1382 return IWindowManager.Stub
1383 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1386 IActivityManager getIActivityManager() {
1387 return ActivityManagerNative.getDefault();
1390 IPackageManager getIPackageManager() {
1391 return AppGlobals.getPackageManager();
1394 IBackupManager getIBackupManager() {
1395 return IBackupManager.Stub.asInterface(
1396 ServiceManager.getService(Context.BACKUP_SERVICE));
1399 IAudioService getIAudioService() {
1400 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1403 LockPatternUtils newLockPatternUtils() {
1404 return new LockPatternUtils(mContext);
1407 boolean storageManagerIsFileBasedEncryptionEnabled() {
1408 return StorageManager.isFileEncryptedNativeOnly();
1411 boolean storageManagerIsNonDefaultBlockEncrypted() {
1412 long identity = Binder.clearCallingIdentity();
1414 return StorageManager.isNonDefaultBlockEncrypted();
1416 Binder.restoreCallingIdentity(identity);
1420 boolean storageManagerIsEncrypted() {
1421 return StorageManager.isEncrypted();
1424 boolean storageManagerIsEncryptable() {
1425 return StorageManager.isEncryptable();
1428 Looper getMyLooper() {
1429 return Looper.myLooper();
1432 WifiManager getWifiManager() {
1433 return mContext.getSystemService(WifiManager.class);
1436 long binderClearCallingIdentity() {
1437 return Binder.clearCallingIdentity();
1440 void binderRestoreCallingIdentity(long token) {
1441 Binder.restoreCallingIdentity(token);
1444 int binderGetCallingUid() {
1445 return Binder.getCallingUid();
1448 int binderGetCallingPid() {
1449 return Binder.getCallingPid();
1452 UserHandle binderGetCallingUserHandle() {
1453 return Binder.getCallingUserHandle();
1456 boolean binderIsCallingUidMyUid() {
1457 return getCallingUid() == Process.myUid();
1460 final int userHandleGetCallingUserId() {
1461 return UserHandle.getUserId(binderGetCallingUid());
1464 File environmentGetUserSystemDirectory(int userId) {
1465 return Environment.getUserSystemDirectory(userId);
1468 void powerManagerGoToSleep(long time, int reason, int flags) {
1469 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1472 void powerManagerReboot(String reason) {
1473 mContext.getSystemService(PowerManager.class).reboot(reason);
1476 boolean systemPropertiesGetBoolean(String key, boolean def) {
1477 return SystemProperties.getBoolean(key, def);
1480 long systemPropertiesGetLong(String key, long def) {
1481 return SystemProperties.getLong(key, def);
1484 String systemPropertiesGet(String key, String def) {
1485 return SystemProperties.get(key, def);
1488 String systemPropertiesGet(String key) {
1489 return SystemProperties.get(key);
1492 void systemPropertiesSet(String key, String value) {
1493 SystemProperties.set(key, value);
1496 boolean userManagerIsSplitSystemUser() {
1497 return UserManager.isSplitSystemUser();
1500 String getDevicePolicyFilePathForSystemUser() {
1501 return "/data/system/";
1504 void registerContentObserver(Uri uri, boolean notifyForDescendents,
1505 ContentObserver observer, int userHandle) {
1506 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1507 observer, userHandle);
1510 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1511 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1512 name, def, userHandle);
1515 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1516 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1517 name, value, userHandle);
1520 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1521 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1522 name, value, userHandle);
1525 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1526 Settings.Global.putStringForUser(mContext.getContentResolver(),
1527 name, value, userHandle);
1530 void settingsSecurePutInt(String name, int value) {
1531 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1534 int settingsGlobalGetInt(String name, int def) {
1535 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1538 void settingsGlobalPutInt(String name, int value) {
1539 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1542 void settingsSecurePutString(String name, String value) {
1543 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1546 void settingsGlobalPutString(String name, String value) {
1547 Settings.Global.putString(mContext.getContentResolver(), name, value);
1550 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1551 SecurityLog.setLoggingEnabledProperty(enabled);
1554 boolean securityLogGetLoggingEnabledProperty() {
1555 return SecurityLog.getLoggingEnabledProperty();
1558 boolean securityLogIsLoggingEnabled() {
1559 return SecurityLog.isLoggingEnabled();
1564 * Instantiates the service.
1566 public DevicePolicyManagerService(Context context) {
1567 this(new Injector(context));
1571 DevicePolicyManagerService(Injector injector) {
1572 mInjector = injector;
1573 mContext = Preconditions.checkNotNull(injector.mContext);
1574 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1575 mOwners = Preconditions.checkNotNull(injector.newOwners());
1577 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1578 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1579 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1580 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1582 mLocalService = new LocalService();
1583 mLockPatternUtils = injector.newLockPatternUtils();
1585 mSecurityLogMonitor = new SecurityLogMonitor(this);
1587 mHasFeature = mContext.getPackageManager()
1588 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1590 // Skip the rest of the initialization
1593 IntentFilter filter = new IntentFilter();
1594 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1595 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1596 filter.addAction(Intent.ACTION_USER_ADDED);
1597 filter.addAction(Intent.ACTION_USER_REMOVED);
1598 filter.addAction(Intent.ACTION_USER_STARTED);
1599 filter.addAction(Intent.ACTION_USER_UNLOCKED);
1600 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1601 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1602 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1603 filter = new IntentFilter();
1604 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1605 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1606 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1607 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1608 filter.addDataScheme("package");
1609 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1610 filter = new IntentFilter();
1611 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1612 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1614 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1618 * Creates and loads the policy data from xml.
1619 * @param userHandle the user for whom to load the policy data
1623 DevicePolicyData getUserData(int userHandle) {
1624 synchronized (this) {
1625 DevicePolicyData policy = mUserData.get(userHandle);
1626 if (policy == null) {
1627 policy = new DevicePolicyData(userHandle);
1628 mUserData.append(userHandle, policy);
1629 loadSettingsLocked(policy, userHandle);
1636 * Creates and loads the policy data from xml for data that is shared between
1637 * various profiles of a user. In contrast to {@link #getUserData(int)}
1638 * it allows access to data of users other than the calling user.
1640 * This function should only be used for shared data, e.g. everything regarding
1641 * passwords and should be removed once multiple screen locks are present.
1642 * @param userHandle the user for whom to load the policy data
1645 DevicePolicyData getUserDataUnchecked(int userHandle) {
1646 long ident = mInjector.binderClearCallingIdentity();
1648 return getUserData(userHandle);
1650 mInjector.binderRestoreCallingIdentity(ident);
1654 void removeUserData(int userHandle) {
1655 synchronized (this) {
1656 if (userHandle == UserHandle.USER_SYSTEM) {
1657 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1660 mOwners.removeProfileOwner(userHandle);
1661 mOwners.writeProfileOwner(userHandle);
1663 DevicePolicyData policy = mUserData.get(userHandle);
1664 if (policy != null) {
1665 mUserData.remove(userHandle);
1667 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1668 DEVICE_POLICIES_XML);
1669 policyFile.delete();
1670 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1672 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1676 synchronized (this) {
1678 setDeviceOwnerSystemPropertyLocked();
1679 findOwnerComponentIfNecessaryLocked();
1680 migrateUserRestrictionsIfNecessaryLocked();
1682 // TODO PO may not have a class name either due to b/17652534. Address that too.
1684 updateDeviceOwnerLocked();
1688 private void setDeviceOwnerSystemPropertyLocked() {
1689 // Device owner may still be provisioned, do not set the read-only system property yet.
1690 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1693 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1694 // always false at this point.
1695 if (StorageManager.inCryptKeeperBounce()) {
1699 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1700 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1702 if (mOwners.hasDeviceOwner()) {
1703 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1704 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1705 disableSecurityLoggingIfNotCompliant();
1706 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1707 mSecurityLogMonitor.start();
1710 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1711 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1716 private void findOwnerComponentIfNecessaryLocked() {
1717 if (!mOwners.hasDeviceOwner()) {
1720 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1722 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1723 return; // Already a full component name.
1726 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1727 doComponentName.getPackageName(),
1728 mOwners.getDeviceOwnerUserId());
1729 if (doComponent == null) {
1730 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1732 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1734 mOwners.getDeviceOwnerName(),
1735 mOwners.getDeviceOwnerUserId(),
1736 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1737 mOwners.writeDeviceOwner();
1739 Log.v(LOG_TAG, "Device owner component filled in");
1745 * We didn't use to persist user restrictions for each owners but only persisted in user
1748 private void migrateUserRestrictionsIfNecessaryLocked() {
1749 boolean migrated = false;
1750 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1751 // except for the "system controlled" ones.
1752 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1754 Log.v(LOG_TAG, "Migrating DO user restrictions");
1758 // Migrate user 0 restrictions to DO.
1759 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1761 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1762 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1764 // Push DO user restrictions to user manager.
1765 pushUserRestrictions(UserHandle.USER_SYSTEM);
1767 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1772 // The following restrictions can be set on secondary users by the device owner, so we
1773 // assume they're not from the PO.
1774 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1775 UserManager.DISALLOW_OUTGOING_CALLS,
1776 UserManager.DISALLOW_SMS);
1778 for (UserInfo ui : mUserManager.getUsers()) {
1779 final int userId = ui.id;
1780 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1782 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1786 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1788 final Set<String> exceptionList =
1789 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1791 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1792 exceptionList, /* isDeviceOwner =*/ false);
1794 // Note if a secondary user has no PO but has a DA that disables camera, we
1795 // don't get here and won't push the camera user restriction to UserManager
1796 // here. That's okay because we'll push user restrictions anyway when a user
1797 // starts. But we still do it because we want to let user manager persist
1799 pushUserRestrictions(userId);
1801 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1804 if (VERBOSE_LOG && migrated) {
1805 Log.v(LOG_TAG, "User restrictions migrated.");
1809 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1810 Set<String> exceptionList, boolean isDeviceOwner) {
1811 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1812 user.getIdentifier());
1814 final Bundle newBaseRestrictions = new Bundle();
1815 final Bundle newOwnerRestrictions = new Bundle();
1817 for (String key : origRestrictions.keySet()) {
1818 if (!origRestrictions.getBoolean(key)) {
1821 final boolean canOwnerChange = isDeviceOwner
1822 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1823 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1825 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1826 newBaseRestrictions.putBoolean(key, true);
1828 newOwnerRestrictions.putBoolean(key, true);
1833 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1834 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1835 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1837 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1838 newBaseRestrictions);
1840 if (admin != null) {
1841 admin.ensureUserRestrictions().clear();
1842 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1844 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1846 saveSettingsLocked(user.getIdentifier());
1849 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1850 final DevicePolicyData policy = getUserData(userId);
1851 final int n = policy.mAdminList.size();
1852 ComponentName found = null;
1854 for (int i = 0; i < n; i++) {
1855 final ActiveAdmin admin = policy.mAdminList.get(i);
1856 if (packageName.equals(admin.info.getPackageName())) {
1859 found = admin.info.getComponent();
1865 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1871 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1872 * reminders. Clears alarm if no expirations are configured.
1874 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1875 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1876 final long now = System.currentTimeMillis();
1877 final long timeToExpire = expiration - now;
1878 final long alarmTime;
1879 if (expiration == 0) {
1880 // No expirations are currently configured: Cancel alarm.
1882 } else if (timeToExpire <= 0) {
1883 // The password has already expired: Repeat every 24 hours.
1884 alarmTime = now + MS_PER_DAY;
1886 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1887 // the expiration time.
1888 long alarmInterval = timeToExpire % MS_PER_DAY;
1889 if (alarmInterval == 0) {
1890 alarmInterval = MS_PER_DAY;
1892 alarmTime = now + alarmInterval;
1895 long token = mInjector.binderClearCallingIdentity();
1897 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1898 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1899 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1900 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1901 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1902 UserHandle.of(affectedUserHandle));
1904 if (alarmTime != 0) {
1905 am.set(AlarmManager.RTC, alarmTime, pi);
1908 mInjector.binderRestoreCallingIdentity(token);
1912 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1913 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1915 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1916 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1922 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
1924 enforceManagedProfile(userHandle, "call APIs on the parent profile");
1926 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1927 if (admin != null && parent) {
1928 admin = admin.getParentActiveAdmin();
1933 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1934 throws SecurityException {
1935 final int callingUid = mInjector.binderGetCallingUid();
1937 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1938 if (result != null) {
1943 final int userId = UserHandle.getUserId(callingUid);
1944 final DevicePolicyData policy = getUserData(userId);
1945 ActiveAdmin admin = policy.mAdminMap.get(who);
1946 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1947 throw new SecurityException("Admin " + admin.info.getComponent()
1948 + " does not own the device");
1950 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1951 throw new SecurityException("Admin " + admin.info.getComponent()
1952 + " does not own the profile");
1954 throw new SecurityException("Admin " + admin.info.getComponent()
1955 + " did not specify uses-policy for: "
1956 + admin.info.getTagForPolicy(reqPolicy));
1958 throw new SecurityException("No active admin owned by uid "
1959 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
1963 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
1964 throws SecurityException {
1966 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
1967 "call APIs on the parent profile");
1969 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
1970 return parent ? admin.getParentActiveAdmin() : admin;
1973 * Find the admin for the component and userId bit of the uid, then check
1974 * the admin's uid matches the uid.
1976 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
1977 final int userId = UserHandle.getUserId(uid);
1978 final DevicePolicyData policy = getUserData(userId);
1979 ActiveAdmin admin = policy.mAdminMap.get(who);
1980 if (admin == null) {
1981 throw new SecurityException("No active admin " + who);
1983 if (admin.getUid() != uid) {
1984 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1989 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
1991 // Try to find an admin which can use reqPolicy
1992 final int userId = UserHandle.getUserId(uid);
1993 final DevicePolicyData policy = getUserData(userId);
1995 ActiveAdmin admin = policy.mAdminMap.get(who);
1996 if (admin == null) {
1997 throw new SecurityException("No active admin " + who);
1999 if (admin.getUid() != uid) {
2000 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2002 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2006 for (ActiveAdmin admin : policy.mAdminList) {
2007 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2018 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2020 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2021 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2023 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2025 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2026 // DO always has the PO power.
2027 return ownsDevice || ownsProfile;
2029 return admin.info.usesPolicy(reqPolicy);
2033 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2034 sendAdminCommandLocked(admin, action, null);
2037 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2038 sendAdminCommandLocked(admin, action, null, result);
2042 * Send an update to one specific admin, get notified when that admin returns a result.
2044 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2045 BroadcastReceiver result) {
2046 Intent intent = new Intent(action);
2047 intent.setComponent(admin.info.getComponent());
2048 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2049 intent.putExtra("expiration", admin.passwordExpirationDate);
2051 if (adminExtras != null) {
2052 intent.putExtras(adminExtras);
2054 if (result != null) {
2055 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2056 null, result, mHandler, Activity.RESULT_OK, null, null);
2058 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2063 * Send an update to all admins of a user that enforce a specified policy.
2065 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2066 final DevicePolicyData policy = getUserData(userHandle);
2067 final int count = policy.mAdminList.size();
2069 for (int i = 0; i < count; i++) {
2070 final ActiveAdmin admin = policy.mAdminList.get(i);
2071 if (admin.info.usesPolicy(reqPolicy)) {
2072 sendAdminCommandLocked(admin, action);
2079 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2080 * enforce a specified policy.
2082 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2084 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2085 for (int profileId : profileIds) {
2086 sendAdminCommandLocked(action, reqPolicy, profileId);
2091 * Sends a broadcast to each profile that share the password unlock with the given user id.
2093 private void sendAdminCommandForLockscreenPoliciesLocked(
2094 String action, int reqPolicy, int userHandle) {
2095 if (isSeparateProfileChallengeEnabled(userHandle)) {
2096 sendAdminCommandLocked(action, reqPolicy, userHandle);
2098 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2102 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2103 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2104 DevicePolicyData policy = getUserData(userHandle);
2105 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2106 policy.mRemovingAdmins.add(adminReceiver);
2107 sendAdminCommandLocked(admin,
2108 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2109 new BroadcastReceiver() {
2111 public void onReceive(Context context, Intent intent) {
2112 removeAdminArtifacts(adminReceiver, userHandle);
2113 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2120 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2121 boolean throwForMissiongPermission) {
2125 enforceFullCrossUsersPermission(userHandle);
2126 ActivityInfo ai = null;
2128 ai = mIPackageManager.getReceiverInfo(adminName,
2129 PackageManager.GET_META_DATA |
2130 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2131 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2132 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2133 } catch (RemoteException e) {
2134 // shouldn't happen.
2137 throw new IllegalArgumentException("Unknown admin: " + adminName);
2140 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2141 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2142 + permission.BIND_DEVICE_ADMIN;
2143 Slog.w(LOG_TAG, message);
2144 if (throwForMissiongPermission &&
2145 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2146 throw new IllegalArgumentException(message);
2151 return new DeviceAdminInfo(mContext, ai);
2152 } catch (XmlPullParserException | IOException e) {
2153 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2159 private JournaledFile makeJournaledFile(int userHandle) {
2160 final String base = userHandle == UserHandle.USER_SYSTEM
2161 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2162 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2163 DEVICE_POLICIES_XML).getAbsolutePath();
2165 Log.v(LOG_TAG, "Opening " + base);
2167 return new JournaledFile(new File(base), new File(base + ".tmp"));
2170 private void saveSettingsLocked(int userHandle) {
2171 DevicePolicyData policy = getUserData(userHandle);
2172 JournaledFile journal = makeJournaledFile(userHandle);
2173 FileOutputStream stream = null;
2175 stream = new FileOutputStream(journal.chooseForWrite(), false);
2176 XmlSerializer out = new FastXmlSerializer();
2177 out.setOutput(stream, StandardCharsets.UTF_8.name());
2178 out.startDocument(null, true);
2180 out.startTag(null, "policies");
2181 if (policy.mRestrictionsProvider != null) {
2182 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2183 policy.mRestrictionsProvider.flattenToString());
2185 if (policy.mUserSetupComplete) {
2186 out.attribute(null, ATTR_SETUP_COMPLETE,
2187 Boolean.toString(true));
2189 if (policy.mDeviceProvisioningConfigApplied) {
2190 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2191 Boolean.toString(true));
2193 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2194 out.attribute(null, ATTR_PROVISIONING_STATE,
2195 Integer.toString(policy.mUserProvisioningState));
2197 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2198 out.attribute(null, ATTR_PERMISSION_POLICY,
2199 Integer.toString(policy.mPermissionPolicy));
2201 if (policy.mDelegatedCertInstallerPackage != null) {
2202 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2203 policy.mDelegatedCertInstallerPackage);
2205 if (policy.mApplicationRestrictionsManagingPackage != null) {
2206 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2207 policy.mApplicationRestrictionsManagingPackage);
2210 final int N = policy.mAdminList.size();
2211 for (int i=0; i<N; i++) {
2212 ActiveAdmin ap = policy.mAdminList.get(i);
2214 out.startTag(null, "admin");
2215 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2217 out.endTag(null, "admin");
2221 if (policy.mPasswordOwner >= 0) {
2222 out.startTag(null, "password-owner");
2223 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2224 out.endTag(null, "password-owner");
2227 if (policy.mFailedPasswordAttempts != 0) {
2228 out.startTag(null, "failed-password-attempts");
2229 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2230 out.endTag(null, "failed-password-attempts");
2233 // Don't save metrics for FBE devices
2234 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
2235 && (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2236 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2237 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2238 || policy.mActivePasswordSymbols != 0
2239 || policy.mActivePasswordNonLetter != 0)) {
2240 out.startTag(null, "active-password");
2241 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2242 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2243 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2244 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2245 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2246 out.attribute(null, "numeric", Integer
2247 .toString(policy.mActivePasswordNumeric));
2248 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2249 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2250 out.endTag(null, "active-password");
2253 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2254 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2255 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2256 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2259 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2260 String component = policy.mLockTaskPackages.get(i);
2261 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2262 out.attribute(null, "name", component);
2263 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2266 if (policy.mStatusBarDisabled) {
2267 out.startTag(null, TAG_STATUS_BAR);
2268 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2269 out.endTag(null, TAG_STATUS_BAR);
2272 if (policy.doNotAskCredentialsOnBoot) {
2273 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2274 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2277 for (String id : policy.mAffiliationIds) {
2278 out.startTag(null, TAG_AFFILIATION_ID);
2279 out.attribute(null, "id", id);
2280 out.endTag(null, TAG_AFFILIATION_ID);
2283 if (policy.mAdminBroadcastPending) {
2284 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2285 out.attribute(null, ATTR_VALUE,
2286 Boolean.toString(policy.mAdminBroadcastPending));
2287 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2290 if (policy.mInitBundle != null) {
2291 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2292 policy.mInitBundle.saveToXml(out);
2293 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2296 out.endTag(null, "policies");
2300 FileUtils.sync(stream);
2303 sendChangedNotification(userHandle);
2304 } catch (XmlPullParserException | IOException e) {
2305 Slog.w(LOG_TAG, "failed writing file", e);
2307 if (stream != null) {
2310 } catch (IOException ex) {
2317 private void sendChangedNotification(int userHandle) {
2318 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2319 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2320 long ident = mInjector.binderClearCallingIdentity();
2322 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2324 mInjector.binderRestoreCallingIdentity(ident);
2328 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2329 JournaledFile journal = makeJournaledFile(userHandle);
2330 FileInputStream stream = null;
2331 File file = journal.chooseForRead();
2332 boolean needsRewrite = false;
2334 stream = new FileInputStream(file);
2335 XmlPullParser parser = Xml.newPullParser();
2336 parser.setInput(stream, StandardCharsets.UTF_8.name());
2339 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2340 && type != XmlPullParser.START_TAG) {
2342 String tag = parser.getName();
2343 if (!"policies".equals(tag)) {
2344 throw new XmlPullParserException(
2345 "Settings do not start with policies tag: found " + tag);
2348 // Extract the permission provider component name if available
2349 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2350 if (permissionProvider != null) {
2351 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2353 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2354 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2355 policy.mUserSetupComplete = true;
2357 String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2358 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2359 if (deviceProvisioningConfigApplied != null
2360 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2361 policy.mDeviceProvisioningConfigApplied = true;
2363 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2364 if (!TextUtils.isEmpty(provisioningState)) {
2365 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2367 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2368 if (!TextUtils.isEmpty(permissionPolicy)) {
2369 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2371 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2372 ATTR_DELEGATED_CERT_INSTALLER);
2373 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2374 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2376 type = parser.next();
2377 int outerDepth = parser.getDepth();
2378 policy.mLockTaskPackages.clear();
2379 policy.mAdminList.clear();
2380 policy.mAdminMap.clear();
2381 policy.mAffiliationIds.clear();
2382 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2383 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2384 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2387 tag = parser.getName();
2388 if ("admin".equals(tag)) {
2389 String name = parser.getAttributeValue(null, "name");
2391 DeviceAdminInfo dai = findAdmin(
2392 ComponentName.unflattenFromString(name), userHandle,
2393 /* throwForMissionPermission= */ false);
2395 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2397 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2398 + dai.getActivityInfo().applicationInfo.uid + " for user "
2402 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2403 ap.readFromXml(parser);
2404 policy.mAdminMap.put(ap.info.getComponent(), ap);
2406 } catch (RuntimeException e) {
2407 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2409 } else if ("failed-password-attempts".equals(tag)) {
2410 policy.mFailedPasswordAttempts = Integer.parseInt(
2411 parser.getAttributeValue(null, "value"));
2412 } else if ("password-owner".equals(tag)) {
2413 policy.mPasswordOwner = Integer.parseInt(
2414 parser.getAttributeValue(null, "value"));
2415 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2416 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2417 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2418 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2419 } else if (TAG_STATUS_BAR.equals(tag)) {
2420 policy.mStatusBarDisabled = Boolean.parseBoolean(
2421 parser.getAttributeValue(null, ATTR_DISABLED));
2422 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2423 policy.doNotAskCredentialsOnBoot = true;
2424 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2425 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2426 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2427 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2428 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2429 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2430 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2431 } else if ("active-password".equals(tag)) {
2432 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2433 // Remove this from FBE devices
2434 needsRewrite = true;
2436 policy.mActivePasswordQuality = Integer.parseInt(
2437 parser.getAttributeValue(null, "quality"));
2438 policy.mActivePasswordLength = Integer.parseInt(
2439 parser.getAttributeValue(null, "length"));
2440 policy.mActivePasswordUpperCase = Integer.parseInt(
2441 parser.getAttributeValue(null, "uppercase"));
2442 policy.mActivePasswordLowerCase = Integer.parseInt(
2443 parser.getAttributeValue(null, "lowercase"));
2444 policy.mActivePasswordLetters = Integer.parseInt(
2445 parser.getAttributeValue(null, "letters"));
2446 policy.mActivePasswordNumeric = Integer.parseInt(
2447 parser.getAttributeValue(null, "numeric"));
2448 policy.mActivePasswordSymbols = Integer.parseInt(
2449 parser.getAttributeValue(null, "symbols"));
2450 policy.mActivePasswordNonLetter = Integer.parseInt(
2451 parser.getAttributeValue(null, "nonletter"));
2454 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2455 XmlUtils.skipCurrentTag(parser);
2458 } catch (FileNotFoundException e) {
2459 // Don't be noisy, this is normal if we haven't defined any policies.
2460 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2461 | IndexOutOfBoundsException e) {
2462 Slog.w(LOG_TAG, "failed parsing " + file, e);
2465 if (stream != null) {
2468 } catch (IOException e) {
2472 // Generate a list of admins from the admin map
2473 policy.mAdminList.addAll(policy.mAdminMap.values());
2475 // Might need to upgrade the file by rewriting it
2477 saveSettingsLocked(userHandle);
2480 validatePasswordOwnerLocked(policy);
2481 updateMaximumTimeToLockLocked(userHandle);
2482 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2483 if (policy.mStatusBarDisabled) {
2484 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2488 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2489 long ident = mInjector.binderClearCallingIdentity();
2491 mInjector.getIActivityManager()
2492 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2493 } catch (RemoteException e) {
2494 // Not gonna happen.
2496 mInjector.binderRestoreCallingIdentity(ident);
2500 private void updateDeviceOwnerLocked() {
2501 long ident = mInjector.binderClearCallingIdentity();
2503 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2504 // user id and also protect all other DAs too.
2505 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2506 if (deviceOwnerComponent != null) {
2507 mInjector.getIActivityManager()
2508 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2510 } catch (RemoteException e) {
2511 // Not gonna happen.
2513 mInjector.binderRestoreCallingIdentity(ident);
2517 static void validateQualityConstant(int quality) {
2519 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2520 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2521 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2522 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2523 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2524 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2525 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2526 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2527 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2530 throw new IllegalArgumentException("Invalid quality constant: 0x"
2531 + Integer.toHexString(quality));
2534 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2535 if (policy.mPasswordOwner >= 0) {
2536 boolean haveOwner = false;
2537 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2538 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2544 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2545 + " no longer active; disabling");
2546 policy.mPasswordOwner = -1;
2552 void systemReady(int phase) {
2557 case SystemService.PHASE_LOCK_SETTINGS_READY:
2558 onLockSettingsReady();
2560 case SystemService.PHASE_BOOT_COMPLETED:
2561 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2566 private void onLockSettingsReady() {
2567 getUserData(UserHandle.USER_SYSTEM);
2571 onStartUser(UserHandle.USER_SYSTEM);
2573 // Register an observer for watching for user setup complete.
2574 new SetupContentObserver(mHandler).register();
2575 // Initialize the user setup state, to handle the upgrade case.
2576 updateUserSetupComplete();
2578 List<String> packageList;
2579 synchronized (this) {
2580 packageList = getKeepUninstalledPackagesLocked();
2582 if (packageList != null) {
2583 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2586 synchronized (this) {
2587 // push the force-ephemeral-users policy to the user manager.
2588 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2589 if (deviceOwner != null) {
2590 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2595 private void ensureDeviceOwnerUserStarted() {
2597 synchronized (this) {
2598 if (!mOwners.hasDeviceOwner()) {
2601 userId = mOwners.getDeviceOwnerUserId();
2604 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2606 if (userId != UserHandle.USER_SYSTEM) {
2608 mInjector.getIActivityManager().startUserInBackground(userId);
2610 // STOPSHIP Prevent the DO user from being killed.
2612 } catch (RemoteException e) {
2613 Slog.w(LOG_TAG, "Exception starting user", e);
2618 private void onStartUser(int userId) {
2619 updateScreenCaptureDisabledInWindowManager(userId,
2620 getScreenCaptureDisabled(null, userId));
2621 pushUserRestrictions(userId);
2624 private void cleanUpOldUsers() {
2625 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2627 Set<Integer> usersWithProfileOwners;
2628 Set<Integer> usersWithData;
2629 synchronized(this) {
2630 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2631 usersWithData = new ArraySet<>();
2632 for (int i = 0; i < mUserData.size(); i++) {
2633 usersWithData.add(mUserData.keyAt(i));
2636 List<UserInfo> allUsers = mUserManager.getUsers();
2638 Set<Integer> deletedUsers = new ArraySet<>();
2639 deletedUsers.addAll(usersWithProfileOwners);
2640 deletedUsers.addAll(usersWithData);
2641 for (UserInfo userInfo : allUsers) {
2642 deletedUsers.remove(userInfo.id);
2644 for (Integer userId : deletedUsers) {
2645 removeUserData(userId);
2649 private void handlePasswordExpirationNotification(int userHandle) {
2650 synchronized (this) {
2651 final long now = System.currentTimeMillis();
2653 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2654 userHandle, /* parent */ false);
2655 final int N = admins.size();
2656 for (int i = 0; i < N; i++) {
2657 ActiveAdmin admin = admins.get(i);
2658 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2659 && admin.passwordExpirationTimeout > 0L
2660 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2661 && admin.passwordExpirationDate > 0L) {
2662 sendAdminCommandLocked(admin,
2663 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2666 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2670 private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2672 protected Void doInBackground(Integer... params) {
2673 int userHandle = params[0];
2675 if (userHandle == UserHandle.USER_ALL) {
2676 for (UserInfo userInfo : mUserManager.getUsers(true)) {
2677 manageNotification(userInfo.getUserHandle());
2680 manageNotification(UserHandle.of(userHandle));
2685 private void manageNotification(UserHandle userHandle) {
2686 if (!mUserManager.isUserUnlocked(userHandle)) {
2690 // Call out to KeyChain to check for CAs which are waiting for approval.
2691 final List<String> pendingCertificates;
2693 pendingCertificates = getInstalledCaCertificates(userHandle);
2694 } catch (RemoteException | RuntimeException e) {
2695 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2699 synchronized (DevicePolicyManagerService.this) {
2700 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2702 // Remove deleted certificates. Flush xml if necessary.
2703 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2704 saveSettingsLocked(userHandle.getIdentifier());
2706 // Trim to approved certificates.
2707 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2710 if (pendingCertificates.isEmpty()) {
2711 mInjector.getNotificationManager().cancelAsUser(
2712 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2716 // Build and show a warning notification
2719 int parentUserId = userHandle.getIdentifier();
2720 if (getProfileOwner(userHandle.getIdentifier()) != null) {
2721 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2722 getProfileOwnerName(userHandle.getIdentifier()));
2723 smallIconId = R.drawable.stat_sys_certificate_info;
2724 parentUserId = getProfileParentId(userHandle.getIdentifier());
2725 } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
2726 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2727 getDeviceOwnerName());
2728 smallIconId = R.drawable.stat_sys_certificate_info;
2730 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2731 smallIconId = android.R.drawable.stat_sys_warning;
2734 final int numberOfCertificates = pendingCertificates.size();
2735 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2736 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2737 dialogIntent.setPackage("com.android.settings");
2738 dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
2739 dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
2740 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2741 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
2742 new UserHandle(parentUserId));
2744 final Context userContext;
2746 final String packageName = mContext.getPackageName();
2747 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
2748 } catch (PackageManager.NameNotFoundException e) {
2749 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2752 final Notification noti = new Notification.Builder(userContext)
2753 .setSmallIcon(smallIconId)
2754 .setContentTitle(mContext.getResources().getQuantityText(
2755 R.plurals.ssl_ca_cert_warning, numberOfCertificates))
2756 .setContentText(contentText)
2757 .setContentIntent(notifyIntent)
2758 .setPriority(Notification.PRIORITY_HIGH)
2760 .setColor(mContext.getColor(
2761 com.android.internal.R.color.system_notification_accent_color))
2764 mInjector.getNotificationManager().notifyAsUser(
2765 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2768 private List<String> getInstalledCaCertificates(UserHandle userHandle)
2769 throws RemoteException, RuntimeException {
2770 KeyChainConnection conn = null;
2772 conn = KeyChain.bindAsUser(mContext, userHandle);
2773 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
2774 List<String> result = new ArrayList<>(aliases.size());
2775 for (int i = 0; i < aliases.size(); i++) {
2776 result.add(aliases.get(i).string);
2779 } catch (InterruptedException e) {
2780 Thread.currentThread().interrupt();
2782 } catch (AssertionError e) {
2783 throw new RuntimeException(e);
2793 * @param adminReceiver The admin to add
2794 * @param refreshing true = update an active admin, no error
2797 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2801 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2804 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2805 Bundle onEnableData) {
2806 mContext.enforceCallingOrSelfPermission(
2807 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2808 enforceFullCrossUsersPermission(userHandle);
2810 DevicePolicyData policy = getUserData(userHandle);
2811 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2812 /* throwForMissionPermission= */ true);
2814 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2816 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2817 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2820 synchronized (this) {
2821 long ident = mInjector.binderClearCallingIdentity();
2824 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
2825 throw new IllegalArgumentException("Admin is already added");
2827 if (policy.mRemovingAdmins.contains(adminReceiver)) {
2828 throw new IllegalArgumentException(
2829 "Trying to set an admin which is being removed");
2831 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2832 policy.mAdminMap.put(adminReceiver, newAdmin);
2833 int replaceIndex = -1;
2834 final int N = policy.mAdminList.size();
2835 for (int i=0; i < N; i++) {
2836 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2837 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2842 if (replaceIndex == -1) {
2843 policy.mAdminList.add(newAdmin);
2844 enableIfNecessary(info.getPackageName(), userHandle);
2846 policy.mAdminList.set(replaceIndex, newAdmin);
2848 saveSettingsLocked(userHandle);
2849 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2850 onEnableData, null);
2852 mInjector.binderRestoreCallingIdentity(ident);
2858 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2862 enforceFullCrossUsersPermission(userHandle);
2863 synchronized (this) {
2864 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2869 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2873 enforceFullCrossUsersPermission(userHandle);
2874 synchronized (this) {
2875 DevicePolicyData policyData = getUserData(userHandle);
2876 return policyData.mRemovingAdmins.contains(adminReceiver);
2881 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2885 enforceFullCrossUsersPermission(userHandle);
2886 synchronized (this) {
2887 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2888 if (administrator == null) {
2889 throw new SecurityException("No active admin " + adminReceiver);
2891 return administrator.info.usesPolicy(policyId);
2896 @SuppressWarnings("unchecked")
2897 public List<ComponentName> getActiveAdmins(int userHandle) {
2899 return Collections.EMPTY_LIST;
2902 enforceFullCrossUsersPermission(userHandle);
2903 synchronized (this) {
2904 DevicePolicyData policy = getUserData(userHandle);
2905 final int N = policy.mAdminList.size();
2909 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2910 for (int i=0; i<N; i++) {
2911 res.add(policy.mAdminList.get(i).info.getComponent());
2918 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2922 enforceFullCrossUsersPermission(userHandle);
2923 synchronized (this) {
2924 DevicePolicyData policy = getUserData(userHandle);
2925 final int N = policy.mAdminList.size();
2926 for (int i=0; i<N; i++) {
2927 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2935 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
2939 Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
2940 enforceShell("forceRemoveActiveAdmin");
2941 long ident = mInjector.binderClearCallingIdentity();
2943 final ApplicationInfo ai;
2945 ai = mIPackageManager.getApplicationInfo(adminReceiver.getPackageName(),
2947 } catch (RemoteException e) {
2948 throw new IllegalStateException(e);
2951 throw new IllegalStateException("Couldn't find package to remove admin "
2952 + adminReceiver.getPackageName() + " " + userHandle);
2954 if ((ai.flags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
2955 throw new SecurityException("Attempt to remove non-test admin " + adminReceiver
2956 + adminReceiver + " " + userHandle);
2958 // If admin is a device or profile owner tidy that up first.
2959 synchronized (this) {
2960 if (isDeviceOwner(adminReceiver, userHandle)) {
2961 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
2963 if (isProfileOwner(adminReceiver, userHandle)) {
2964 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
2965 userHandle, /* parent */ false);
2966 clearProfileOwnerLocked(admin, userHandle);
2969 // Remove the admin skipping sending the broadcast.
2970 removeAdminArtifacts(adminReceiver, userHandle);
2972 mInjector.binderRestoreCallingIdentity(ident);
2976 private void enforceShell(String method) {
2977 final int callingUid = Binder.getCallingUid();
2978 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
2979 throw new SecurityException("Non-shell user attempted to call " + method);
2984 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
2988 enforceFullCrossUsersPermission(userHandle);
2989 enforceUserUnlocked(userHandle);
2990 synchronized (this) {
2991 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2992 if (admin == null) {
2995 // Active device/profile owners must remain active admins.
2996 if (isDeviceOwner(adminReceiver, userHandle)
2997 || isProfileOwner(adminReceiver, userHandle)) {
2998 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3002 if (admin.getUid() != mInjector.binderGetCallingUid()) {
3003 mContext.enforceCallingOrSelfPermission(
3004 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3006 long ident = mInjector.binderClearCallingIdentity();
3008 removeActiveAdminLocked(adminReceiver, userHandle);
3010 mInjector.binderRestoreCallingIdentity(ident);
3016 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3017 ComponentName profileOwner = getProfileOwner(userHandle);
3018 // Profile challenge is supported on N or newer release.
3019 return profileOwner != null &&
3020 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3024 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3028 Preconditions.checkNotNull(who, "ComponentName is null");
3029 validateQualityConstant(quality);
3031 synchronized (this) {
3032 ActiveAdmin ap = getActiveAdminForCallerLocked(
3033 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3034 if (ap.passwordQuality != quality) {
3035 ap.passwordQuality = quality;
3036 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3042 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3044 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3046 enforceFullCrossUsersPermission(userHandle);
3047 synchronized (this) {
3048 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3051 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3052 return admin != null ? admin.passwordQuality : mode;
3055 // Return the strictest policy across all participating admins.
3056 List<ActiveAdmin> admins =
3057 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3058 final int N = admins.size();
3059 for (int i = 0; i < N; i++) {
3060 ActiveAdmin admin = admins.get(i);
3061 if (mode < admin.passwordQuality) {
3062 mode = admin.passwordQuality;
3069 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3070 int userHandle, boolean parent) {
3071 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3072 // If this user has a separate challenge, only return its restrictions.
3073 return getUserDataUnchecked(userHandle).mAdminList;
3075 // Return all admins for this user and the profiles that are visible from this
3076 // user that do not use a separate work challenge.
3077 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3078 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3079 DevicePolicyData policy = getUserData(userInfo.id);
3080 if (!userInfo.isManagedProfile()) {
3081 admins.addAll(policy.mAdminList);
3083 // For managed profiles, we always include the policies set on the parent
3084 // profile. Additionally, we include the ones set on the managed profile
3085 // if no separate challenge is in place.
3086 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3087 final int N = policy.mAdminList.size();
3088 for (int i = 0; i < N; i++) {
3089 ActiveAdmin admin = policy.mAdminList.get(i);
3090 if (admin.hasParentActiveAdmin()) {
3091 admins.add(admin.getParentActiveAdmin());
3093 if (!hasSeparateChallenge) {
3103 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3104 long ident = mInjector.binderClearCallingIdentity();
3106 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3108 mInjector.binderRestoreCallingIdentity(ident);
3113 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3117 Preconditions.checkNotNull(who, "ComponentName is null");
3118 synchronized (this) {
3119 ActiveAdmin ap = getActiveAdminForCallerLocked(
3120 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3121 if (ap.minimumPasswordLength != length) {
3122 ap.minimumPasswordLength = length;
3123 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3129 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3133 enforceFullCrossUsersPermission(userHandle);
3134 synchronized (this) {
3138 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3139 return admin != null ? admin.minimumPasswordLength : length;
3142 // Return the strictest policy across all participating admins.
3143 List<ActiveAdmin> admins =
3144 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3145 final int N = admins.size();
3146 for (int i = 0; i < N; i++) {
3147 ActiveAdmin admin = admins.get(i);
3148 if (length < admin.minimumPasswordLength) {
3149 length = admin.minimumPasswordLength;
3157 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3161 Preconditions.checkNotNull(who, "ComponentName is null");
3162 synchronized (this) {
3163 ActiveAdmin ap = getActiveAdminForCallerLocked(
3164 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3165 if (ap.passwordHistoryLength != length) {
3166 ap.passwordHistoryLength = length;
3167 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3173 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3177 enforceFullCrossUsersPermission(userHandle);
3178 synchronized (this) {
3182 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3183 return admin != null ? admin.passwordHistoryLength : length;
3186 // Return the strictest policy across all participating admins.
3187 List<ActiveAdmin> admins =
3188 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3189 final int N = admins.size();
3190 for (int i = 0; i < N; i++) {
3191 ActiveAdmin admin = admins.get(i);
3192 if (length < admin.passwordHistoryLength) {
3193 length = admin.passwordHistoryLength;
3202 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3206 Preconditions.checkNotNull(who, "ComponentName is null");
3207 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3208 final int userHandle = mInjector.userHandleGetCallingUserId();
3209 synchronized (this) {
3210 ActiveAdmin ap = getActiveAdminForCallerLocked(
3211 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3212 // Calling this API automatically bumps the expiration date
3213 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3214 ap.passwordExpirationDate = expiration;
3215 ap.passwordExpirationTimeout = timeout;
3217 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3218 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3219 .format(new Date(expiration)));
3221 saveSettingsLocked(userHandle);
3223 // in case this is the first one, set the alarm on the appropriate user.
3224 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3229 * Return a single admin's expiration cycle time, or the min of all cycle times.
3230 * Returns 0 if not configured.
3233 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3237 enforceFullCrossUsersPermission(userHandle);
3238 synchronized (this) {
3242 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3243 return admin != null ? admin.passwordExpirationTimeout : timeout;
3246 // Return the strictest policy across all participating admins.
3247 List<ActiveAdmin> admins =
3248 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3249 final int N = admins.size();
3250 for (int i = 0; i < N; i++) {
3251 ActiveAdmin admin = admins.get(i);
3252 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3253 && timeout > admin.passwordExpirationTimeout)) {
3254 timeout = admin.passwordExpirationTimeout;
3262 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3263 final int userId = UserHandle.getCallingUserId();
3264 List<String> changedProviders = null;
3266 synchronized (this) {
3267 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3268 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3269 if (activeAdmin.crossProfileWidgetProviders == null) {
3270 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3272 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3273 if (!providers.contains(packageName)) {
3274 providers.add(packageName);
3275 changedProviders = new ArrayList<>(providers);
3276 saveSettingsLocked(userId);
3280 if (changedProviders != null) {
3281 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3289 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3290 final int userId = UserHandle.getCallingUserId();
3291 List<String> changedProviders = null;
3293 synchronized (this) {
3294 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3295 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3296 if (activeAdmin.crossProfileWidgetProviders == null) {
3299 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3300 if (providers.remove(packageName)) {
3301 changedProviders = new ArrayList<>(providers);
3302 saveSettingsLocked(userId);
3306 if (changedProviders != null) {
3307 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3315 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3316 synchronized (this) {
3317 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3318 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3319 if (activeAdmin.crossProfileWidgetProviders == null
3320 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3323 if (mInjector.binderIsCallingUidMyUid()) {
3324 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3326 return activeAdmin.crossProfileWidgetProviders;
3332 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3333 * Returns 0 if not configured.
3335 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3339 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3340 return admin != null ? admin.passwordExpirationDate : timeout;
3343 // Return the strictest policy across all participating admins.
3344 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3345 final int N = admins.size();
3346 for (int i = 0; i < N; i++) {
3347 ActiveAdmin admin = admins.get(i);
3348 if (timeout == 0L || (admin.passwordExpirationDate != 0
3349 && timeout > admin.passwordExpirationDate)) {
3350 timeout = admin.passwordExpirationDate;
3357 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3361 enforceFullCrossUsersPermission(userHandle);
3362 synchronized (this) {
3363 return getPasswordExpirationLocked(who, userHandle, parent);
3368 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3372 Preconditions.checkNotNull(who, "ComponentName is null");
3373 synchronized (this) {
3374 ActiveAdmin ap = getActiveAdminForCallerLocked(
3375 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3376 if (ap.minimumPasswordUpperCase != length) {
3377 ap.minimumPasswordUpperCase = length;
3378 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3384 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3388 enforceFullCrossUsersPermission(userHandle);
3389 synchronized (this) {
3393 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3394 return admin != null ? admin.minimumPasswordUpperCase : length;
3397 // Return the strictest policy across all participating admins.
3398 List<ActiveAdmin> admins =
3399 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3400 final int N = admins.size();
3401 for (int i = 0; i < N; i++) {
3402 ActiveAdmin admin = admins.get(i);
3403 if (length < admin.minimumPasswordUpperCase) {
3404 length = admin.minimumPasswordUpperCase;
3412 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3413 Preconditions.checkNotNull(who, "ComponentName is null");
3414 synchronized (this) {
3415 ActiveAdmin ap = getActiveAdminForCallerLocked(
3416 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3417 if (ap.minimumPasswordLowerCase != length) {
3418 ap.minimumPasswordLowerCase = length;
3419 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3425 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3429 enforceFullCrossUsersPermission(userHandle);
3430 synchronized (this) {
3434 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3435 return admin != null ? admin.minimumPasswordLowerCase : length;
3438 // Return the strictest policy across all participating admins.
3439 List<ActiveAdmin> admins =
3440 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3441 final int N = admins.size();
3442 for (int i = 0; i < N; i++) {
3443 ActiveAdmin admin = admins.get(i);
3444 if (length < admin.minimumPasswordLowerCase) {
3445 length = admin.minimumPasswordLowerCase;
3453 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3457 Preconditions.checkNotNull(who, "ComponentName is null");
3458 synchronized (this) {
3459 ActiveAdmin ap = getActiveAdminForCallerLocked(
3460 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3461 if (ap.minimumPasswordLetters != length) {
3462 ap.minimumPasswordLetters = length;
3463 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3469 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3473 enforceFullCrossUsersPermission(userHandle);
3474 synchronized (this) {
3478 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3479 return admin != null ? admin.minimumPasswordLetters : length;
3482 // Return the strictest policy across all participating admins.
3483 List<ActiveAdmin> admins =
3484 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3485 final int N = admins.size();
3486 for (int i = 0; i < N; i++) {
3487 ActiveAdmin admin = admins.get(i);
3488 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3491 if (length < admin.minimumPasswordLetters) {
3492 length = admin.minimumPasswordLetters;
3500 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3504 Preconditions.checkNotNull(who, "ComponentName is null");
3505 synchronized (this) {
3506 ActiveAdmin ap = getActiveAdminForCallerLocked(
3507 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3508 if (ap.minimumPasswordNumeric != length) {
3509 ap.minimumPasswordNumeric = length;
3510 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3516 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3520 enforceFullCrossUsersPermission(userHandle);
3521 synchronized (this) {
3525 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3526 return admin != null ? admin.minimumPasswordNumeric : length;
3529 // Return the strictest policy across all participating admins.
3530 List<ActiveAdmin> admins =
3531 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3532 final int N = admins.size();
3533 for (int i = 0; i < N; i++) {
3534 ActiveAdmin admin = admins.get(i);
3535 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3538 if (length < admin.minimumPasswordNumeric) {
3539 length = admin.minimumPasswordNumeric;
3547 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3551 Preconditions.checkNotNull(who, "ComponentName is null");
3552 synchronized (this) {
3553 ActiveAdmin ap = getActiveAdminForCallerLocked(
3554 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3555 if (ap.minimumPasswordSymbols != length) {
3556 ap.minimumPasswordSymbols = length;
3557 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3563 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3567 enforceFullCrossUsersPermission(userHandle);
3568 synchronized (this) {
3572 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3573 return admin != null ? admin.minimumPasswordSymbols : length;
3576 // Return the strictest policy across all participating admins.
3577 List<ActiveAdmin> admins =
3578 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3579 final int N = admins.size();
3580 for (int i = 0; i < N; i++) {
3581 ActiveAdmin admin = admins.get(i);
3582 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3585 if (length < admin.minimumPasswordSymbols) {
3586 length = admin.minimumPasswordSymbols;
3594 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3598 Preconditions.checkNotNull(who, "ComponentName is null");
3599 synchronized (this) {
3600 ActiveAdmin ap = getActiveAdminForCallerLocked(
3601 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3602 if (ap.minimumPasswordNonLetter != length) {
3603 ap.minimumPasswordNonLetter = length;
3604 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3610 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3614 enforceFullCrossUsersPermission(userHandle);
3615 synchronized (this) {
3619 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3620 return admin != null ? admin.minimumPasswordNonLetter : length;
3623 // Return the strictest policy across all participating admins.
3624 List<ActiveAdmin> admins =
3625 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3626 final int N = admins.size();
3627 for (int i = 0; i < N; i++) {
3628 ActiveAdmin admin = admins.get(i);
3629 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3632 if (length < admin.minimumPasswordNonLetter) {
3633 length = admin.minimumPasswordNonLetter;
3641 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3645 enforceFullCrossUsersPermission(userHandle);
3647 synchronized (this) {
3648 // This API can only be called by an active device admin,
3649 // so try to retrieve it to check that the caller is one.
3650 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3651 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3652 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3657 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3661 enforceFullCrossUsersPermission(userHandle);
3662 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3664 synchronized (this) {
3665 int targetUser = getProfileParentId(userHandle);
3666 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3667 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3671 private boolean isActivePasswordSufficientForUserLocked(
3672 DevicePolicyData policy, int userHandle, boolean parent) {
3673 final long id = Binder.clearCallingIdentity();
3675 enforceUserUnlocked(userHandle, parent);
3677 Binder.restoreCallingIdentity(id);
3680 if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle, parent)
3681 || policy.mActivePasswordLength < getPasswordMinimumLength(
3682 null, userHandle, parent)) {
3685 if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3688 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3689 null, userHandle, parent)
3690 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3691 null, userHandle, parent)
3692 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3693 null, userHandle, parent)
3694 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3695 null, userHandle, parent)
3696 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3697 null, userHandle, parent)
3698 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3699 null, userHandle, parent);
3703 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3704 enforceFullCrossUsersPermission(userHandle);
3705 synchronized (this) {
3706 if (!isCallerWithSystemUid()) {
3707 // This API can only be called by an active device admin,
3708 // so try to retrieve it to check that the caller is one.
3709 getActiveAdminForCallerLocked(
3710 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3713 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3715 return policy.mFailedPasswordAttempts;
3720 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3724 Preconditions.checkNotNull(who, "ComponentName is null");
3725 synchronized (this) {
3726 // This API can only be called by an active device admin,
3727 // so try to retrieve it to check that the caller is one.
3728 getActiveAdminForCallerLocked(
3729 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3730 ActiveAdmin ap = getActiveAdminForCallerLocked(
3731 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3732 if (ap.maximumFailedPasswordsForWipe != num) {
3733 ap.maximumFailedPasswordsForWipe = num;
3734 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3740 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3744 enforceFullCrossUsersPermission(userHandle);
3745 synchronized (this) {
3746 ActiveAdmin admin = (who != null)
3747 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3748 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3749 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3754 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3756 return UserHandle.USER_NULL;
3758 enforceFullCrossUsersPermission(userHandle);
3759 synchronized (this) {
3760 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3761 userHandle, parent);
3762 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3767 * Returns the admin with the strictest policy on maximum failed passwords for:
3769 * <li>this user if it has a separate profile challenge, or
3770 * <li>this user and all profiles that don't have their own challenge otherwise.
3772 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3773 * the primary profile.
3774 * Returns {@code null} if no participating admin has that policy set.
3776 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3777 int userHandle, boolean parent) {
3779 ActiveAdmin strictestAdmin = null;
3781 // Return the strictest policy across all participating admins.
3782 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3783 final int N = admins.size();
3784 for (int i = 0; i < N; i++) {
3785 ActiveAdmin admin = admins.get(i);
3786 if (admin.maximumFailedPasswordsForWipe ==
3787 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3788 continue; // No max number of failed passwords policy set for this profile.
3791 // We always favor the primary profile if several profiles have the same value set.
3792 int userId = admin.getUserHandle().getIdentifier();
3794 count > admin.maximumFailedPasswordsForWipe ||
3795 (count == admin.maximumFailedPasswordsForWipe &&
3796 getUserInfo(userId).isPrimary())) {
3797 count = admin.maximumFailedPasswordsForWipe;
3798 strictestAdmin = admin;
3801 return strictestAdmin;
3804 private UserInfo getUserInfo(@UserIdInt int userId) {
3805 final long token = mInjector.binderClearCallingIdentity();
3807 return mUserManager.getUserInfo(userId);
3809 mInjector.binderRestoreCallingIdentity(token);
3814 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3818 final int callingUid = mInjector.binderGetCallingUid();
3819 final int userHandle = mInjector.userHandleGetCallingUserId();
3821 String password = passwordOrNull != null ? passwordOrNull : "";
3823 // Password resetting to empty/null is not allowed for managed profiles.
3824 if (TextUtils.isEmpty(password)) {
3825 enforceNotManagedProfile(userHandle, "clear the active password");
3829 synchronized (this) {
3830 // If caller has PO (or DO) it can change the password, so see if that's the case first.
3831 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3832 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3834 if (admin != null) {
3835 preN = getTargetSdk(admin.info.getPackageName(),
3836 userHandle) <= android.os.Build.VERSION_CODES.M;
3838 // Otherwise, make sure the caller has any active admin with the right policy.
3839 admin = getActiveAdminForCallerLocked(null,
3840 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3841 preN = getTargetSdk(admin.info.getPackageName(),
3842 userHandle) <= android.os.Build.VERSION_CODES.M;
3844 // As of N, password resetting to empty/null is not allowed anymore.
3845 // TODO Should we allow DO/PO to set an empty password?
3846 if (TextUtils.isEmpty(password)) {
3848 throw new SecurityException("Cannot call with null password");
3850 Slog.e(LOG_TAG, "Cannot call with null password");
3854 // As of N, password cannot be changed by the admin if it is already set.
3855 if (isLockScreenSecureUnchecked(userHandle)) {
3857 throw new SecurityException("Admin cannot change current password");
3859 Slog.e(LOG_TAG, "Admin cannot change current password");
3864 // Do not allow to reset password when current user has a managed profile
3865 if (!isManagedProfile(userHandle)) {
3866 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3867 if (userInfo.isManagedProfile()) {
3869 throw new IllegalStateException(
3870 "Cannot reset password on user has managed profile");
3872 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
3878 // Do not allow to reset password when user is locked
3879 if (!mUserManager.isUserUnlocked(userHandle)) {
3881 throw new IllegalStateException("Cannot reset password when user is locked");
3883 Slog.e(LOG_TAG, "Cannot reset password when user is locked");
3888 quality = getPasswordQuality(null, userHandle, /* parent */ false);
3889 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
3890 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3892 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
3893 int realQuality = LockPatternUtils.computePasswordQuality(password);
3894 if (realQuality < quality
3895 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3896 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
3897 + Integer.toHexString(realQuality)
3898 + " does not meet required quality 0x"
3899 + Integer.toHexString(quality));
3902 quality = Math.max(realQuality, quality);
3904 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
3905 if (password.length() < length) {
3906 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
3907 + " does not meet required length " + length);
3910 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3917 for (int i = 0; i < password.length(); i++) {
3918 char c = password.charAt(i);
3919 if (c >= 'A' && c <= 'Z') {
3922 } else if (c >= 'a' && c <= 'z') {
3925 } else if (c >= '0' && c <= '9') {
3933 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
3934 if(letters < neededLetters) {
3935 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
3936 + " does not meet required number of letters " + neededLetters);
3939 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
3940 if (numbers < neededNumbers) {
3941 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
3942 + " does not meet required number of numerical digits "
3946 int neededLowerCase = getPasswordMinimumLowerCase(
3947 null, userHandle, /* parent */ false);
3948 if (lowercase < neededLowerCase) {
3949 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
3950 + " does not meet required number of lowercase letters "
3954 int neededUpperCase = getPasswordMinimumUpperCase(
3955 null, userHandle, /* parent */ false);
3956 if (uppercase < neededUpperCase) {
3957 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
3958 + " does not meet required number of uppercase letters "
3962 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
3963 if (symbols < neededSymbols) {
3964 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
3965 + " does not meet required number of special symbols " + neededSymbols);
3968 int neededNonLetter = getPasswordMinimumNonLetter(
3969 null, userHandle, /* parent */ false);
3970 if (nonletter < neededNonLetter) {
3971 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
3972 + " does not meet required number of non-letter characters "
3979 DevicePolicyData policy = getUserData(userHandle);
3980 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
3981 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
3985 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
3986 boolean doNotAskCredentialsOnBoot =
3987 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
3988 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
3989 setDoNotAskCredentialsOnBoot();
3992 // Don't do this with the lock held, because it is going to call
3993 // back in to the service.
3994 final long ident = mInjector.binderClearCallingIdentity();
3996 if (!TextUtils.isEmpty(password)) {
3997 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
3999 mLockPatternUtils.clearLock(userHandle);
4001 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4003 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4004 UserHandle.USER_ALL);
4006 synchronized (this) {
4007 int newOwner = requireEntry ? callingUid : -1;
4008 if (policy.mPasswordOwner != newOwner) {
4009 policy.mPasswordOwner = newOwner;
4010 saveSettingsLocked(userHandle);
4014 mInjector.binderRestoreCallingIdentity(ident);
4020 private boolean isLockScreenSecureUnchecked(int userId) {
4021 long ident = mInjector.binderClearCallingIdentity();
4023 return mLockPatternUtils.isSecure(userId);
4025 mInjector.binderRestoreCallingIdentity(ident);
4029 private void setDoNotAskCredentialsOnBoot() {
4030 synchronized (this) {
4031 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4032 if (!policyData.doNotAskCredentialsOnBoot) {
4033 policyData.doNotAskCredentialsOnBoot = true;
4034 saveSettingsLocked(UserHandle.USER_SYSTEM);
4040 public boolean getDoNotAskCredentialsOnBoot() {
4041 mContext.enforceCallingOrSelfPermission(
4042 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4043 synchronized (this) {
4044 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4045 return policyData.doNotAskCredentialsOnBoot;
4050 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4054 Preconditions.checkNotNull(who, "ComponentName is null");
4055 final int userHandle = mInjector.userHandleGetCallingUserId();
4056 synchronized (this) {
4057 ActiveAdmin ap = getActiveAdminForCallerLocked(
4058 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4059 if (ap.maximumTimeToUnlock != timeMs) {
4060 ap.maximumTimeToUnlock = timeMs;
4061 saveSettingsLocked(userHandle);
4062 updateMaximumTimeToLockLocked(userHandle);
4067 void updateMaximumTimeToLockLocked(int userHandle) {
4068 // Calculate the min timeout for all profiles - including the ones with a separate
4069 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4070 // challenge only and keep the screen on. However there is no easy way of doing that at the
4071 // moment so we set the screen off timeout regardless of whether it affects the parent user
4072 // or the profile challenge only.
4073 long timeMs = Long.MAX_VALUE;
4074 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4075 for (int profileId : profileIds) {
4076 DevicePolicyData policy = getUserDataUnchecked(profileId);
4077 final int N = policy.mAdminList.size();
4078 for (int i = 0; i < N; i++) {
4079 ActiveAdmin admin = policy.mAdminList.get(i);
4080 if (admin.maximumTimeToUnlock > 0
4081 && timeMs > admin.maximumTimeToUnlock) {
4082 timeMs = admin.maximumTimeToUnlock;
4084 // If userInfo.id is a managed profile, we also need to look at
4085 // the policies set on the parent.
4086 if (admin.hasParentActiveAdmin()) {
4087 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4088 if (parentAdmin.maximumTimeToUnlock > 0
4089 && timeMs > parentAdmin.maximumTimeToUnlock) {
4090 timeMs = parentAdmin.maximumTimeToUnlock;
4096 // We only store the last maximum time to lock on the parent profile. So if calling from a
4097 // managed profile, retrieve the policy for the parent.
4098 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4099 if (policy.mLastMaximumTimeToLock == timeMs) {
4102 policy.mLastMaximumTimeToLock = timeMs;
4104 final long ident = mInjector.binderClearCallingIdentity();
4106 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4107 // Make sure KEEP_SCREEN_ON is disabled, since that
4108 // would allow bypassing of the maximum time to lock.
4109 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4112 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4113 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4115 mInjector.binderRestoreCallingIdentity(ident);
4120 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4124 enforceFullCrossUsersPermission(userHandle);
4125 synchronized (this) {
4127 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4128 return admin != null ? admin.maximumTimeToUnlock : 0;
4130 // Return the strictest policy across all participating admins.
4131 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4132 userHandle, parent);
4133 return getMaximumTimeToLockPolicyFromAdmins(admins);
4138 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4142 enforceFullCrossUsersPermission(userHandle);
4143 synchronized (this) {
4144 // All admins for this user.
4145 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4146 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4147 DevicePolicyData policy = getUserData(userInfo.id);
4148 admins.addAll(policy.mAdminList);
4149 // If it is a managed profile, it may have parent active admins
4150 if (userInfo.isManagedProfile()) {
4151 for (ActiveAdmin admin : policy.mAdminList) {
4152 if (admin.hasParentActiveAdmin()) {
4153 admins.add(admin.getParentActiveAdmin());
4158 return getMaximumTimeToLockPolicyFromAdmins(admins);
4162 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4164 final int N = admins.size();
4165 for (int i = 0; i < N; i++) {
4166 ActiveAdmin admin = admins.get(i);
4168 time = admin.maximumTimeToUnlock;
4169 } else if (admin.maximumTimeToUnlock != 0
4170 && time > admin.maximumTimeToUnlock) {
4171 time = admin.maximumTimeToUnlock;
4178 public void lockNow(boolean parent) {
4182 synchronized (this) {
4183 // This API can only be called by an active device admin,
4184 // so try to retrieve it to check that the caller is one.
4185 getActiveAdminForCallerLocked(
4186 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4188 int userToLock = mInjector.userHandleGetCallingUserId();
4190 // Unless this is a managed profile with work challenge enabled, lock all users.
4191 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4192 userToLock = UserHandle.USER_ALL;
4194 final long ident = mInjector.binderClearCallingIdentity();
4196 mLockPatternUtils.requireStrongAuth(
4197 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4198 if (userToLock == UserHandle.USER_ALL) {
4199 // Power off the display
4200 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4201 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4202 mInjector.getIWindowManager().lockNow(null);
4204 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4206 } catch (RemoteException e) {
4208 mInjector.binderRestoreCallingIdentity(ident);
4214 public void enforceCanManageCaCerts(ComponentName who) {
4216 if (!isCallerDelegatedCertInstaller()) {
4217 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4220 synchronized (this) {
4221 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4226 private void enforceCanManageInstalledKeys(ComponentName who) {
4228 if (!isCallerDelegatedCertInstaller()) {
4229 throw new SecurityException("who == null, but caller is not cert installer");
4232 synchronized (this) {
4233 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4238 private boolean isCallerDelegatedCertInstaller() {
4239 final int callingUid = mInjector.binderGetCallingUid();
4240 final int userHandle = UserHandle.getUserId(callingUid);
4241 synchronized (this) {
4242 final DevicePolicyData policy = getUserData(userHandle);
4243 if (policy.mDelegatedCertInstallerPackage == null) {
4248 int uid = mContext.getPackageManager().getPackageUidAsUser(
4249 policy.mDelegatedCertInstallerPackage, userHandle);
4250 return uid == callingUid;
4251 } catch (NameNotFoundException e) {
4258 public boolean approveCaCert(String alias, int userId, boolean approval) {
4259 enforceManageUsers();
4260 synchronized (this) {
4261 Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4262 boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4266 saveSettingsLocked(userId);
4268 new MonitoringCertNotificationTask().execute(userId);
4273 public boolean isCaCertApproved(String alias, int userId) {
4274 enforceManageUsers();
4275 synchronized (this) {
4276 return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4280 private void removeCaApprovalsIfNeeded(int userId) {
4281 for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4282 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4283 if (userInfo.isManagedProfile()){
4284 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4287 synchronized (this) {
4288 getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4289 saveSettingsLocked(userInfo.id);
4292 new MonitoringCertNotificationTask().execute(userInfo.id);
4298 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4299 enforceCanManageCaCerts(admin);
4303 X509Certificate cert = parseCert(certBuffer);
4304 pemCert = Credentials.convertToPem(cert);
4305 } catch (CertificateException ce) {
4306 Log.e(LOG_TAG, "Problem converting cert", ce);
4308 } catch (IOException ioe) {
4309 Log.e(LOG_TAG, "Problem reading cert", ioe);
4313 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4314 final long id = mInjector.binderClearCallingIdentity();
4316 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4318 keyChainConnection.getService().installCaCertificate(pemCert);
4320 } catch (RemoteException e) {
4321 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4323 keyChainConnection.close();
4325 } catch (InterruptedException e1) {
4326 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4327 Thread.currentThread().interrupt();
4329 mInjector.binderRestoreCallingIdentity(id);
4334 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4335 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4336 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4341 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4342 enforceCanManageCaCerts(admin);
4344 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4345 final long id = mInjector.binderClearCallingIdentity();
4347 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4349 for (int i = 0 ; i < aliases.length; i++) {
4350 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4352 } catch (RemoteException e) {
4353 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4355 keyChainConnection.close();
4357 } catch (InterruptedException ie) {
4358 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4359 Thread.currentThread().interrupt();
4361 mInjector.binderRestoreCallingIdentity(id);
4366 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4367 String alias, boolean requestAccess) {
4368 enforceCanManageInstalledKeys(who);
4370 final int callingUid = mInjector.binderGetCallingUid();
4371 final long id = mInjector.binderClearCallingIdentity();
4373 final KeyChainConnection keyChainConnection =
4374 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4376 IKeyChainService keyChain = keyChainConnection.getService();
4377 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4380 if (requestAccess) {
4381 keyChain.setGrant(callingUid, alias, true);
4384 } catch (RemoteException e) {
4385 Log.e(LOG_TAG, "Installing certificate", e);
4387 keyChainConnection.close();
4389 } catch (InterruptedException e) {
4390 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4391 Thread.currentThread().interrupt();
4393 mInjector.binderRestoreCallingIdentity(id);
4399 public boolean removeKeyPair(ComponentName who, String alias) {
4400 enforceCanManageInstalledKeys(who);
4402 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4403 final long id = Binder.clearCallingIdentity();
4405 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4407 IKeyChainService keyChain = keyChainConnection.getService();
4408 return keyChain.removeKeyPair(alias);
4409 } catch (RemoteException e) {
4410 Log.e(LOG_TAG, "Removing keypair", e);
4412 keyChainConnection.close();
4414 } catch (InterruptedException e) {
4415 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4416 Thread.currentThread().interrupt();
4418 Binder.restoreCallingIdentity(id);
4424 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4425 final IBinder response) {
4426 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4427 if (!isCallerWithSystemUid()) {
4431 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4432 // If there is a profile owner, redirect to that; otherwise query the device owner.
4433 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4434 if (aliasChooser == null && caller.isSystem()) {
4435 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4436 if (deviceOwnerAdmin != null) {
4437 aliasChooser = deviceOwnerAdmin.info.getComponent();
4440 if (aliasChooser == null) {
4441 sendPrivateKeyAliasResponse(null, response);
4445 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4446 intent.setComponent(aliasChooser);
4447 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4448 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4449 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4450 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4451 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4453 final long id = mInjector.binderClearCallingIdentity();
4455 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4457 public void onReceive(Context context, Intent intent) {
4458 final String chosenAlias = getResultData();
4459 sendPrivateKeyAliasResponse(chosenAlias, response);
4461 }, null, Activity.RESULT_OK, null, null);
4463 mInjector.binderRestoreCallingIdentity(id);
4467 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4468 final IKeyChainAliasCallback keyChainAliasResponse =
4469 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4470 new AsyncTask<Void, Void, Void>() {
4472 protected Void doInBackground(Void... unused) {
4474 keyChainAliasResponse.alias(alias);
4475 } catch (Exception e) {
4476 // Catch everything (not just RemoteException): caller could throw a
4477 // RuntimeException back across processes.
4478 Log.e(LOG_TAG, "error while responding to callback", e);
4486 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4487 throws SecurityException {
4488 int userHandle = UserHandle.getCallingUserId();
4489 synchronized (this) {
4490 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4491 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4492 if (installerPackage != null &&
4493 !isPackageInstalledForUser(installerPackage, userHandle)) {
4494 throw new IllegalArgumentException("Package " + installerPackage
4495 + " is not installed on the current user");
4498 DevicePolicyData policy = getUserData(userHandle);
4499 policy.mDelegatedCertInstallerPackage = installerPackage;
4500 saveSettingsLocked(userHandle);
4505 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4506 int userHandle = UserHandle.getCallingUserId();
4507 synchronized (this) {
4508 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4509 DevicePolicyData policy = getUserData(userHandle);
4510 return policy.mDelegatedCertInstallerPackage;
4515 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4516 * not installed and therefore not available.
4518 * @throws SecurityException if the caller is not a profile or device owner.
4519 * @throws UnsupportedException if the package does not support being set as always-on.
4522 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4523 throws SecurityException {
4524 synchronized (this) {
4525 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4528 final int userId = mInjector.userHandleGetCallingUserId();
4529 final long token = mInjector.binderClearCallingIdentity();
4531 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4534 ConnectivityManager connectivityManager = (ConnectivityManager)
4535 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4536 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4537 throw new UnsupportedOperationException();
4540 mInjector.binderRestoreCallingIdentity(token);
4546 public String getAlwaysOnVpnPackage(ComponentName admin)
4547 throws SecurityException {
4548 synchronized (this) {
4549 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4552 final int userId = mInjector.userHandleGetCallingUserId();
4553 final long token = mInjector.binderClearCallingIdentity();
4555 ConnectivityManager connectivityManager = (ConnectivityManager)
4556 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4557 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4559 mInjector.binderRestoreCallingIdentity(token);
4563 private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
4564 if (wipeExtRequested) {
4565 StorageManager sm = (StorageManager) mContext.getSystemService(
4566 Context.STORAGE_SERVICE);
4567 sm.wipeAdoptableDisks();
4570 RecoverySystem.rebootWipeUserData(mContext, reason);
4571 } catch (IOException | SecurityException e) {
4572 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4577 public void wipeData(int flags) {
4581 final int userHandle = mInjector.userHandleGetCallingUserId();
4582 enforceFullCrossUsersPermission(userHandle);
4584 final String source;
4585 synchronized (this) {
4586 // This API can only be called by an active device admin,
4587 // so try to retrieve it to check that the caller is one.
4588 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4589 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4590 source = admin.info.getComponent().flattenToShortString();
4592 long ident = mInjector.binderClearCallingIdentity();
4594 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4595 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4596 throw new SecurityException(
4597 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4599 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4600 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4601 if (manager != null) {
4606 mInjector.binderRestoreCallingIdentity(ident);
4609 final boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4610 wipeDeviceNoLock(wipeExtRequested, userHandle,
4611 "DevicePolicyManager.wipeData() from " + source);
4614 private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
4615 final long ident = mInjector.binderClearCallingIdentity();
4617 if (userHandle == UserHandle.USER_SYSTEM) {
4618 wipeDataNoLock(wipeExtRequested, reason);
4620 mHandler.post(new Runnable() {
4624 IActivityManager am = mInjector.getIActivityManager();
4625 if (am.getCurrentUser().id == userHandle) {
4626 am.switchUser(UserHandle.USER_SYSTEM);
4629 boolean isManagedProfile = isManagedProfile(userHandle);
4630 if (!mUserManager.removeUser(userHandle)) {
4631 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4632 } else if (isManagedProfile) {
4633 sendWipeProfileNotification();
4635 } catch (RemoteException re) {
4642 mInjector.binderRestoreCallingIdentity(ident);
4646 private void sendWipeProfileNotification() {
4647 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4648 Notification notification = new Notification.Builder(mContext)
4649 .setSmallIcon(android.R.drawable.stat_sys_warning)
4650 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4651 .setContentText(contentText)
4652 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4653 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4655 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4658 private void clearWipeProfileNotification() {
4659 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4663 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4667 enforceFullCrossUsersPermission(userHandle);
4668 mContext.enforceCallingOrSelfPermission(
4669 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4671 synchronized (this) {
4672 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4673 if (admin == null) {
4674 result.sendResult(null);
4677 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4678 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4679 intent.setComponent(admin.info.getComponent());
4680 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4681 null, new BroadcastReceiver() {
4683 public void onReceive(Context context, Intent intent) {
4684 result.sendResult(getResultExtras(false));
4686 }, null, Activity.RESULT_OK, null, null);
4691 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4692 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4696 enforceFullCrossUsersPermission(userHandle);
4697 mContext.enforceCallingOrSelfPermission(
4698 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4700 // If the managed profile doesn't have a separate password, set the metrics to default
4701 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
4702 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4712 validateQualityConstant(quality);
4713 DevicePolicyData policy = getUserData(userHandle);
4714 synchronized (this) {
4715 policy.mActivePasswordQuality = quality;
4716 policy.mActivePasswordLength = length;
4717 policy.mActivePasswordLetters = letters;
4718 policy.mActivePasswordLowerCase = lowercase;
4719 policy.mActivePasswordUpperCase = uppercase;
4720 policy.mActivePasswordNumeric = numbers;
4721 policy.mActivePasswordSymbols = symbols;
4722 policy.mActivePasswordNonLetter = nonletter;
4727 public void reportPasswordChanged(int userId) {
4731 enforceFullCrossUsersPermission(userId);
4733 // Managed Profile password can only be changed when it has a separate challenge.
4734 if (!isSeparateProfileChallengeEnabled(userId)) {
4735 enforceNotManagedProfile(userId, "set the active password");
4738 mContext.enforceCallingOrSelfPermission(
4739 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4741 DevicePolicyData policy = getUserData(userId);
4743 long ident = mInjector.binderClearCallingIdentity();
4745 synchronized (this) {
4746 policy.mFailedPasswordAttempts = 0;
4747 saveSettingsLocked(userId);
4748 updatePasswordExpirationsLocked(userId);
4749 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
4751 // Send a broadcast to each profile using this password as its primary unlock.
4752 sendAdminCommandForLockscreenPoliciesLocked(
4753 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4754 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
4756 removeCaApprovalsIfNeeded(userId);
4758 mInjector.binderRestoreCallingIdentity(ident);
4763 * Called any time the device password is updated. Resets all password expiration clocks.
4765 private void updatePasswordExpirationsLocked(int userHandle) {
4766 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4767 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4768 userHandle, /* parent */ false);
4769 final int N = admins.size();
4770 for (int i = 0; i < N; i++) {
4771 ActiveAdmin admin = admins.get(i);
4772 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4773 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4774 long timeout = admin.passwordExpirationTimeout;
4775 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4776 admin.passwordExpirationDate = expiration;
4779 for (int affectedUserId : affectedUserIds) {
4780 saveSettingsLocked(affectedUserId);
4785 public void reportFailedPasswordAttempt(int userHandle) {
4786 enforceFullCrossUsersPermission(userHandle);
4787 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4788 enforceNotManagedProfile(userHandle,
4789 "report failed password attempt if separate profile challenge is not in place");
4791 mContext.enforceCallingOrSelfPermission(
4792 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4794 final long ident = mInjector.binderClearCallingIdentity();
4796 boolean wipeData = false;
4798 synchronized (this) {
4799 DevicePolicyData policy = getUserData(userHandle);
4800 policy.mFailedPasswordAttempts++;
4801 saveSettingsLocked(userHandle);
4803 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4804 userHandle, /* parent */ false);
4805 int max = strictestAdmin != null
4806 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4807 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4808 // Wipe the user/profile associated with the policy that was violated. This
4809 // is not necessarily calling user: if the policy that fired was from a
4810 // managed profile rather than the main user profile, we wipe former only.
4812 identifier = strictestAdmin.getUserHandle().getIdentifier();
4815 sendAdminCommandForLockscreenPoliciesLocked(
4816 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
4817 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4821 // Call without holding lock.
4822 wipeDeviceNoLock(false, identifier,
4823 "reportFailedPasswordAttempt()");
4826 mInjector.binderRestoreCallingIdentity(ident);
4829 if (mInjector.securityLogIsLoggingEnabled()) {
4830 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4831 /*method strength*/ 1);
4836 public void reportSuccessfulPasswordAttempt(int userHandle) {
4837 enforceFullCrossUsersPermission(userHandle);
4838 mContext.enforceCallingOrSelfPermission(
4839 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4841 synchronized (this) {
4842 DevicePolicyData policy = getUserData(userHandle);
4843 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
4844 long ident = mInjector.binderClearCallingIdentity();
4846 policy.mFailedPasswordAttempts = 0;
4847 policy.mPasswordOwner = -1;
4848 saveSettingsLocked(userHandle);
4850 sendAdminCommandForLockscreenPoliciesLocked(
4851 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
4852 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4855 mInjector.binderRestoreCallingIdentity(ident);
4860 if (mInjector.securityLogIsLoggingEnabled()) {
4861 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4862 /*method strength*/ 1);
4867 public void reportFailedFingerprintAttempt(int userHandle) {
4868 enforceFullCrossUsersPermission(userHandle);
4869 mContext.enforceCallingOrSelfPermission(
4870 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4871 if (mInjector.securityLogIsLoggingEnabled()) {
4872 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4873 /*method strength*/ 0);
4878 public void reportSuccessfulFingerprintAttempt(int userHandle) {
4879 enforceFullCrossUsersPermission(userHandle);
4880 mContext.enforceCallingOrSelfPermission(
4881 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4882 if (mInjector.securityLogIsLoggingEnabled()) {
4883 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4884 /*method strength*/ 0);
4889 public void reportKeyguardDismissed(int userHandle) {
4890 enforceFullCrossUsersPermission(userHandle);
4891 mContext.enforceCallingOrSelfPermission(
4892 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4894 if (mInjector.securityLogIsLoggingEnabled()) {
4895 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
4900 public void reportKeyguardSecured(int userHandle) {
4901 enforceFullCrossUsersPermission(userHandle);
4902 mContext.enforceCallingOrSelfPermission(
4903 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4905 if (mInjector.securityLogIsLoggingEnabled()) {
4906 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
4911 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
4912 String exclusionList) {
4916 synchronized(this) {
4917 Preconditions.checkNotNull(who, "ComponentName is null");
4919 // Only check if system user has set global proxy. We don't allow other users to set it.
4920 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4921 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4922 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
4924 // Scan through active admins and find if anyone has already
4925 // set the global proxy.
4926 Set<ComponentName> compSet = policy.mAdminMap.keySet();
4927 for (ComponentName component : compSet) {
4928 ActiveAdmin ap = policy.mAdminMap.get(component);
4929 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
4930 // Another admin already sets the global proxy
4931 // Return it to the caller.
4936 // If the user is not system, don't set the global proxy. Fail silently.
4937 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
4938 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
4939 + UserHandle.getCallingUserId() + " is not permitted.");
4942 if (proxySpec == null) {
4943 admin.specifiesGlobalProxy = false;
4944 admin.globalProxySpec = null;
4945 admin.globalProxyExclusionList = null;
4948 admin.specifiesGlobalProxy = true;
4949 admin.globalProxySpec = proxySpec;
4950 admin.globalProxyExclusionList = exclusionList;
4953 // Reset the global proxy accordingly
4954 // Do this using system permissions, as apps cannot write to secure settings
4955 long origId = mInjector.binderClearCallingIdentity();
4957 resetGlobalProxyLocked(policy);
4959 mInjector.binderRestoreCallingIdentity(origId);
4966 public ComponentName getGlobalProxyAdmin(int userHandle) {
4970 enforceFullCrossUsersPermission(userHandle);
4971 synchronized(this) {
4972 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4973 // Scan through active admins and find if anyone has already
4974 // set the global proxy.
4975 final int N = policy.mAdminList.size();
4976 for (int i = 0; i < N; i++) {
4977 ActiveAdmin ap = policy.mAdminList.get(i);
4978 if (ap.specifiesGlobalProxy) {
4979 // Device admin sets the global proxy
4980 // Return it to the caller.
4981 return ap.info.getComponent();
4985 // No device admin sets the global proxy.
4990 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
4991 synchronized (this) {
4992 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4994 long token = mInjector.binderClearCallingIdentity();
4996 ConnectivityManager connectivityManager = (ConnectivityManager)
4997 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4998 connectivityManager.setGlobalProxy(proxyInfo);
5000 mInjector.binderRestoreCallingIdentity(token);
5004 private void resetGlobalProxyLocked(DevicePolicyData policy) {
5005 final int N = policy.mAdminList.size();
5006 for (int i = 0; i < N; i++) {
5007 ActiveAdmin ap = policy.mAdminList.get(i);
5008 if (ap.specifiesGlobalProxy) {
5009 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5013 // No device admins defining global proxies - reset global proxy settings to none
5014 saveGlobalProxyLocked(null, null);
5017 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5018 if (exclusionList == null) {
5021 if (proxySpec == null) {
5024 // Remove white spaces
5025 proxySpec = proxySpec.trim();
5026 String data[] = proxySpec.split(":");
5027 int proxyPort = 8080;
5028 if (data.length > 1) {
5030 proxyPort = Integer.parseInt(data[1]);
5031 } catch (NumberFormatException e) {}
5033 exclusionList = exclusionList.trim();
5035 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5036 if (!proxyProperties.isValid()) {
5037 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5040 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5041 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5042 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5047 * Set the storage encryption request for a single admin. Returns the new total request
5048 * status (for all admins).
5051 public int setStorageEncryption(ComponentName who, boolean encrypt) {
5053 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5055 Preconditions.checkNotNull(who, "ComponentName is null");
5056 final int userHandle = UserHandle.getCallingUserId();
5057 synchronized (this) {
5058 // Check for permissions
5059 // Only system user can set storage encryption
5060 if (userHandle != UserHandle.USER_SYSTEM) {
5061 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5062 + UserHandle.getCallingUserId() + " is not permitted.");
5066 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5067 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5069 // Quick exit: If the filesystem does not support encryption, we can exit early.
5070 if (!isEncryptionSupported()) {
5071 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5074 // (1) Record the value for the admin so it's sticky
5075 if (ap.encryptionRequested != encrypt) {
5076 ap.encryptionRequested = encrypt;
5077 saveSettingsLocked(userHandle);
5080 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5081 // (2) Compute "max" for all admins
5082 boolean newRequested = false;
5083 final int N = policy.mAdminList.size();
5084 for (int i = 0; i < N; i++) {
5085 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5088 // Notify OS of new request
5089 setEncryptionRequested(newRequested);
5091 // Return the new global request status
5093 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5094 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5099 * Get the current storage encryption request status for a given admin, or aggregate of all
5103 public boolean getStorageEncryption(ComponentName who, int userHandle) {
5107 enforceFullCrossUsersPermission(userHandle);
5108 synchronized (this) {
5109 // Check for permissions if a particular caller is specified
5111 // When checking for a single caller, status is based on caller's request
5112 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5113 return ap != null ? ap.encryptionRequested : false;
5116 // If no particular caller is specified, return the aggregate set of requests.
5117 // This is short circuited by returning true on the first hit.
5118 DevicePolicyData policy = getUserData(userHandle);
5119 final int N = policy.mAdminList.size();
5120 for (int i = 0; i < N; i++) {
5121 if (policy.mAdminList.get(i).encryptionRequested) {
5130 * Get the current encryption status of the device.
5133 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5135 // Ok to return current status.
5137 enforceFullCrossUsersPermission(userHandle);
5139 // It's not critical here, but let's make sure the package name is correct, in case
5140 // we start using it for different purposes.
5141 ensureCallerPackage(callerPackage);
5143 final ApplicationInfo ai;
5145 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5146 } catch (RemoteException e) {
5147 throw new SecurityException(e);
5150 boolean legacyApp = false;
5151 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5155 final int rawStatus = getEncryptionStatus();
5156 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5157 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5163 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
5165 private boolean isEncryptionSupported() {
5166 // Note, this can be implemented as
5167 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5168 // But is provided as a separate internal method if there's a faster way to do a
5169 // simple check for supported-or-not.
5170 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5174 * Hook to low-levels: Reporting the current status of encryption.
5175 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5176 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5177 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5178 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5179 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5181 private int getEncryptionStatus() {
5182 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5183 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5184 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5185 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5186 } else if (mInjector.storageManagerIsEncrypted()) {
5187 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5188 } else if (mInjector.storageManagerIsEncryptable()) {
5189 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5191 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5196 * Hook to low-levels: If needed, record the new admin setting for encryption.
5198 private void setEncryptionRequested(boolean encrypt) {
5202 * Set whether the screen capture is disabled for the user managed by the specified admin.
5205 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5209 Preconditions.checkNotNull(who, "ComponentName is null");
5210 final int userHandle = UserHandle.getCallingUserId();
5211 synchronized (this) {
5212 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5213 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5214 if (ap.disableScreenCapture != disabled) {
5215 ap.disableScreenCapture = disabled;
5216 saveSettingsLocked(userHandle);
5217 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5223 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5224 * active admin (if given admin is null).
5227 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5231 synchronized (this) {
5233 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5234 return (admin != null) ? admin.disableScreenCapture : false;
5237 DevicePolicyData policy = getUserData(userHandle);
5238 final int N = policy.mAdminList.size();
5239 for (int i = 0; i < N; i++) {
5240 ActiveAdmin admin = policy.mAdminList.get(i);
5241 if (admin.disableScreenCapture) {
5249 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5250 final boolean disabled) {
5251 mHandler.post(new Runnable() {
5255 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5256 } catch (RemoteException e) {
5257 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5264 * Set whether auto time is required by the specified admin (must be device owner).
5267 public void setAutoTimeRequired(ComponentName who, boolean required) {
5271 Preconditions.checkNotNull(who, "ComponentName is null");
5272 final int userHandle = UserHandle.getCallingUserId();
5273 synchronized (this) {
5274 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5275 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5276 if (admin.requireAutoTime != required) {
5277 admin.requireAutoTime = required;
5278 saveSettingsLocked(userHandle);
5282 // Turn AUTO_TIME on in settings if it is required
5284 long ident = mInjector.binderClearCallingIdentity();
5286 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5288 mInjector.binderRestoreCallingIdentity(ident);
5294 * Returns whether or not auto time is required by the device owner.
5297 public boolean getAutoTimeRequired() {
5301 synchronized (this) {
5302 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5303 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5308 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5312 Preconditions.checkNotNull(who, "ComponentName is null");
5313 // Allow setting this policy to true only if there is a split system user.
5314 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5315 throw new UnsupportedOperationException(
5316 "Cannot force ephemeral users on systems without split system user.");
5318 boolean removeAllUsers = false;
5319 synchronized (this) {
5320 final ActiveAdmin deviceOwner =
5321 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5322 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5323 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5324 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5325 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5326 removeAllUsers = forceEphemeralUsers;
5329 if (removeAllUsers) {
5330 long identitity = mInjector.binderClearCallingIdentity();
5332 mUserManagerInternal.removeAllUsers();
5334 mInjector.binderRestoreCallingIdentity(identitity);
5340 public boolean getForceEphemeralUsers(ComponentName who) {
5344 Preconditions.checkNotNull(who, "ComponentName is null");
5345 synchronized (this) {
5346 final ActiveAdmin deviceOwner =
5347 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5348 return deviceOwner.forceEphemeralUsers;
5352 private boolean isDeviceOwnerManagedSingleUserDevice() {
5353 synchronized (this) {
5354 if (!mOwners.hasDeviceOwner()) {
5358 final long callingIdentity = mInjector.binderClearCallingIdentity();
5360 if (mInjector.userManagerIsSplitSystemUser()) {
5361 // In split system user mode, only allow the case where the device owner is managing
5362 // the only non-system user of the device
5363 return (mUserManager.getUserCount() == 2
5364 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5366 return mUserManager.getUserCount() == 1;
5369 mInjector.binderRestoreCallingIdentity(callingIdentity);
5373 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5374 synchronized (this) {
5375 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5377 if (!isDeviceOwnerManagedSingleUserDevice()) {
5378 throw new SecurityException(
5379 "There should only be one user, managed by Device Owner");
5384 public boolean requestBugreport(ComponentName who) {
5388 Preconditions.checkNotNull(who, "ComponentName is null");
5389 ensureDeviceOwnerManagingSingleUser(who);
5391 if (mRemoteBugreportServiceIsActive.get()
5392 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5393 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5397 final long callingIdentity = mInjector.binderClearCallingIdentity();
5399 ActivityManagerNative.getDefault().requestBugReport(
5400 ActivityManager.BUGREPORT_OPTION_REMOTE);
5402 mRemoteBugreportServiceIsActive.set(true);
5403 mRemoteBugreportSharingAccepted.set(false);
5404 registerRemoteBugreportReceivers();
5405 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5406 RemoteBugreportUtils.buildNotification(mContext,
5407 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5408 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5409 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5411 } catch (RemoteException re) {
5412 // should never happen
5413 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5416 mInjector.binderRestoreCallingIdentity(callingIdentity);
5420 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5421 Intent intent = new Intent(action);
5422 intent.setComponent(mOwners.getDeviceOwnerComponent());
5423 if (extras != null) {
5424 intent.putExtras(extras);
5426 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5429 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5430 return mOwners.getDeviceOwnerRemoteBugreportUri();
5433 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5434 String bugreportHash) {
5435 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5438 private void registerRemoteBugreportReceivers() {
5440 IntentFilter filterFinished = new IntentFilter(
5441 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5442 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5443 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5444 } catch (IntentFilter.MalformedMimeTypeException e) {
5445 // should never happen, as setting a constant
5446 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5448 IntentFilter filterConsent = new IntentFilter();
5449 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5450 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5451 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5454 private void onBugreportFinished(Intent intent) {
5455 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5456 mRemoteBugreportServiceIsActive.set(false);
5457 Uri bugreportUri = intent.getData();
5458 String bugreportUriString = null;
5459 if (bugreportUri != null) {
5460 bugreportUriString = bugreportUri.toString();
5462 String bugreportHash = intent.getStringExtra(
5463 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5464 if (mRemoteBugreportSharingAccepted.get()) {
5465 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5466 mInjector.getNotificationManager().cancel(LOG_TAG,
5467 RemoteBugreportUtils.NOTIFICATION_ID);
5469 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5470 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5471 RemoteBugreportUtils.buildNotification(mContext,
5472 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5475 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5478 private void onBugreportFailed() {
5479 mRemoteBugreportServiceIsActive.set(false);
5480 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5481 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5482 mRemoteBugreportSharingAccepted.set(false);
5483 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5484 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5485 Bundle extras = new Bundle();
5486 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5487 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5488 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5489 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5490 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5493 private void onBugreportSharingAccepted() {
5494 mRemoteBugreportSharingAccepted.set(true);
5495 String bugreportUriString = null;
5496 String bugreportHash = null;
5497 synchronized (this) {
5498 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5499 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5501 if (bugreportUriString != null) {
5502 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5503 } else if (mRemoteBugreportServiceIsActive.get()) {
5504 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5505 RemoteBugreportUtils.buildNotification(mContext,
5506 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5511 private void onBugreportSharingDeclined() {
5512 if (mRemoteBugreportServiceIsActive.get()) {
5513 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5514 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5515 mRemoteBugreportServiceIsActive.set(false);
5516 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5517 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5519 mRemoteBugreportSharingAccepted.set(false);
5520 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5521 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5524 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5525 String bugreportHash) {
5526 ParcelFileDescriptor pfd = null;
5528 if (bugreportUriString == null) {
5529 throw new FileNotFoundException();
5531 Uri bugreportUri = Uri.parse(bugreportUriString);
5532 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5534 synchronized (this) {
5535 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5536 intent.setComponent(mOwners.getDeviceOwnerComponent());
5537 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5538 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5539 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
5541 LocalServices.getService(ActivityManagerInternal.class)
5542 .grantUriPermissionFromIntent(Process.SHELL_UID,
5543 mOwners.getDeviceOwnerComponent().getPackageName(),
5544 intent, mOwners.getDeviceOwnerUserId());
5545 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5547 } catch (FileNotFoundException e) {
5548 Bundle extras = new Bundle();
5549 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5550 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5551 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5557 } catch (IOException ex) {
5560 mRemoteBugreportSharingAccepted.set(false);
5561 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5566 * Disables all device cameras according to the specified admin.
5569 public void setCameraDisabled(ComponentName who, boolean disabled) {
5573 Preconditions.checkNotNull(who, "ComponentName is null");
5574 final int userHandle = mInjector.userHandleGetCallingUserId();
5575 synchronized (this) {
5576 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5577 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5578 if (ap.disableCamera != disabled) {
5579 ap.disableCamera = disabled;
5580 saveSettingsLocked(userHandle);
5583 // Tell the user manager that the restrictions have changed.
5584 pushUserRestrictions(userHandle);
5588 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5592 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5593 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5596 private boolean getCameraDisabled(ComponentName who, int userHandle,
5597 boolean mergeDeviceOwnerRestriction) {
5601 synchronized (this) {
5603 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5604 return (admin != null) ? admin.disableCamera : false;
5606 // First, see if DO has set it. If so, it's device-wide.
5607 if (mergeDeviceOwnerRestriction) {
5608 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5609 if (deviceOwner != null && deviceOwner.disableCamera) {
5614 // Then check each device admin on the user.
5615 DevicePolicyData policy = getUserData(userHandle);
5616 // Determine whether or not the device camera is disabled for any active admins.
5617 final int N = policy.mAdminList.size();
5618 for (int i = 0; i < N; i++) {
5619 ActiveAdmin admin = policy.mAdminList.get(i);
5620 if (admin.disableCamera) {
5629 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5633 Preconditions.checkNotNull(who, "ComponentName is null");
5634 final int userHandle = mInjector.userHandleGetCallingUserId();
5635 if (isManagedProfile(userHandle)) {
5637 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5639 which = which & PROFILE_KEYGUARD_FEATURES;
5642 synchronized (this) {
5643 ActiveAdmin ap = getActiveAdminForCallerLocked(
5644 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5645 if (ap.disabledKeyguardFeatures != which) {
5646 ap.disabledKeyguardFeatures = which;
5647 saveSettingsLocked(userHandle);
5653 * Gets the disabled state for features in keyguard for the given admin,
5654 * or the aggregate of all active admins if who is null.
5657 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5661 enforceFullCrossUsersPermission(userHandle);
5662 final long ident = mInjector.binderClearCallingIdentity();
5664 synchronized (this) {
5666 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5667 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5670 final List<ActiveAdmin> admins;
5671 if (!parent && isManagedProfile(userHandle)) {
5672 // If we are being asked about a managed profile, just return keyguard features
5673 // disabled by admins in the profile.
5674 admins = getUserDataUnchecked(userHandle).mAdminList;
5676 // Otherwise return those set by admins in the user and its profiles.
5677 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5680 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5681 final int N = admins.size();
5682 for (int i = 0; i < N; i++) {
5683 ActiveAdmin admin = admins.get(i);
5684 int userId = admin.getUserHandle().getIdentifier();
5685 boolean isRequestedUser = !parent && (userId == userHandle);
5686 if (isRequestedUser || !isManagedProfile(userId)) {
5687 // If we are being asked explicitly about this user
5688 // return all disabled features even if its a managed profile.
5689 which |= admin.disabledKeyguardFeatures;
5691 // Otherwise a managed profile is only allowed to disable
5692 // some features on the parent user.
5693 which |= (admin.disabledKeyguardFeatures
5694 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5700 mInjector.binderRestoreCallingIdentity(ident);
5705 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5709 Preconditions.checkNotNull(who, "ComponentName is null");
5710 Preconditions.checkNotNull(packageList, "packageList is null");
5711 final int userHandle = UserHandle.getCallingUserId();
5712 synchronized (this) {
5713 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5714 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5715 admin.keepUninstalledPackages = packageList;
5716 saveSettingsLocked(userHandle);
5717 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5722 public List<String> getKeepUninstalledPackages(ComponentName who) {
5723 Preconditions.checkNotNull(who, "ComponentName is null");
5727 // TODO In split system user mode, allow apps on user 0 to query the list
5728 synchronized (this) {
5729 // Check if this is the device owner who is calling
5730 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5731 return getKeepUninstalledPackagesLocked();
5735 private List<String> getKeepUninstalledPackagesLocked() {
5736 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5737 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5741 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5746 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5747 throw new IllegalArgumentException("Invalid component " + admin
5748 + " for device owner");
5750 synchronized (this) {
5751 enforceCanSetDeviceOwnerLocked(userId);
5752 if (getActiveAdminUncheckedLocked(admin, userId) == null
5753 || getUserData(userId).mRemovingAdmins.contains(admin)) {
5754 throw new IllegalArgumentException("Not active admin: " + admin);
5757 // Shutting down backup manager service permanently.
5758 long ident = mInjector.binderClearCallingIdentity();
5760 if (mInjector.getIBackupManager() != null) {
5761 mInjector.getIBackupManager()
5762 .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5764 } catch (RemoteException e) {
5765 throw new IllegalStateException("Failed deactivating backup service.", e);
5767 mInjector.binderRestoreCallingIdentity(ident);
5770 mOwners.setDeviceOwner(admin, ownerName, userId);
5771 mOwners.writeDeviceOwner();
5772 updateDeviceOwnerLocked();
5773 setDeviceOwnerSystemPropertyLocked();
5774 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5776 ident = mInjector.binderClearCallingIdentity();
5778 // TODO Send to system too?
5779 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5781 mInjector.binderRestoreCallingIdentity(ident);
5787 public boolean isDeviceOwner(ComponentName who, int userId) {
5788 synchronized (this) {
5789 return mOwners.hasDeviceOwner()
5790 && mOwners.getDeviceOwnerUserId() == userId
5791 && mOwners.getDeviceOwnerComponent().equals(who);
5795 public boolean isProfileOwner(ComponentName who, int userId) {
5796 final ComponentName profileOwner = getProfileOwner(userId);
5797 return who != null && who.equals(profileOwner);
5801 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5805 if (!callingUserOnly) {
5806 enforceManageUsers();
5808 synchronized (this) {
5809 if (!mOwners.hasDeviceOwner()) {
5812 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
5813 mOwners.getDeviceOwnerUserId()) {
5816 return mOwners.getDeviceOwnerComponent();
5821 public int getDeviceOwnerUserId() {
5823 return UserHandle.USER_NULL;
5825 enforceManageUsers();
5826 synchronized (this) {
5827 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
5832 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
5836 public String getDeviceOwnerName() {
5840 enforceManageUsers();
5841 synchronized (this) {
5842 if (!mOwners.hasDeviceOwner()) {
5845 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
5846 // Should setDeviceOwner/ProfileOwner still take a name?
5847 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
5848 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
5852 // Returns the active device owner or null if there is no device owner.
5854 ActiveAdmin getDeviceOwnerAdminLocked() {
5855 ComponentName component = mOwners.getDeviceOwnerComponent();
5856 if (component == null) {
5860 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
5861 final int n = policy.mAdminList.size();
5862 for (int i = 0; i < n; i++) {
5863 ActiveAdmin admin = policy.mAdminList.get(i);
5864 if (component.equals(admin.info.getComponent())) {
5868 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
5873 public void clearDeviceOwner(String packageName) {
5874 Preconditions.checkNotNull(packageName, "packageName is null");
5875 final int callingUid = mInjector.binderGetCallingUid();
5877 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
5878 UserHandle.getUserId(callingUid));
5879 if (uid != callingUid) {
5880 throw new SecurityException("Invalid packageName");
5882 } catch (NameNotFoundException e) {
5883 throw new SecurityException(e);
5885 synchronized (this) {
5886 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
5887 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
5888 if (!mOwners.hasDeviceOwner()
5889 || !deviceOwnerComponent.getPackageName().equals(packageName)
5890 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
5891 throw new SecurityException(
5892 "clearDeviceOwner can only be called by the device owner");
5894 enforceUserUnlocked(deviceOwnerUserId);
5896 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
5897 long ident = mInjector.binderClearCallingIdentity();
5899 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
5900 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
5902 mInjector.binderRestoreCallingIdentity(ident);
5907 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
5908 if (admin != null) {
5909 admin.disableCamera = false;
5910 admin.userRestrictions = null;
5911 admin.forceEphemeralUsers = false;
5912 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
5914 clearUserPoliciesLocked(userId);
5916 mOwners.clearDeviceOwner();
5917 mOwners.writeDeviceOwner();
5918 updateDeviceOwnerLocked();
5919 disableSecurityLoggingIfNotCompliant();
5921 // Reactivate backup service.
5922 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
5923 } catch (RemoteException e) {
5924 throw new IllegalStateException("Failed reactivating backup service.", e);
5929 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
5934 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
5935 throw new IllegalArgumentException("Component " + who
5936 + " not installed for userId:" + userHandle);
5938 synchronized (this) {
5939 enforceCanSetProfileOwnerLocked(userHandle);
5941 if (getActiveAdminUncheckedLocked(who, userHandle) == null
5942 || getUserData(userHandle).mRemovingAdmins.contains(who)) {
5943 throw new IllegalArgumentException("Not active admin: " + who);
5946 mOwners.setProfileOwner(who, ownerName, userHandle);
5947 mOwners.writeProfileOwner(userHandle);
5953 public void clearProfileOwner(ComponentName who) {
5957 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
5958 final int userId = callingUser.getIdentifier();
5959 enforceNotManagedProfile(userId, "clear profile owner");
5960 enforceUserUnlocked(userId);
5961 // Check if this is the profile owner who is calling
5962 final ActiveAdmin admin =
5963 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5964 synchronized (this) {
5965 final long ident = mInjector.binderClearCallingIdentity();
5967 clearProfileOwnerLocked(admin, userId);
5968 removeActiveAdminLocked(who, userId);
5970 mInjector.binderRestoreCallingIdentity(ident);
5975 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
5976 if (admin != null) {
5977 admin.disableCamera = false;
5978 admin.userRestrictions = null;
5980 clearUserPoliciesLocked(userId);
5981 mOwners.removeProfileOwner(userId);
5982 mOwners.writeProfileOwner(userId);
5986 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
5987 Preconditions.checkNotNull(who, "ComponentName is null");
5992 synchronized (this) {
5993 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5994 long token = mInjector.binderClearCallingIdentity();
5996 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
5998 mInjector.binderRestoreCallingIdentity(token);
6004 public CharSequence getDeviceOwnerLockScreenInfo() {
6005 return mLockPatternUtils.getDeviceOwnerInfo();
6008 private void clearUserPoliciesLocked(int userId) {
6009 // Reset some of the user-specific policies
6010 DevicePolicyData policy = getUserData(userId);
6011 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6012 policy.mDelegatedCertInstallerPackage = null;
6013 policy.mApplicationRestrictionsManagingPackage = null;
6014 policy.mStatusBarDisabled = false;
6015 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6016 saveSettingsLocked(userId);
6019 mIPackageManager.updatePermissionFlagsForAllApps(
6020 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6021 0 /* flagValues */, userId);
6022 pushUserRestrictions(userId);
6023 } catch (RemoteException re) {
6024 // Shouldn't happen.
6029 public boolean hasUserSetupCompleted() {
6030 return hasUserSetupCompleted(UserHandle.getCallingUserId());
6033 private boolean hasUserSetupCompleted(int userHandle) {
6037 return getUserData(userHandle).mUserSetupComplete;
6041 public int getUserProvisioningState() {
6043 return DevicePolicyManager.STATE_USER_UNMANAGED;
6045 int userHandle = mInjector.userHandleGetCallingUserId();
6046 return getUserProvisioningState(userHandle);
6049 private int getUserProvisioningState(int userHandle) {
6050 return getUserData(userHandle).mUserProvisioningState;
6054 public void setUserProvisioningState(int newState, int userHandle) {
6059 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6060 && getManagedUserId(userHandle) == -1) {
6061 // No managed device, user or profile, so setting provisioning state makes no sense.
6062 throw new IllegalStateException("Not allowed to change provisioning state unless a "
6063 + "device or profile owner is set.");
6066 synchronized (this) {
6067 boolean transitionCheckNeeded = true;
6069 // Calling identity/permission checks.
6070 final int callingUid = mInjector.binderGetCallingUid();
6071 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6072 // ADB shell can only move directly from un-managed to finalized as part of directly
6073 // setting profile-owner or device-owner.
6074 if (getUserProvisioningState(userHandle) !=
6075 DevicePolicyManager.STATE_USER_UNMANAGED
6076 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6077 throw new IllegalStateException("Not allowed to change provisioning state "
6078 + "unless current provisioning state is unmanaged, and new state is "
6081 transitionCheckNeeded = false;
6083 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6084 enforceCanManageProfileAndDeviceOwners();
6087 final DevicePolicyData policyData = getUserData(userHandle);
6088 if (transitionCheckNeeded) {
6089 // Optional state transition check for non-ADB case.
6090 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6092 policyData.mUserProvisioningState = newState;
6093 saveSettingsLocked(userHandle);
6097 private void checkUserProvisioningStateTransition(int currentState, int newState) {
6098 // Valid transitions for normal use-cases.
6099 switch (currentState) {
6100 case DevicePolicyManager.STATE_USER_UNMANAGED:
6101 // Can move to any state from unmanaged (except itself as an edge case)..
6102 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6106 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6107 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6108 // Can only move to finalized from these states.
6109 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6113 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6114 // Current user has a managed-profile, but current user is not managed, so
6115 // rather than moving to finalized state, go back to unmanaged once
6116 // profile provisioning is complete.
6117 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6121 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6122 // Cannot transition out of finalized.
6126 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6127 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6128 + "from state [" + currentState + "]");
6132 public void setProfileEnabled(ComponentName who) {
6136 Preconditions.checkNotNull(who, "ComponentName is null");
6137 synchronized (this) {
6138 // Check if this is the profile owner who is calling
6139 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6140 final int userId = UserHandle.getCallingUserId();
6141 enforceManagedProfile(userId, "enable the profile");
6143 long id = mInjector.binderClearCallingIdentity();
6145 mUserManager.setUserEnabled(userId);
6146 UserInfo parent = mUserManager.getProfileParent(userId);
6147 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6148 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6149 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6150 Intent.FLAG_RECEIVER_FOREGROUND);
6151 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6153 mInjector.binderRestoreCallingIdentity(id);
6159 public void setProfileName(ComponentName who, String profileName) {
6160 Preconditions.checkNotNull(who, "ComponentName is null");
6161 int userId = UserHandle.getCallingUserId();
6162 // Check if this is the profile owner (includes device owner).
6163 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6165 long id = mInjector.binderClearCallingIdentity();
6167 mUserManager.setUserName(userId, profileName);
6169 mInjector.binderRestoreCallingIdentity(id);
6174 public ComponentName getProfileOwner(int userHandle) {
6179 synchronized (this) {
6180 return mOwners.getProfileOwnerComponent(userHandle);
6184 // Returns the active profile owner for this user or null if the current user has no
6187 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6188 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6189 if (profileOwner == null) {
6192 DevicePolicyData policy = getUserData(userHandle);
6193 final int n = policy.mAdminList.size();
6194 for (int i = 0; i < n; i++) {
6195 ActiveAdmin admin = policy.mAdminList.get(i);
6196 if (profileOwner.equals(admin.info.getComponent())) {
6204 public String getProfileOwnerName(int userHandle) {
6208 enforceManageUsers();
6209 ComponentName profileOwner = getProfileOwner(userHandle);
6210 if (profileOwner == null) {
6213 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6217 * Canonical name for a given package.
6219 private String getApplicationLabel(String packageName, int userHandle) {
6220 long token = mInjector.binderClearCallingIdentity();
6222 final Context userContext;
6224 UserHandle handle = new UserHandle(userHandle);
6225 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6226 } catch (PackageManager.NameNotFoundException nnfe) {
6227 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6230 ApplicationInfo appInfo = userContext.getApplicationInfo();
6231 CharSequence result = null;
6232 if (appInfo != null) {
6233 PackageManager pm = userContext.getPackageManager();
6234 result = pm.getApplicationLabel(appInfo);
6236 return result != null ? result.toString() : null;
6238 mInjector.binderRestoreCallingIdentity(token);
6243 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6245 * The profile owner can only be set before the user setup phase has completed,
6248 * - adb if there are not accounts.
6250 private void enforceCanSetProfileOwnerLocked(int userHandle) {
6251 UserInfo info = getUserInfo(userHandle);
6253 // User doesn't exist.
6254 throw new IllegalArgumentException(
6255 "Attempted to set profile owner for invalid userId: " + userHandle);
6257 if (info.isGuest()) {
6258 throw new IllegalStateException("Cannot set a profile owner on a guest");
6260 if (mOwners.hasProfileOwner(userHandle)) {
6261 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6262 + "is already set.");
6264 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6265 throw new IllegalStateException("Trying to set the profile owner, but the user "
6266 + "already has a device owner.");
6268 int callingUid = mInjector.binderGetCallingUid();
6269 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6270 if (hasUserSetupCompleted(userHandle) &&
6271 AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) {
6272 throw new IllegalStateException("Not allowed to set the profile owner because "
6273 + "there are already some accounts on the profile");
6277 enforceCanManageProfileAndDeviceOwners();
6278 if (hasUserSetupCompleted(userHandle) && !isCallerWithSystemUid()) {
6279 throw new IllegalStateException("Cannot set the profile owner on a user which is "
6280 + "already set-up");
6285 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6288 private void enforceCanSetDeviceOwnerLocked(int userId) {
6289 int callingUid = mInjector.binderGetCallingUid();
6290 boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6292 enforceCanManageProfileAndDeviceOwners();
6295 final int code = checkSetDeviceOwnerPreCondition(userId, isAdb);
6299 case CODE_HAS_DEVICE_OWNER:
6300 throw new IllegalStateException(
6301 "Trying to set the device owner, but device owner is already set.");
6302 case CODE_USER_HAS_PROFILE_OWNER:
6303 throw new IllegalStateException("Trying to set the device owner, but the user "
6304 + "already has a profile owner.");
6305 case CODE_USER_NOT_RUNNING:
6306 throw new IllegalStateException("User not running: " + userId);
6307 case CODE_NOT_SYSTEM_USER:
6308 throw new IllegalStateException("User is not system user");
6309 case CODE_USER_SETUP_COMPLETED:
6310 throw new IllegalStateException(
6311 "Cannot set the device owner if the device is already set-up");
6312 case CODE_NONSYSTEM_USER_EXISTS:
6313 throw new IllegalStateException("Not allowed to set the device owner because there "
6314 + "are already several users on the device");
6315 case CODE_ACCOUNTS_NOT_EMPTY:
6316 throw new IllegalStateException("Not allowed to set the device owner because there "
6317 + "are already some accounts on the device");
6319 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6323 private void enforceUserUnlocked(int userId) {
6324 // Since we're doing this operation on behalf of an app, we only
6325 // want to use the actual "unlocked" state.
6326 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6327 "User must be running and unlocked");
6330 private void enforceUserUnlocked(int userId, boolean parent) {
6332 enforceUserUnlocked(getProfileParentId(userId));
6334 enforceUserUnlocked(userId);
6338 private void enforceManageUsers() {
6339 final int callingUid = mInjector.binderGetCallingUid();
6340 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6341 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6345 private void enforceFullCrossUsersPermission(int userHandle) {
6346 enforceSystemUserOrPermission(userHandle,
6347 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6350 private void enforceCrossUsersPermission(int userHandle) {
6351 enforceSystemUserOrPermission(userHandle,
6352 android.Manifest.permission.INTERACT_ACROSS_USERS);
6355 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6356 if (userHandle < 0) {
6357 throw new IllegalArgumentException("Invalid userId " + userHandle);
6359 final int callingUid = mInjector.binderGetCallingUid();
6360 if (userHandle == UserHandle.getUserId(callingUid)) {
6363 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6364 mContext.enforceCallingOrSelfPermission(permission,
6365 "Must be system or have " + permission + " permission");
6369 private void enforceManagedProfile(int userHandle, String message) {
6370 if(!isManagedProfile(userHandle)) {
6371 throw new SecurityException("You can not " + message + " outside a managed profile.");
6375 private void enforceNotManagedProfile(int userHandle, String message) {
6376 if(isManagedProfile(userHandle)) {
6377 throw new SecurityException("You can not " + message + " for a managed profile.");
6381 private void ensureCallerPackage(@Nullable String packageName) {
6382 if (packageName == null) {
6383 Preconditions.checkState(isCallerWithSystemUid(),
6384 "Only caller can omit package name");
6386 final int callingUid = mInjector.binderGetCallingUid();
6387 final int userId = mInjector.userHandleGetCallingUserId();
6389 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6390 packageName, 0, userId);
6391 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6392 } catch (RemoteException e) {
6398 private boolean isCallerWithSystemUid() {
6399 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6402 private int getProfileParentId(int userHandle) {
6403 final long ident = mInjector.binderClearCallingIdentity();
6405 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6406 return parentUser != null ? parentUser.id : userHandle;
6408 mInjector.binderRestoreCallingIdentity(ident);
6412 private int getCredentialOwner(int userHandle, boolean parent) {
6413 final long ident = mInjector.binderClearCallingIdentity();
6416 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6417 if (parentProfile != null) {
6418 userHandle = parentProfile.id;
6421 return mUserManager.getCredentialOwnerProfile(userHandle);
6423 mInjector.binderRestoreCallingIdentity(ident);
6427 private boolean isManagedProfile(int userHandle) {
6428 return getUserInfo(userHandle).isManagedProfile();
6431 private void enableIfNecessary(String packageName, int userId) {
6433 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6434 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6436 if (ai.enabledSetting
6437 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6438 mIPackageManager.setApplicationEnabledSetting(packageName,
6439 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6440 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6442 } catch (RemoteException e) {
6447 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6448 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6449 != PackageManager.PERMISSION_GRANTED) {
6451 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6452 + mInjector.binderGetCallingPid()
6453 + ", uid=" + mInjector.binderGetCallingUid());
6457 synchronized (this) {
6458 pw.println("Current Device Policy Manager state:");
6459 mOwners.dump(" ", pw);
6460 int userCount = mUserData.size();
6461 for (int u = 0; u < userCount; u++) {
6462 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6464 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6465 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6466 final int N = policy.mAdminList.size();
6467 for (int i=0; i<N; i++) {
6468 ActiveAdmin ap = policy.mAdminList.get(i);
6470 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6475 if (!policy.mRemovingAdmins.isEmpty()) {
6476 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6477 + policy.mRemovingAdmins);
6481 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6484 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6488 private String getEncryptionStatusName(int encryptionStatus) {
6489 switch (encryptionStatus) {
6490 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6492 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6493 return "block default key";
6494 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6496 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6498 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6499 return "unsupported";
6500 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6501 return "activating";
6508 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6509 ComponentName activity) {
6510 Preconditions.checkNotNull(who, "ComponentName is null");
6511 final int userHandle = UserHandle.getCallingUserId();
6512 synchronized (this) {
6513 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6515 long id = mInjector.binderClearCallingIdentity();
6517 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6518 } catch (RemoteException re) {
6521 mInjector.binderRestoreCallingIdentity(id);
6527 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6528 Preconditions.checkNotNull(who, "ComponentName is null");
6529 final int userHandle = UserHandle.getCallingUserId();
6530 synchronized (this) {
6531 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6533 long id = mInjector.binderClearCallingIdentity();
6535 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6536 } catch (RemoteException re) {
6539 mInjector.binderRestoreCallingIdentity(id);
6545 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6546 String packageName) {
6547 Preconditions.checkNotNull(admin, "ComponentName is null");
6549 final int userHandle = mInjector.userHandleGetCallingUserId();
6550 synchronized (this) {
6551 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6552 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6555 DevicePolicyData policy = getUserData(userHandle);
6556 policy.mApplicationRestrictionsManagingPackage = packageName;
6557 saveSettingsLocked(userHandle);
6563 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6564 Preconditions.checkNotNull(admin, "ComponentName is null");
6566 final int userHandle = mInjector.userHandleGetCallingUserId();
6567 synchronized (this) {
6568 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6569 DevicePolicyData policy = getUserData(userHandle);
6570 return policy.mApplicationRestrictionsManagingPackage;
6575 public boolean isCallerApplicationRestrictionsManagingPackage() {
6576 final int callingUid = mInjector.binderGetCallingUid();
6577 final int userHandle = UserHandle.getUserId(callingUid);
6578 synchronized (this) {
6579 final DevicePolicyData policy = getUserData(userHandle);
6580 if (policy.mApplicationRestrictionsManagingPackage == null) {
6585 int uid = mContext.getPackageManager().getPackageUidAsUser(
6586 policy.mApplicationRestrictionsManagingPackage, userHandle);
6587 return uid == callingUid;
6588 } catch (NameNotFoundException e) {
6594 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6596 synchronized (this) {
6597 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6599 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6600 throw new SecurityException(
6601 "No admin component given, and caller cannot manage application restrictions "
6602 + "for other apps.");
6607 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6608 enforceCanManageApplicationRestrictions(who);
6610 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6611 final long id = mInjector.binderClearCallingIdentity();
6613 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6615 mInjector.binderRestoreCallingIdentity(id);
6620 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6621 PersistableBundle args, boolean parent) {
6625 Preconditions.checkNotNull(admin, "admin is null");
6626 Preconditions.checkNotNull(agent, "agent is null");
6627 final int userHandle = UserHandle.getCallingUserId();
6628 synchronized (this) {
6629 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6630 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6631 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6632 saveSettingsLocked(userHandle);
6637 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6638 ComponentName agent, int userHandle, boolean parent) {
6642 Preconditions.checkNotNull(agent, "agent null");
6643 enforceFullCrossUsersPermission(userHandle);
6645 synchronized (this) {
6646 final String componentName = agent.flattenToString();
6647 if (admin != null) {
6648 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6649 if (ap == null) return null;
6650 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6651 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6652 List<PersistableBundle> result = new ArrayList<>();
6653 result.add(trustAgentInfo.options);
6657 // Return strictest policy for this user and profiles that are visible from this user.
6658 List<PersistableBundle> result = null;
6659 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6660 // of the options. If any admin doesn't have options, discard options for the rest
6662 List<ActiveAdmin> admins =
6663 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6664 boolean allAdminsHaveOptions = true;
6665 final int N = admins.size();
6666 for (int i = 0; i < N; i++) {
6667 final ActiveAdmin active = admins.get(i);
6669 final boolean disablesTrust = (active.disabledKeyguardFeatures
6670 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6671 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6672 if (info != null && info.options != null && !info.options.isEmpty()) {
6673 if (disablesTrust) {
6674 if (result == null) {
6675 result = new ArrayList<>();
6677 result.add(info.options);
6679 Log.w(LOG_TAG, "Ignoring admin " + active.info
6680 + " because it has trust options but doesn't declare "
6681 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6683 } else if (disablesTrust) {
6684 allAdminsHaveOptions = false;
6688 return allAdminsHaveOptions ? result : null;
6693 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6694 Preconditions.checkNotNull(who, "ComponentName is null");
6695 synchronized (this) {
6696 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6698 int userHandle = UserHandle.getCallingUserId();
6699 DevicePolicyData userData = getUserData(userHandle);
6700 userData.mRestrictionsProvider = permissionProvider;
6701 saveSettingsLocked(userHandle);
6706 public ComponentName getRestrictionsProvider(int userHandle) {
6707 synchronized (this) {
6708 if (!isCallerWithSystemUid()) {
6709 throw new SecurityException("Only the system can query the permission provider");
6711 DevicePolicyData userData = getUserData(userHandle);
6712 return userData != null ? userData.mRestrictionsProvider : null;
6717 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6718 Preconditions.checkNotNull(who, "ComponentName is null");
6719 int callingUserId = UserHandle.getCallingUserId();
6720 synchronized (this) {
6721 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6723 long id = mInjector.binderClearCallingIdentity();
6725 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6726 if (parent == null) {
6727 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6731 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6732 mIPackageManager.addCrossProfileIntentFilter(
6733 filter, who.getPackageName(), callingUserId, parent.id, 0);
6735 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6736 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6737 parent.id, callingUserId, 0);
6739 } catch (RemoteException re) {
6742 mInjector.binderRestoreCallingIdentity(id);
6748 public void clearCrossProfileIntentFilters(ComponentName who) {
6749 Preconditions.checkNotNull(who, "ComponentName is null");
6750 int callingUserId = UserHandle.getCallingUserId();
6751 synchronized (this) {
6752 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6753 long id = mInjector.binderClearCallingIdentity();
6755 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6756 if (parent == null) {
6757 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6761 // Removing those that go from the managed profile to the parent.
6762 mIPackageManager.clearCrossProfileIntentFilters(
6763 callingUserId, who.getPackageName());
6764 // And those that go from the parent to the managed profile.
6765 // If we want to support multiple managed profiles, we will have to only remove
6766 // those that have callingUserId as their target.
6767 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6768 } catch (RemoteException re) {
6771 mInjector.binderRestoreCallingIdentity(id);
6777 * @return true if all packages in enabledPackages are either in the list
6778 * permittedList or are a system app.
6780 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6781 List<String> permittedList, int userIdToCheck) {
6782 long id = mInjector.binderClearCallingIdentity();
6784 // If we have an enabled packages list for a managed profile the packages
6785 // we should check are installed for the parent user.
6786 UserInfo user = getUserInfo(userIdToCheck);
6787 if (user.isManagedProfile()) {
6788 userIdToCheck = user.profileGroupId;
6791 for (String enabledPackage : enabledPackages) {
6792 boolean systemService = false;
6794 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
6795 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
6796 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6797 } catch (RemoteException e) {
6798 Log.i(LOG_TAG, "Can't talk to package managed", e);
6800 if (!systemService && !permittedList.contains(enabledPackage)) {
6805 mInjector.binderRestoreCallingIdentity(id);
6810 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
6811 // Not using AccessibilityManager.getInstance because that guesses
6812 // at the user you require based on callingUid and caches for a given
6814 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
6815 IAccessibilityManager service = iBinder == null
6816 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
6817 return new AccessibilityManager(mContext, service, userId);
6821 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
6825 Preconditions.checkNotNull(who, "ComponentName is null");
6827 if (packageList != null) {
6828 int userId = UserHandle.getCallingUserId();
6829 List<AccessibilityServiceInfo> enabledServices = null;
6830 long id = mInjector.binderClearCallingIdentity();
6832 UserInfo user = getUserInfo(userId);
6833 if (user.isManagedProfile()) {
6834 userId = user.profileGroupId;
6836 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
6837 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
6838 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
6840 mInjector.binderRestoreCallingIdentity(id);
6843 if (enabledServices != null) {
6844 List<String> enabledPackages = new ArrayList<String>();
6845 for (AccessibilityServiceInfo service : enabledServices) {
6846 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
6848 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6850 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
6851 + "because it contains already enabled accesibility services.");
6857 synchronized (this) {
6858 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6859 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6860 admin.permittedAccessiblityServices = packageList;
6861 saveSettingsLocked(UserHandle.getCallingUserId());
6867 public List getPermittedAccessibilityServices(ComponentName who) {
6871 Preconditions.checkNotNull(who, "ComponentName is null");
6873 synchronized (this) {
6874 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6875 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6876 return admin.permittedAccessiblityServices;
6881 public List getPermittedAccessibilityServicesForUser(int userId) {
6885 synchronized (this) {
6886 List<String> result = null;
6887 // If we have multiple profiles we return the intersection of the
6888 // permitted lists. This can happen in cases where we have a device
6889 // and profile owner.
6890 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
6891 for (int profileId : profileIds) {
6892 // Just loop though all admins, only device or profiles
6893 // owners can have permitted lists set.
6894 DevicePolicyData policy = getUserDataUnchecked(profileId);
6895 final int N = policy.mAdminList.size();
6896 for (int j = 0; j < N; j++) {
6897 ActiveAdmin admin = policy.mAdminList.get(j);
6898 List<String> fromAdmin = admin.permittedAccessiblityServices;
6899 if (fromAdmin != null) {
6900 if (result == null) {
6901 result = new ArrayList<>(fromAdmin);
6903 result.retainAll(fromAdmin);
6909 // If we have a permitted list add all system accessibility services.
6910 if (result != null) {
6911 long id = mInjector.binderClearCallingIdentity();
6913 UserInfo user = getUserInfo(userId);
6914 if (user.isManagedProfile()) {
6915 userId = user.profileGroupId;
6917 AccessibilityManager accessibilityManager =
6918 getAccessibilityManagerForUser(userId);
6919 List<AccessibilityServiceInfo> installedServices =
6920 accessibilityManager.getInstalledAccessibilityServiceList();
6922 if (installedServices != null) {
6923 for (AccessibilityServiceInfo service : installedServices) {
6924 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
6925 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
6926 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6927 result.add(serviceInfo.packageName);
6932 mInjector.binderRestoreCallingIdentity(id);
6941 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
6946 Preconditions.checkNotNull(who, "ComponentName is null");
6947 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
6948 if (!isCallerWithSystemUid()){
6949 throw new SecurityException(
6950 "Only the system can query if an accessibility service is disabled by admin");
6952 synchronized (this) {
6953 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6954 if (admin == null) {
6957 if (admin.permittedAccessiblityServices == null) {
6960 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
6961 admin.permittedAccessiblityServices, userHandle);
6965 private boolean checkCallerIsCurrentUserOrProfile() {
6966 int callingUserId = UserHandle.getCallingUserId();
6967 long token = mInjector.binderClearCallingIdentity();
6969 UserInfo currentUser;
6970 UserInfo callingUser = getUserInfo(callingUserId);
6972 currentUser = mInjector.getIActivityManager().getCurrentUser();
6973 } catch (RemoteException e) {
6974 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
6978 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
6979 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
6980 + "of a user that isn't the foreground user.");
6983 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
6984 Slog.e(LOG_TAG, "Cannot set permitted input methods "
6985 + "of a user that isn't the foreground user.");
6989 mInjector.binderRestoreCallingIdentity(token);
6995 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
6999 Preconditions.checkNotNull(who, "ComponentName is null");
7001 // TODO When InputMethodManager supports per user calls remove
7002 // this restriction.
7003 if (!checkCallerIsCurrentUserOrProfile()) {
7007 if (packageList != null) {
7008 // InputMethodManager fetches input methods for current user.
7009 // So this can only be set when calling user is the current user
7010 // or parent is current user in case of managed profiles.
7011 InputMethodManager inputMethodManager =
7012 mContext.getSystemService(InputMethodManager.class);
7013 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7015 if (enabledImes != null) {
7016 List<String> enabledPackages = new ArrayList<String>();
7017 for (InputMethodInfo ime : enabledImes) {
7018 enabledPackages.add(ime.getPackageName());
7020 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7021 mInjector.binderGetCallingUserHandle().getIdentifier())) {
7022 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7023 + "because it contains already enabled input method.");
7029 synchronized (this) {
7030 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7031 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7032 admin.permittedInputMethods = packageList;
7033 saveSettingsLocked(UserHandle.getCallingUserId());
7039 public List getPermittedInputMethods(ComponentName who) {
7043 Preconditions.checkNotNull(who, "ComponentName is null");
7045 synchronized (this) {
7046 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7047 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7048 return admin.permittedInputMethods;
7053 public List getPermittedInputMethodsForCurrentUser() {
7054 UserInfo currentUser;
7056 currentUser = mInjector.getIActivityManager().getCurrentUser();
7057 } catch (RemoteException e) {
7058 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7059 // Activity managed is dead, just allow all IMEs
7063 int userId = currentUser.id;
7064 synchronized (this) {
7065 List<String> result = null;
7066 // If we have multiple profiles we return the intersection of the
7067 // permitted lists. This can happen in cases where we have a device
7068 // and profile owner.
7069 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7070 for (int profileId : profileIds) {
7071 // Just loop though all admins, only device or profiles
7072 // owners can have permitted lists set.
7073 DevicePolicyData policy = getUserDataUnchecked(profileId);
7074 final int N = policy.mAdminList.size();
7075 for (int j = 0; j < N; j++) {
7076 ActiveAdmin admin = policy.mAdminList.get(j);
7077 List<String> fromAdmin = admin.permittedInputMethods;
7078 if (fromAdmin != null) {
7079 if (result == null) {
7080 result = new ArrayList<String>(fromAdmin);
7082 result.retainAll(fromAdmin);
7088 // If we have a permitted list add all system input methods.
7089 if (result != null) {
7090 InputMethodManager inputMethodManager =
7091 mContext.getSystemService(InputMethodManager.class);
7092 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7093 long id = mInjector.binderClearCallingIdentity();
7096 for (InputMethodInfo ime : imes) {
7097 ServiceInfo serviceInfo = ime.getServiceInfo();
7098 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7099 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7100 result.add(serviceInfo.packageName);
7105 mInjector.binderRestoreCallingIdentity(id);
7113 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7118 Preconditions.checkNotNull(who, "ComponentName is null");
7119 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7120 if (!isCallerWithSystemUid()) {
7121 throw new SecurityException(
7122 "Only the system can query if an input method is disabled by admin");
7124 synchronized (this) {
7125 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7126 if (admin == null) {
7129 if (admin.permittedInputMethods == null) {
7132 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7133 admin.permittedInputMethods, userHandle);
7137 private void sendAdminEnabledBroadcastLocked(int userHandle) {
7138 DevicePolicyData policyData = getUserData(userHandle);
7139 if (policyData.mAdminBroadcastPending) {
7140 // Send the initialization data to profile owner and delete the data
7141 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7142 if (admin != null) {
7143 PersistableBundle initBundle = policyData.mInitBundle;
7144 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7145 initBundle == null ? null : new Bundle(initBundle), null);
7147 policyData.mInitBundle = null;
7148 policyData.mAdminBroadcastPending = false;
7149 saveSettingsLocked(userHandle);
7154 public UserHandle createAndManageUser(ComponentName admin, String name,
7155 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7156 Preconditions.checkNotNull(admin, "admin is null");
7157 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7158 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7159 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7160 + admin + " are not in the same package");
7162 // Only allow the system user to use this method
7163 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7164 throw new SecurityException("createAndManageUser was called from non-system user");
7166 if (!mInjector.userManagerIsSplitSystemUser()
7167 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7168 throw new IllegalArgumentException(
7169 "Ephemeral users are only supported on systems with a split system user.");
7172 UserHandle user = null;
7173 synchronized (this) {
7174 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7176 final long id = mInjector.binderClearCallingIdentity();
7178 int userInfoFlags = 0;
7179 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7180 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7182 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7184 if (userInfo != null) {
7185 user = userInfo.getUserHandle();
7188 mInjector.binderRestoreCallingIdentity(id);
7195 final long id = mInjector.binderClearCallingIdentity();
7197 final String adminPkg = admin.getPackageName();
7199 final int userHandle = user.getIdentifier();
7201 // Install the profile owner if not present.
7202 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7203 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7205 } catch (RemoteException e) {
7206 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7207 + "removing created user", e);
7208 mUserManager.removeUser(user.getIdentifier());
7212 setActiveAdmin(profileOwner, true, userHandle);
7213 // User is not started yet, the broadcast by setActiveAdmin will not be received.
7214 // So we store adminExtras for broadcasting when the user starts for first time.
7215 synchronized(this) {
7216 DevicePolicyData policyData = getUserData(userHandle);
7217 policyData.mInitBundle = adminExtras;
7218 policyData.mAdminBroadcastPending = true;
7219 saveSettingsLocked(userHandle);
7221 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7222 setProfileOwner(profileOwner, ownerName, userHandle);
7224 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7225 Settings.Secure.putIntForUser(mContext.getContentResolver(),
7226 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7231 mInjector.binderRestoreCallingIdentity(id);
7236 public boolean removeUser(ComponentName who, UserHandle userHandle) {
7237 Preconditions.checkNotNull(who, "ComponentName is null");
7238 synchronized (this) {
7239 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7241 long id = mInjector.binderClearCallingIdentity();
7243 return mUserManager.removeUser(userHandle.getIdentifier());
7245 mInjector.binderRestoreCallingIdentity(id);
7251 public boolean switchUser(ComponentName who, UserHandle userHandle) {
7252 Preconditions.checkNotNull(who, "ComponentName is null");
7253 synchronized (this) {
7254 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7256 long id = mInjector.binderClearCallingIdentity();
7258 int userId = UserHandle.USER_SYSTEM;
7259 if (userHandle != null) {
7260 userId = userHandle.getIdentifier();
7262 return mInjector.getIActivityManager().switchUser(userId);
7263 } catch (RemoteException e) {
7264 Log.e(LOG_TAG, "Couldn't switch user", e);
7267 mInjector.binderRestoreCallingIdentity(id);
7273 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7274 enforceCanManageApplicationRestrictions(who);
7276 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7277 final long id = mInjector.binderClearCallingIdentity();
7279 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7280 // if no restrictions were saved, mUserManager.getApplicationRestrictions
7281 // returns null, but DPM method should return an empty Bundle as per JavaDoc
7282 return bundle != null ? bundle : Bundle.EMPTY;
7284 mInjector.binderRestoreCallingIdentity(id);
7289 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7290 boolean suspended) {
7291 Preconditions.checkNotNull(who, "ComponentName is null");
7292 int callingUserId = UserHandle.getCallingUserId();
7293 synchronized (this) {
7294 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7296 long id = mInjector.binderClearCallingIdentity();
7298 return mIPackageManager.setPackagesSuspendedAsUser(
7299 packageNames, suspended, callingUserId);
7300 } catch (RemoteException re) {
7301 // Shouldn't happen.
7302 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7304 mInjector.binderRestoreCallingIdentity(id);
7306 return packageNames;
7311 public boolean isPackageSuspended(ComponentName who, String packageName) {
7312 Preconditions.checkNotNull(who, "ComponentName is null");
7313 int callingUserId = UserHandle.getCallingUserId();
7314 synchronized (this) {
7315 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7317 long id = mInjector.binderClearCallingIdentity();
7319 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7320 } catch (RemoteException re) {
7321 // Shouldn't happen.
7322 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7324 mInjector.binderRestoreCallingIdentity(id);
7331 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7332 Preconditions.checkNotNull(who, "ComponentName is null");
7333 if (!UserRestrictionsUtils.isValidRestriction(key)) {
7337 final int userHandle = mInjector.userHandleGetCallingUserId();
7338 synchronized (this) {
7339 ActiveAdmin activeAdmin =
7340 getActiveAdminForCallerLocked(who,
7341 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7342 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7343 if (isDeviceOwner) {
7344 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7345 throw new SecurityException("Device owner cannot set user restriction " + key);
7347 } else { // profile owner
7348 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7349 throw new SecurityException("Profile owner cannot set user restriction " + key);
7353 // Save the restriction to ActiveAdmin.
7354 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7355 saveSettingsLocked(userHandle);
7357 pushUserRestrictions(userHandle);
7359 sendChangedNotification(userHandle);
7363 private void pushUserRestrictions(int userId) {
7364 synchronized (this) {
7365 final Bundle global;
7366 final Bundle local = new Bundle();
7367 if (mOwners.isDeviceOwnerUserId(userId)) {
7368 global = new Bundle();
7370 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7371 if (deviceOwner == null) {
7372 return; // Shouldn't happen.
7375 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7377 // DO can disable camera globally.
7378 if (deviceOwner.disableCamera) {
7379 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7384 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7385 if (profileOwner != null) {
7386 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7389 // Also merge in *local* camera restriction.
7390 if (getCameraDisabled(/* who= */ null,
7391 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7392 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7394 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7399 public Bundle getUserRestrictions(ComponentName who) {
7403 Preconditions.checkNotNull(who, "ComponentName is null");
7404 synchronized (this) {
7405 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7406 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7407 return activeAdmin.userRestrictions;
7412 public boolean setApplicationHidden(ComponentName who, String packageName,
7414 Preconditions.checkNotNull(who, "ComponentName is null");
7415 int callingUserId = UserHandle.getCallingUserId();
7416 synchronized (this) {
7417 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7419 long id = mInjector.binderClearCallingIdentity();
7421 return mIPackageManager.setApplicationHiddenSettingAsUser(
7422 packageName, hidden, callingUserId);
7423 } catch (RemoteException re) {
7425 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7427 mInjector.binderRestoreCallingIdentity(id);
7434 public boolean isApplicationHidden(ComponentName who, String packageName) {
7435 Preconditions.checkNotNull(who, "ComponentName is null");
7436 int callingUserId = UserHandle.getCallingUserId();
7437 synchronized (this) {
7438 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7440 long id = mInjector.binderClearCallingIdentity();
7442 return mIPackageManager.getApplicationHiddenSettingAsUser(
7443 packageName, callingUserId);
7444 } catch (RemoteException re) {
7446 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7448 mInjector.binderRestoreCallingIdentity(id);
7455 public void enableSystemApp(ComponentName who, String packageName) {
7456 Preconditions.checkNotNull(who, "ComponentName is null");
7457 synchronized (this) {
7458 // This API can only be called by an active device admin,
7459 // so try to retrieve it to check that the caller is one.
7460 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7462 int userId = UserHandle.getCallingUserId();
7463 long id = mInjector.binderClearCallingIdentity();
7467 Slog.v(LOG_TAG, "installing " + packageName + " for "
7471 int parentUserId = getProfileParentId(userId);
7472 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7473 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7477 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7479 } catch (RemoteException re) {
7481 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7483 mInjector.binderRestoreCallingIdentity(id);
7489 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7490 Preconditions.checkNotNull(who, "ComponentName is null");
7491 synchronized (this) {
7492 // This API can only be called by an active device admin,
7493 // so try to retrieve it to check that the caller is one.
7494 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7496 int userId = UserHandle.getCallingUserId();
7497 long id = mInjector.binderClearCallingIdentity();
7500 int parentUserId = getProfileParentId(userId);
7501 List<ResolveInfo> activitiesToEnable = mIPackageManager
7502 .queryIntentActivities(intent,
7503 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7504 PackageManager.MATCH_DIRECT_BOOT_AWARE
7505 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7510 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7512 int numberOfAppsInstalled = 0;
7513 if (activitiesToEnable != null) {
7514 for (ResolveInfo info : activitiesToEnable) {
7515 if (info.activityInfo != null) {
7516 String packageName = info.activityInfo.packageName;
7517 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7518 numberOfAppsInstalled++;
7519 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7521 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7527 return numberOfAppsInstalled;
7528 } catch (RemoteException e) {
7530 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7533 mInjector.binderRestoreCallingIdentity(id);
7538 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7539 throws RemoteException {
7540 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7542 if (appInfo == null) {
7543 throw new IllegalArgumentException("The application " + packageName +
7544 " is not present on this device");
7546 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7550 public void setAccountManagementDisabled(ComponentName who, String accountType,
7555 Preconditions.checkNotNull(who, "ComponentName is null");
7556 synchronized (this) {
7557 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7558 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7560 ap.accountTypesWithManagementDisabled.add(accountType);
7562 ap.accountTypesWithManagementDisabled.remove(accountType);
7564 saveSettingsLocked(UserHandle.getCallingUserId());
7569 public String[] getAccountTypesWithManagementDisabled() {
7570 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7574 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7575 enforceFullCrossUsersPermission(userId);
7579 synchronized (this) {
7580 DevicePolicyData policy = getUserData(userId);
7581 final int N = policy.mAdminList.size();
7582 ArraySet<String> resultSet = new ArraySet<>();
7583 for (int i = 0; i < N; i++) {
7584 ActiveAdmin admin = policy.mAdminList.get(i);
7585 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7587 return resultSet.toArray(new String[resultSet.size()]);
7592 public void setUninstallBlocked(ComponentName who, String packageName,
7593 boolean uninstallBlocked) {
7594 Preconditions.checkNotNull(who, "ComponentName is null");
7595 final int userId = UserHandle.getCallingUserId();
7596 synchronized (this) {
7597 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7599 long id = mInjector.binderClearCallingIdentity();
7601 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7602 } catch (RemoteException re) {
7603 // Shouldn't happen.
7604 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7606 mInjector.binderRestoreCallingIdentity(id);
7612 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7613 // This function should return true if and only if the package is blocked by
7614 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7615 // when the package is a system app, or when it is an active device admin.
7616 final int userId = UserHandle.getCallingUserId();
7618 synchronized (this) {
7620 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7623 long id = mInjector.binderClearCallingIdentity();
7625 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7626 } catch (RemoteException re) {
7627 // Shouldn't happen.
7628 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7630 mInjector.binderRestoreCallingIdentity(id);
7637 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7641 Preconditions.checkNotNull(who, "ComponentName is null");
7642 synchronized (this) {
7643 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7644 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7645 if (admin.disableCallerId != disabled) {
7646 admin.disableCallerId = disabled;
7647 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7653 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7657 Preconditions.checkNotNull(who, "ComponentName is null");
7658 synchronized (this) {
7659 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7660 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7661 return admin.disableCallerId;
7666 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7667 enforceCrossUsersPermission(userId);
7668 synchronized (this) {
7669 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7670 return (admin != null) ? admin.disableCallerId : false;
7675 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7679 Preconditions.checkNotNull(who, "ComponentName is null");
7680 synchronized (this) {
7681 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7682 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7683 if (admin.disableContactsSearch != disabled) {
7684 admin.disableContactsSearch = disabled;
7685 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7691 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7695 Preconditions.checkNotNull(who, "ComponentName is null");
7696 synchronized (this) {
7697 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7698 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7699 return admin.disableContactsSearch;
7704 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7705 enforceCrossUsersPermission(userId);
7706 synchronized (this) {
7707 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7708 return (admin != null) ? admin.disableContactsSearch : false;
7713 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7714 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7715 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7716 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7717 final int callingUserId = UserHandle.getCallingUserId();
7719 final long ident = mInjector.binderClearCallingIdentity();
7721 synchronized (this) {
7722 final int managedUserId = getManagedUserId(callingUserId);
7723 if (managedUserId < 0) {
7726 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7729 "Cross-profile contacts access disabled for user " + managedUserId);
7733 ContactsInternal.startQuickContactWithErrorToastForUser(
7734 mContext, intent, new UserHandle(managedUserId));
7737 mInjector.binderRestoreCallingIdentity(ident);
7742 * @return true if cross-profile QuickContact is disabled
7744 private boolean isCrossProfileQuickContactDisabled(int userId) {
7745 return getCrossProfileCallerIdDisabledForUser(userId)
7746 && getCrossProfileContactsSearchDisabledForUser(userId);
7750 * @return the user ID of the managed user that is linked to the current user, if any.
7753 public int getManagedUserId(int callingUserId) {
7755 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7758 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7759 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7760 continue; // Caller user self, or not a managed profile. Skip.
7763 Log.v(LOG_TAG, "Managed user=" + ui.id);
7768 Log.v(LOG_TAG, "Managed user not found.");
7774 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7778 Preconditions.checkNotNull(who, "ComponentName is null");
7779 synchronized (this) {
7780 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7781 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7782 if (admin.disableBluetoothContactSharing != disabled) {
7783 admin.disableBluetoothContactSharing = disabled;
7784 saveSettingsLocked(UserHandle.getCallingUserId());
7790 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
7794 Preconditions.checkNotNull(who, "ComponentName is null");
7795 synchronized (this) {
7796 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7797 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7798 return admin.disableBluetoothContactSharing;
7803 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
7804 // TODO: Should there be a check to make sure this relationship is
7805 // within a profile group?
7806 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
7807 synchronized (this) {
7808 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7809 return (admin != null) ? admin.disableBluetoothContactSharing : false;
7814 * Sets which packages may enter lock task mode.
7816 * <p>This function can only be called by the device owner or alternatively by the profile owner
7817 * in case the user is affiliated.
7819 * @param packages The list of packages allowed to enter lock task mode.
7822 public void setLockTaskPackages(ComponentName who, String[] packages)
7823 throws SecurityException {
7824 Preconditions.checkNotNull(who, "ComponentName is null");
7825 synchronized (this) {
7826 ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
7827 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
7828 ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
7829 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
7830 if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
7831 int userHandle = mInjector.userHandleGetCallingUserId();
7832 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
7834 throw new SecurityException("Admin " + who +
7835 " is neither the device owner or affiliated user's profile owner.");
7840 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
7841 DevicePolicyData policy = getUserData(userHandle);
7842 policy.mLockTaskPackages = packages;
7844 // Store the settings persistently.
7845 saveSettingsLocked(userHandle);
7846 updateLockTaskPackagesLocked(packages, userHandle);
7850 * This function returns the list of components allowed to start the task lock mode.
7853 public String[] getLockTaskPackages(ComponentName who) {
7854 Preconditions.checkNotNull(who, "ComponentName is null");
7855 synchronized (this) {
7856 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7857 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
7858 final List<String> packages = getLockTaskPackagesLocked(userHandle);
7859 return packages.toArray(new String[packages.size()]);
7863 private List<String> getLockTaskPackagesLocked(int userHandle) {
7864 final DevicePolicyData policy = getUserData(userHandle);
7865 return policy.mLockTaskPackages;
7869 * This function lets the caller know whether the given package is allowed to start the
7871 * @param pkg The package to check
7874 public boolean isLockTaskPermitted(String pkg) {
7875 // Get current user's devicepolicy
7876 int uid = mInjector.binderGetCallingUid();
7877 int userHandle = UserHandle.getUserId(uid);
7878 DevicePolicyData policy = getUserData(userHandle);
7879 synchronized (this) {
7880 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
7881 String lockTaskPackage = policy.mLockTaskPackages.get(i);
7883 // If the given package equals one of the packages stored our list,
7884 // we allow this package to start lock task mode.
7885 if (lockTaskPackage.equals(pkg)) {
7894 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
7895 if (!isCallerWithSystemUid()) {
7896 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
7898 synchronized (this) {
7899 final DevicePolicyData policy = getUserData(userHandle);
7900 Bundle adminExtras = new Bundle();
7901 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
7902 for (ActiveAdmin admin : policy.mAdminList) {
7903 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
7904 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
7905 if (ownsDevice || ownsProfile) {
7907 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
7910 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
7918 public void setGlobalSetting(ComponentName who, String setting, String value) {
7919 Preconditions.checkNotNull(who, "ComponentName is null");
7921 synchronized (this) {
7922 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7924 // Some settings are no supported any more. However we do not want to throw a
7925 // SecurityException to avoid breaking apps.
7926 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
7927 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
7931 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
7932 throw new SecurityException(String.format(
7933 "Permission denial: device owners cannot update %1$s", setting));
7936 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
7937 // ignore if it contradicts an existing policy
7938 long timeMs = getMaximumTimeToLock(
7939 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
7940 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
7945 long id = mInjector.binderClearCallingIdentity();
7947 mInjector.settingsGlobalPutString(setting, value);
7949 mInjector.binderRestoreCallingIdentity(id);
7955 public void setSecureSetting(ComponentName who, String setting, String value) {
7956 Preconditions.checkNotNull(who, "ComponentName is null");
7957 int callingUserId = mInjector.userHandleGetCallingUserId();
7959 synchronized (this) {
7960 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7962 if (isDeviceOwner(who, callingUserId)) {
7963 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
7964 throw new SecurityException(String.format(
7965 "Permission denial: Device owners cannot update %1$s", setting));
7967 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
7968 throw new SecurityException(String.format(
7969 "Permission denial: Profile owners cannot update %1$s", setting));
7972 long id = mInjector.binderClearCallingIdentity();
7974 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
7976 mInjector.binderRestoreCallingIdentity(id);
7982 public void setMasterVolumeMuted(ComponentName who, boolean on) {
7983 Preconditions.checkNotNull(who, "ComponentName is null");
7984 synchronized (this) {
7985 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7986 setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
7991 public boolean isMasterVolumeMuted(ComponentName who) {
7992 Preconditions.checkNotNull(who, "ComponentName is null");
7993 synchronized (this) {
7994 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7996 AudioManager audioManager =
7997 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
7998 return audioManager.isMasterMute();
8003 public void setUserIcon(ComponentName who, Bitmap icon) {
8004 synchronized (this) {
8005 Preconditions.checkNotNull(who, "ComponentName is null");
8006 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8008 int userId = UserHandle.getCallingUserId();
8009 long id = mInjector.binderClearCallingIdentity();
8011 mUserManagerInternal.setUserIcon(userId, icon);
8013 mInjector.binderRestoreCallingIdentity(id);
8019 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8020 Preconditions.checkNotNull(who, "ComponentName is null");
8021 synchronized (this) {
8022 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8024 final int userId = UserHandle.getCallingUserId();
8026 long ident = mInjector.binderClearCallingIdentity();
8028 // disallow disabling the keyguard if a password is currently set
8029 if (disabled && mLockPatternUtils.isSecure(userId)) {
8032 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8034 mInjector.binderRestoreCallingIdentity(ident);
8040 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8041 int userId = UserHandle.getCallingUserId();
8042 synchronized (this) {
8043 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8044 DevicePolicyData policy = getUserData(userId);
8045 if (policy.mStatusBarDisabled != disabled) {
8046 if (!setStatusBarDisabledInternal(disabled, userId)) {
8049 policy.mStatusBarDisabled = disabled;
8050 saveSettingsLocked(userId);
8056 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8057 long ident = mInjector.binderClearCallingIdentity();
8059 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8060 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8061 if (statusBarService != null) {
8062 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8063 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8064 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8065 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8068 } catch (RemoteException e) {
8069 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8071 mInjector.binderRestoreCallingIdentity(ident);
8077 * We need to update the internal state of whether a user has completed setup once. After
8078 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
8079 * as we don't trust any apps that might try to reset it.
8081 * Unfortunately, we don't know which user's setup state was changed, so we write all of
8084 void updateUserSetupComplete() {
8085 List<UserInfo> users = mUserManager.getUsers(true);
8086 final int N = users.size();
8087 for (int i = 0; i < N; i++) {
8088 int userHandle = users.get(i).id;
8089 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8091 DevicePolicyData policy = getUserData(userHandle);
8092 if (!policy.mUserSetupComplete) {
8093 policy.mUserSetupComplete = true;
8094 synchronized (this) {
8095 saveSettingsLocked(userHandle);
8102 private class SetupContentObserver extends ContentObserver {
8104 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8105 Settings.Secure.USER_SETUP_COMPLETE);
8106 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8107 Settings.Global.DEVICE_PROVISIONED);
8109 public SetupContentObserver(Handler handler) {
8114 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8115 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8119 public void onChange(boolean selfChange, Uri uri) {
8120 if (mUserSetupComplete.equals(uri)) {
8121 updateUserSetupComplete();
8122 } else if (mDeviceProvisioned.equals(uri)) {
8123 synchronized (DevicePolicyManagerService.this) {
8124 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8125 // is delayed until device is marked as provisioned.
8126 setDeviceOwnerSystemPropertyLocked();
8133 final class LocalService extends DevicePolicyManagerInternal {
8134 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8137 public List<String> getCrossProfileWidgetProviders(int profileId) {
8138 synchronized (DevicePolicyManagerService.this) {
8139 if (mOwners == null) {
8140 return Collections.emptyList();
8142 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8143 if (ownerComponent == null) {
8144 return Collections.emptyList();
8147 DevicePolicyData policy = getUserDataUnchecked(profileId);
8148 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8150 if (admin == null || admin.crossProfileWidgetProviders == null
8151 || admin.crossProfileWidgetProviders.isEmpty()) {
8152 return Collections.emptyList();
8155 return admin.crossProfileWidgetProviders;
8160 public void addOnCrossProfileWidgetProvidersChangeListener(
8161 OnCrossProfileWidgetProvidersChangeListener listener) {
8162 synchronized (DevicePolicyManagerService.this) {
8163 if (mWidgetProviderListeners == null) {
8164 mWidgetProviderListeners = new ArrayList<>();
8166 if (!mWidgetProviderListeners.contains(listener)) {
8167 mWidgetProviderListeners.add(listener);
8173 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8174 synchronized(DevicePolicyManagerService.this) {
8175 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8179 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8180 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8181 synchronized (DevicePolicyManagerService.this) {
8182 listeners = new ArrayList<>(mWidgetProviderListeners);
8184 final int listenerCount = listeners.size();
8185 for (int i = 0; i < listenerCount; i++) {
8186 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8187 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8192 public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
8193 Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8194 intent.putExtra(Intent.EXTRA_USER_ID, userId);
8195 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8197 // This method is called from AM with its lock held, so don't take the DPMS lock.
8200 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8201 if (profileOwner != null) {
8202 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
8206 final Pair<Integer, ComponentName> deviceOwner =
8207 mOwners.getDeviceOwnerUserIdAndComponent();
8208 if (deviceOwner != null && deviceOwner.first == userId) {
8209 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
8213 // We're not specifying the device admin because there isn't one.
8219 * Returns true if specified admin is allowed to limit passwords and has a
8220 * {@code passwordQuality} of at least {@code minPasswordQuality}
8222 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8223 if (admin.passwordQuality < minPasswordQuality) {
8226 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8230 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8231 if (policy != null && !policy.isValid()) {
8232 throw new IllegalArgumentException("Invalid system update policy.");
8234 synchronized (this) {
8235 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8236 if (policy == null) {
8237 mOwners.clearSystemUpdatePolicy();
8239 mOwners.setSystemUpdatePolicy(policy);
8241 mOwners.writeDeviceOwner();
8243 mContext.sendBroadcastAsUser(
8244 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8249 public SystemUpdatePolicy getSystemUpdatePolicy() {
8250 if (UserManager.isDeviceInDemoMode(mContext)) {
8251 // Pretending to have an automatic update policy when the device is in retail demo
8252 // mode. This will allow the device to download and install an ota without
8253 // any user interaction.
8254 return SystemUpdatePolicy.createAutomaticInstallPolicy();
8256 synchronized (this) {
8257 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
8258 if (policy != null && !policy.isValid()) {
8259 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8267 * Checks if the caller of the method is the device owner app.
8269 * @param callerUid UID of the caller.
8270 * @return true if the caller is the device owner app
8273 boolean isCallerDeviceOwner(int callerUid) {
8274 synchronized (this) {
8275 if (!mOwners.hasDeviceOwner()) {
8278 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8281 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8283 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8285 for (String pkg : pkgs) {
8286 if (deviceOwnerPackageName.equals(pkg)) {
8296 public void notifyPendingSystemUpdate(long updateReceivedTime) {
8297 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8298 "Only the system update service can broadcast update information");
8300 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8301 Slog.w(LOG_TAG, "Only the system update service in the system user " +
8302 "can broadcast update information.");
8305 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8306 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8307 updateReceivedTime);
8309 synchronized (this) {
8310 final String deviceOwnerPackage =
8311 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8313 if (deviceOwnerPackage == null) {
8316 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8318 ActivityInfo[] receivers = null;
8320 receivers = mContext.getPackageManager().getPackageInfo(
8321 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8322 } catch (NameNotFoundException e) {
8323 Log.e(LOG_TAG, "Cannot find device owner package", e);
8325 if (receivers != null) {
8326 long ident = mInjector.binderClearCallingIdentity();
8328 for (int i = 0; i < receivers.length; i++) {
8329 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8330 intent.setComponent(new ComponentName(deviceOwnerPackage,
8331 receivers[i].name));
8332 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8336 mInjector.binderRestoreCallingIdentity(ident);
8343 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8344 int userId = UserHandle.getCallingUserId();
8345 synchronized (this) {
8346 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8347 DevicePolicyData userPolicy = getUserData(userId);
8348 if (userPolicy.mPermissionPolicy != policy) {
8349 userPolicy.mPermissionPolicy = policy;
8350 saveSettingsLocked(userId);
8356 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8357 int userId = UserHandle.getCallingUserId();
8358 synchronized (this) {
8359 DevicePolicyData userPolicy = getUserData(userId);
8360 return userPolicy.mPermissionPolicy;
8365 public boolean setPermissionGrantState(ComponentName admin, String packageName,
8366 String permission, int grantState) throws RemoteException {
8367 UserHandle user = mInjector.binderGetCallingUserHandle();
8368 synchronized (this) {
8369 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8370 long ident = mInjector.binderClearCallingIdentity();
8372 if (getTargetSdk(packageName, user.getIdentifier())
8373 < android.os.Build.VERSION_CODES.M) {
8376 if (!isRuntimePermission(permission)) {
8377 EventLog.writeEvent(0x534e4554, "62623498", user.getIdentifier(), "");
8380 final PackageManager packageManager = mContext.getPackageManager();
8381 switch (grantState) {
8382 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8383 packageManager.grantRuntimePermission(packageName, permission, user);
8384 packageManager.updatePermissionFlags(permission, packageName,
8385 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8386 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8389 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8390 packageManager.revokeRuntimePermission(packageName,
8392 packageManager.updatePermissionFlags(permission, packageName,
8393 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8394 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8397 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8398 packageManager.updatePermissionFlags(permission, packageName,
8399 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8403 } catch (SecurityException se) {
8405 } catch (NameNotFoundException e) {
8408 mInjector.binderRestoreCallingIdentity(ident);
8413 public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
8414 final PackageManager packageManager = mContext.getPackageManager();
8415 PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
8416 return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
8417 == PermissionInfo.PROTECTION_DANGEROUS;
8421 public int getPermissionGrantState(ComponentName admin, String packageName,
8422 String permission) throws RemoteException {
8423 PackageManager packageManager = mContext.getPackageManager();
8425 UserHandle user = mInjector.binderGetCallingUserHandle();
8426 synchronized (this) {
8427 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8428 long ident = mInjector.binderClearCallingIdentity();
8430 int granted = mIPackageManager.checkPermission(permission,
8431 packageName, user.getIdentifier());
8432 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8433 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8434 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8435 // Not controlled by policy
8436 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8438 // Policy controlled so return result based on permission grant state
8439 return granted == PackageManager.PERMISSION_GRANTED
8440 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8441 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8444 mInjector.binderRestoreCallingIdentity(ident);
8449 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8451 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8453 return (pi != null) && (pi.applicationInfo.flags != 0);
8454 } catch (RemoteException re) {
8455 throw new RuntimeException("Package manager has died", re);
8460 public boolean isProvisioningAllowed(String action) {
8465 final int callingUserId = mInjector.userHandleGetCallingUserId();
8466 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8467 if (!hasFeatureManagedUsers()) {
8470 synchronized (this) {
8471 if (mOwners.hasDeviceOwner()) {
8472 if (!mInjector.userManagerIsSplitSystemUser()) {
8473 // Only split-system-user systems support managed-profiles in combination with
8477 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8478 // Only system device-owner supports managed-profiles. Non-system device-owner
8482 if (callingUserId == UserHandle.USER_SYSTEM) {
8483 // Managed-profiles cannot be setup on the system user, only regular users.
8488 if (getProfileOwner(callingUserId) != null) {
8489 // Managed user cannot have a managed profile.
8492 final long ident = mInjector.binderClearCallingIdentity();
8494 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8498 mInjector.binderRestoreCallingIdentity(ident);
8501 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8502 return isDeviceOwnerProvisioningAllowed(callingUserId);
8503 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8504 if (!hasFeatureManagedUsers()) {
8507 if (!mInjector.userManagerIsSplitSystemUser()) {
8508 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8511 if (callingUserId == UserHandle.USER_SYSTEM) {
8512 // System user cannot be a managed user.
8515 if (hasUserSetupCompleted(callingUserId)) {
8519 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8520 if (!mInjector.userManagerIsSplitSystemUser()) {
8521 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8524 return isDeviceOwnerProvisioningAllowed(callingUserId);
8526 throw new IllegalArgumentException("Unknown provisioning action " + action);
8530 * The device owner can only be set before the setup phase of the primary user has completed,
8531 * except for adb command if no accounts or additional users are present on the device.
8533 private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreCondition(
8534 int deviceOwnerUserId, boolean isAdb) {
8535 if (mOwners.hasDeviceOwner()) {
8536 return CODE_HAS_DEVICE_OWNER;
8538 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8539 return CODE_USER_HAS_PROFILE_OWNER;
8541 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8542 return CODE_USER_NOT_RUNNING;
8545 // if shell command runs after user setup completed check device status. Otherwise, OK.
8546 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8547 if (!mInjector.userManagerIsSplitSystemUser()) {
8548 if (mUserManager.getUserCount() > 1) {
8549 return CODE_NONSYSTEM_USER_EXISTS;
8551 if (AccountManager.get(mContext).getAccounts().length > 0) {
8552 return CODE_ACCOUNTS_NOT_EMPTY;
8555 // STOPSHIP Do proper check in split user mode
8560 if (!mInjector.userManagerIsSplitSystemUser()) {
8561 // In non-split user mode, DO has to be user 0
8562 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8563 return CODE_NOT_SYSTEM_USER;
8565 // In non-split user mode, only provision DO before setup wizard completes
8566 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8567 return CODE_USER_SETUP_COMPLETED;
8570 // STOPSHIP Do proper check in split user mode
8576 private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8577 return CODE_OK == checkSetDeviceOwnerPreCondition(deviceOwnerUserId, /* isAdb */ false);
8580 private boolean hasFeatureManagedUsers() {
8582 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8583 } catch (RemoteException e) {
8589 public String getWifiMacAddress(ComponentName admin) {
8590 // Make sure caller has DO.
8591 synchronized (this) {
8592 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8595 final long ident = mInjector.binderClearCallingIdentity();
8597 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8598 if (wifiInfo == null) {
8601 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8603 mInjector.binderRestoreCallingIdentity(ident);
8608 * Returns the target sdk version number that the given packageName was built for
8609 * in the given user.
8611 private int getTargetSdk(String packageName, int userId) {
8612 final ApplicationInfo ai;
8614 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8615 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8616 return targetSdkVersion;
8617 } catch (RemoteException e) {
8624 public boolean isManagedProfile(ComponentName admin) {
8625 synchronized (this) {
8626 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8628 final int callingUserId = mInjector.userHandleGetCallingUserId();
8629 final UserInfo user = getUserInfo(callingUserId);
8630 return user != null && user.isManagedProfile();
8634 public boolean isSystemOnlyUser(ComponentName admin) {
8635 synchronized (this) {
8636 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8638 final int callingUserId = mInjector.userHandleGetCallingUserId();
8639 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8643 public void reboot(ComponentName admin) {
8644 Preconditions.checkNotNull(admin);
8645 // Make sure caller has DO.
8646 synchronized (this) {
8647 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8649 long ident = mInjector.binderClearCallingIdentity();
8651 // Make sure there are no ongoing calls on the device.
8652 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8653 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8655 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8657 mInjector.binderRestoreCallingIdentity(ident);
8662 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8666 Preconditions.checkNotNull(who, "ComponentName is null");
8667 final int userHandle = mInjector.userHandleGetCallingUserId();
8668 synchronized (this) {
8669 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8670 mInjector.binderGetCallingUid());
8671 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8672 admin.shortSupportMessage = message;
8673 saveSettingsLocked(userHandle);
8679 public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8683 Preconditions.checkNotNull(who, "ComponentName is null");
8684 synchronized (this) {
8685 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8686 mInjector.binderGetCallingUid());
8687 return admin.shortSupportMessage;
8692 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8696 Preconditions.checkNotNull(who, "ComponentName is null");
8697 final int userHandle = mInjector.userHandleGetCallingUserId();
8698 synchronized (this) {
8699 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8700 mInjector.binderGetCallingUid());
8701 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8702 admin.longSupportMessage = message;
8703 saveSettingsLocked(userHandle);
8709 public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8713 Preconditions.checkNotNull(who, "ComponentName is null");
8714 synchronized (this) {
8715 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8716 mInjector.binderGetCallingUid());
8717 return admin.longSupportMessage;
8722 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8726 Preconditions.checkNotNull(who, "ComponentName is null");
8727 if (!isCallerWithSystemUid()) {
8728 throw new SecurityException("Only the system can query support message for user");
8730 synchronized (this) {
8731 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8732 if (admin != null) {
8733 return admin.shortSupportMessage;
8740 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8744 Preconditions.checkNotNull(who, "ComponentName is null");
8745 if (!isCallerWithSystemUid()) {
8746 throw new SecurityException("Only the system can query support message for user");
8748 synchronized (this) {
8749 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8750 if (admin != null) {
8751 return admin.longSupportMessage;
8758 public void setOrganizationColor(@NonNull ComponentName who, int color) {
8762 Preconditions.checkNotNull(who, "ComponentName is null");
8763 final int userHandle = mInjector.userHandleGetCallingUserId();
8764 enforceManagedProfile(userHandle, "set organization color");
8765 synchronized (this) {
8766 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8767 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8768 admin.organizationColor = color;
8769 saveSettingsLocked(userHandle);
8774 public void setOrganizationColorForUser(int color, int userId) {
8778 enforceFullCrossUsersPermission(userId);
8779 enforceManageUsers();
8780 enforceManagedProfile(userId, "set organization color");
8781 synchronized (this) {
8782 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8783 admin.organizationColor = color;
8784 saveSettingsLocked(userId);
8789 public int getOrganizationColor(@NonNull ComponentName who) {
8791 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8793 Preconditions.checkNotNull(who, "ComponentName is null");
8794 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
8795 synchronized (this) {
8796 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8797 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8798 return admin.organizationColor;
8803 public int getOrganizationColorForUser(int userHandle) {
8805 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8807 enforceFullCrossUsersPermission(userHandle);
8808 enforceManagedProfile(userHandle, "get organization color");
8809 synchronized (this) {
8810 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8811 return (profileOwner != null)
8812 ? profileOwner.organizationColor
8813 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
8818 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
8822 Preconditions.checkNotNull(who, "ComponentName is null");
8823 final int userHandle = mInjector.userHandleGetCallingUserId();
8824 enforceManagedProfile(userHandle, "set organization name");
8825 synchronized (this) {
8826 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8827 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8828 if (!TextUtils.equals(admin.organizationName, text)) {
8829 admin.organizationName = (text == null || text.length() == 0)
8830 ? null : text.toString();
8831 saveSettingsLocked(userHandle);
8837 public CharSequence getOrganizationName(@NonNull ComponentName who) {
8841 Preconditions.checkNotNull(who, "ComponentName is null");
8842 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
8843 synchronized(this) {
8844 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8845 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8846 return admin.organizationName;
8851 public CharSequence getOrganizationNameForUser(int userHandle) {
8855 enforceFullCrossUsersPermission(userHandle);
8856 enforceManagedProfile(userHandle, "get organization name");
8857 synchronized (this) {
8858 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8859 return (profileOwner != null)
8860 ? profileOwner.organizationName
8866 public void setAffiliationIds(ComponentName admin, List<String> ids) {
8867 final Set<String> affiliationIds = new ArraySet<String>(ids);
8868 final int callingUserId = mInjector.userHandleGetCallingUserId();
8870 synchronized (this) {
8871 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8872 getUserData(callingUserId).mAffiliationIds = affiliationIds;
8873 saveSettingsLocked(callingUserId);
8874 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
8875 // Affiliation ids specified by the device owner are additionally stored in
8876 // UserHandle.USER_SYSTEM's DevicePolicyData.
8877 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
8878 saveSettingsLocked(UserHandle.USER_SYSTEM);
8884 public boolean isAffiliatedUser() {
8885 final int callingUserId = mInjector.userHandleGetCallingUserId();
8887 synchronized (this) {
8888 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
8889 // The user that the DO is installed on is always affiliated.
8892 final ComponentName profileOwner = getProfileOwner(callingUserId);
8893 if (profileOwner == null
8894 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
8897 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
8898 final Set<String> deviceAffiliationIds =
8899 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
8900 for (String id : userAffiliationIds) {
8901 if (deviceAffiliationIds.contains(id)) {
8909 private synchronized void disableSecurityLoggingIfNotCompliant() {
8910 if (!isDeviceOwnerManagedSingleUserDevice()) {
8911 mInjector.securityLogSetLoggingEnabledProperty(false);
8912 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user device.");
8917 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
8918 Preconditions.checkNotNull(admin);
8919 ensureDeviceOwnerManagingSingleUser(admin);
8921 synchronized (this) {
8922 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
8925 mInjector.securityLogSetLoggingEnabledProperty(enabled);
8927 mSecurityLogMonitor.start();
8929 mSecurityLogMonitor.stop();
8935 public boolean isSecurityLoggingEnabled(ComponentName admin) {
8936 Preconditions.checkNotNull(admin);
8937 synchronized (this) {
8938 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8939 return mInjector.securityLogGetLoggingEnabledProperty();
8944 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
8945 Preconditions.checkNotNull(admin);
8946 ensureDeviceOwnerManagingSingleUser(admin);
8948 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
8952 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
8954 SecurityLog.readPreviousEvents(output);
8955 return new ParceledListSlice<SecurityEvent>(output);
8956 } catch (IOException e) {
8957 Slog.w(LOG_TAG, "Fail to read previous events" , e);
8958 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
8963 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
8964 Preconditions.checkNotNull(admin);
8965 ensureDeviceOwnerManagingSingleUser(admin);
8967 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
8968 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
8971 private void enforceCanManageDeviceAdmin() {
8972 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
8976 private void enforceCanManageProfileAndDeviceOwners() {
8977 mContext.enforceCallingOrSelfPermission(
8978 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
8982 public boolean isUninstallInQueue(final String packageName) {
8983 enforceCanManageDeviceAdmin();
8984 final int userId = mInjector.userHandleGetCallingUserId();
8985 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8986 synchronized (this) {
8987 return mPackagesToRemove.contains(packageUserPair);
8992 public void uninstallPackageWithActiveAdmins(final String packageName) {
8993 enforceCanManageDeviceAdmin();
8994 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
8996 final int userId = mInjector.userHandleGetCallingUserId();
8998 enforceUserUnlocked(userId);
9000 final ComponentName profileOwner = getProfileOwner(userId);
9001 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
9002 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
9005 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
9006 if (getDeviceOwnerUserId() == userId && deviceOwner != null
9007 && packageName.equals(deviceOwner.getPackageName())) {
9008 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
9011 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9012 synchronized (this) {
9013 mPackagesToRemove.add(packageUserPair);
9016 // All active admins on the user.
9017 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
9019 // Active admins in the target package.
9020 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
9021 if (allActiveAdmins != null) {
9022 for (ComponentName activeAdmin : allActiveAdmins) {
9023 if (packageName.equals(activeAdmin.getPackageName())) {
9024 packageActiveAdmins.add(activeAdmin);
9025 removeActiveAdmin(activeAdmin, userId);
9029 if (packageActiveAdmins.size() == 0) {
9030 startUninstallIntent(packageName, userId);
9032 mHandler.postDelayed(new Runnable() {
9035 for (ComponentName activeAdmin : packageActiveAdmins) {
9036 removeAdminArtifacts(activeAdmin, userId);
9038 startUninstallIntent(packageName, userId);
9040 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9045 public boolean isDeviceProvisioned() {
9046 return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9049 private void removePackageIfRequired(final String packageName, final int userId) {
9050 if (!packageHasActiveAdmins(packageName, userId)) {
9051 // Will not do anything if uninstall was not requested or was already started.
9052 startUninstallIntent(packageName, userId);
9056 private void startUninstallIntent(final String packageName, final int userId) {
9057 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9058 synchronized (this) {
9059 if (!mPackagesToRemove.contains(packageUserPair)) {
9060 // Do nothing if uninstall was not requested or was already started.
9063 mPackagesToRemove.remove(packageUserPair);
9066 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9067 // Package does not exist. Nothing to do.
9070 } catch (RemoteException re) {
9071 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9074 try { // force stop the package before uninstalling
9075 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9076 } catch (RemoteException re) {
9077 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9079 final Uri packageURI = Uri.parse("package:" + packageName);
9080 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9081 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9082 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9086 * Removes the admin from the policy. Ideally called after the admin's
9087 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9089 * @param adminReceiver The admin to remove
9090 * @param userHandle The user for which this admin has to be removed.
9092 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9093 synchronized (this) {
9094 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9095 if (admin == null) {
9098 final DevicePolicyData policy = getUserData(userHandle);
9099 final boolean doProxyCleanup = admin.info.usesPolicy(
9100 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9101 policy.mAdminList.remove(admin);
9102 policy.mAdminMap.remove(adminReceiver);
9103 validatePasswordOwnerLocked(policy);
9104 if (doProxyCleanup) {
9105 resetGlobalProxyLocked(policy);
9107 saveSettingsLocked(userHandle);
9108 updateMaximumTimeToLockLocked(userHandle);
9109 policy.mRemovingAdmins.remove(adminReceiver);
9111 // The removed admin might have disabled camera, so update user
9113 pushUserRestrictions(userHandle);
9117 public void setDeviceProvisioningConfigApplied() {
9118 enforceManageUsers();
9119 synchronized (this) {
9120 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9121 policy.mDeviceProvisioningConfigApplied = true;
9122 saveSettingsLocked(UserHandle.USER_SYSTEM);
9127 public boolean isDeviceProvisioningConfigApplied() {
9128 enforceManageUsers();
9129 synchronized (this) {
9130 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9131 return policy.mDeviceProvisioningConfigApplied;