2 * Copyright (C) 2010 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.server.devicepolicy;
19 import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
20 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
21 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
22 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
23 import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
25 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
26 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
27 import static org.xmlpull.v1.XmlPullParser.END_TAG;
28 import static org.xmlpull.v1.XmlPullParser.TEXT;
30 import android.Manifest.permission;
31 import android.accessibilityservice.AccessibilityServiceInfo;
32 import android.accounts.Account;
33 import android.accounts.AccountManager;
34 import android.annotation.IntDef;
35 import android.annotation.NonNull;
36 import android.annotation.Nullable;
37 import android.annotation.UserIdInt;
38 import android.app.Activity;
39 import android.app.ActivityManager;
40 import android.app.ActivityManagerInternal;
41 import android.app.ActivityManagerNative;
42 import android.app.AlarmManager;
43 import android.app.AppGlobals;
44 import android.app.IActivityManager;
45 import android.app.Notification;
46 import android.app.NotificationManager;
47 import android.app.PendingIntent;
48 import android.app.StatusBarManager;
49 import android.app.admin.DeviceAdminInfo;
50 import android.app.admin.DeviceAdminReceiver;
51 import android.app.admin.DevicePolicyManager;
52 import android.app.admin.DevicePolicyManagerInternal;
53 import android.app.admin.IDevicePolicyManager;
54 import android.app.admin.SecurityLog;
55 import android.app.admin.SecurityLog.SecurityEvent;
56 import android.app.admin.SystemUpdatePolicy;
57 import android.app.backup.IBackupManager;
58 import android.app.trust.TrustManager;
59 import android.content.BroadcastReceiver;
60 import android.content.ComponentName;
61 import android.content.Context;
62 import android.content.Intent;
63 import android.content.IntentFilter;
64 import android.content.pm.ActivityInfo;
65 import android.content.pm.ApplicationInfo;
66 import android.content.pm.IPackageManager;
67 import android.content.pm.PackageInfo;
68 import android.content.pm.PackageManager;
69 import android.content.pm.PackageManager.NameNotFoundException;
70 import android.content.pm.PackageManagerInternal;
71 import android.content.pm.ParceledListSlice;
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.Log;
123 import android.util.Pair;
124 import android.util.Slog;
125 import android.util.SparseArray;
126 import android.util.Xml;
127 import android.view.IWindowManager;
128 import android.view.accessibility.AccessibilityManager;
129 import android.view.accessibility.IAccessibilityManager;
130 import android.view.inputmethod.InputMethodInfo;
131 import android.view.inputmethod.InputMethodManager;
133 import com.android.internal.R;
134 import com.android.internal.annotations.VisibleForTesting;
135 import com.android.internal.statusbar.IStatusBarService;
136 import com.android.internal.util.FastXmlSerializer;
137 import com.android.internal.util.JournaledFile;
138 import com.android.internal.util.ParcelableString;
139 import com.android.internal.util.Preconditions;
140 import com.android.internal.util.XmlUtils;
141 import com.android.internal.widget.LockPatternUtils;
142 import com.android.server.LocalServices;
143 import com.android.server.SystemService;
144 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
145 import com.android.server.pm.UserRestrictionsUtils;
146 import com.google.android.collect.Sets;
148 import org.xmlpull.v1.XmlPullParser;
149 import org.xmlpull.v1.XmlPullParserException;
150 import org.xmlpull.v1.XmlSerializer;
152 import java.io.ByteArrayInputStream;
154 import java.io.FileDescriptor;
155 import java.io.FileInputStream;
156 import java.io.FileNotFoundException;
157 import java.io.FileOutputStream;
158 import java.io.IOException;
159 import java.io.PrintWriter;
160 import java.lang.annotation.Retention;
161 import java.lang.annotation.RetentionPolicy;
162 import java.nio.charset.StandardCharsets;
163 import java.security.cert.CertificateException;
164 import java.security.cert.CertificateFactory;
165 import java.security.cert.X509Certificate;
166 import java.text.DateFormat;
167 import java.util.ArrayList;
168 import java.util.Arrays;
169 import java.util.Collections;
170 import java.util.Date;
171 import java.util.List;
172 import java.util.Map.Entry;
173 import java.util.Set;
174 import java.util.concurrent.atomic.AtomicBoolean;
177 * Implementation of the device policy APIs.
179 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
181 private static final String LOG_TAG = "DevicePolicyManagerService";
183 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
185 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
187 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
189 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
191 private static final String TAG_STATUS_BAR = "statusbar";
193 private static final String ATTR_DISABLED = "disabled";
195 private static final String ATTR_NAME = "name";
197 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
198 "do-not-ask-credentials-on-boot";
200 private static final String TAG_AFFILIATION_ID = "affiliation-id";
202 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
204 private static final String ATTR_VALUE = "value";
206 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
208 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
210 private static final long MS_PER_DAY = 86400 * 1000;
212 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
214 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
215 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
217 private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
218 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
220 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
221 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
222 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
223 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
224 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
225 "device-provisioning-config-applied";
227 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
228 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
229 = "application-restrictions-manager";
232 * System property whose value is either "true" or "false", indicating whether
234 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
236 private static final int STATUS_BAR_DISABLE_MASK =
237 StatusBarManager.DISABLE_EXPAND |
238 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
239 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
240 StatusBarManager.DISABLE_SEARCH;
242 private static final int STATUS_BAR_DISABLE2_MASK =
243 StatusBarManager.DISABLE2_QUICK_SETTINGS;
245 private static final Set<String> SECURE_SETTINGS_WHITELIST;
246 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
247 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
248 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
250 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
251 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
252 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
253 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
255 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
256 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
257 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
259 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
260 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
261 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
262 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
263 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
264 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
265 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
266 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
267 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
269 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
270 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
271 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
272 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
273 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
274 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
278 * Keyguard features that when set on a managed profile that doesn't have its own challenge will
279 * affect the profile's parent user. These can also be set on the managed profile's parent DPM
282 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
283 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
284 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
287 * Keyguard features that when set on a profile affect the profile content or challenge only.
288 * These cannot be set on the managed profile's parent DPM instance
290 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
291 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
293 /** Keyguard features that are allowed to be set on a managed profile */
294 private static final int PROFILE_KEYGUARD_FEATURES =
295 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
297 private static final int CODE_OK = 0;
298 private static final int CODE_HAS_DEVICE_OWNER = 1;
299 private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
300 private static final int CODE_USER_NOT_RUNNING = 3;
301 private static final int CODE_USER_SETUP_COMPLETED = 4;
302 private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
303 private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
304 private static final int CODE_NOT_SYSTEM_USER = 7;
306 @Retention(RetentionPolicy.SOURCE)
307 @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
308 CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
309 private @interface DeviceOwnerPreConditionCode {}
311 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
314 * Minimum timeout in milliseconds after which unlocking with weak auth times out,
315 * i.e. the user has to use a strong authentication method like password, PIN or pattern.
317 private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
319 final Context mContext;
320 final Injector mInjector;
321 final IPackageManager mIPackageManager;
322 final UserManager mUserManager;
323 final UserManagerInternal mUserManagerInternal;
324 final TelephonyManager mTelephonyManager;
325 private final LockPatternUtils mLockPatternUtils;
328 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
329 * is requested for user u.
331 private final Set<Pair<String, Integer>> mPackagesToRemove =
332 new ArraySet<Pair<String, Integer>>();
334 final LocalService mLocalService;
336 // Stores and loads state on device and profile owners.
338 final Owners mOwners;
340 private final Binder mToken = new Binder();
343 * Whether or not device admin feature is supported. If it isn't return defaults for all
348 private final SecurityLogMonitor mSecurityLogMonitor;
350 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
351 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
353 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
356 if(mRemoteBugreportServiceIsActive.get()) {
362 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
365 public void onReceive(Context context, Intent intent) {
366 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
367 && mRemoteBugreportServiceIsActive.get()) {
368 onBugreportFinished(intent);
373 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
376 public void onReceive(Context context, Intent intent) {
377 String action = intent.getAction();
378 mInjector.getNotificationManager().cancel(LOG_TAG,
379 RemoteBugreportUtils.NOTIFICATION_ID);
380 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
381 onBugreportSharingAccepted();
382 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
383 onBugreportSharingDeclined();
385 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
389 public static final class Lifecycle extends SystemService {
390 private DevicePolicyManagerService mService;
392 public Lifecycle(Context context) {
394 mService = new DevicePolicyManagerService(context);
398 public void onStart() {
399 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
403 public void onBootPhase(int phase) {
404 mService.systemReady(phase);
408 public void onStartUser(int userHandle) {
409 mService.onStartUser(userHandle);
413 public static class DevicePolicyData {
414 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
415 int mActivePasswordLength = 0;
416 int mActivePasswordUpperCase = 0;
417 int mActivePasswordLowerCase = 0;
418 int mActivePasswordLetters = 0;
419 int mActivePasswordNumeric = 0;
420 int mActivePasswordSymbols = 0;
421 int mActivePasswordNonLetter = 0;
422 int mFailedPasswordAttempts = 0;
425 int mPasswordOwner = -1;
426 long mLastMaximumTimeToLock = -1;
427 boolean mUserSetupComplete = false;
428 int mUserProvisioningState;
429 int mPermissionPolicy;
431 boolean mDeviceProvisioningConfigApplied = false;
433 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
434 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
435 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
437 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
439 // This is the list of component allowed to start lock task mode.
440 List<String> mLockTaskPackages = new ArrayList<>();
442 boolean mStatusBarDisabled = false;
444 ComponentName mRestrictionsProvider;
446 String mDelegatedCertInstallerPackage;
448 boolean doNotAskCredentialsOnBoot = false;
450 String mApplicationRestrictionsManagingPackage;
452 Set<String> mAffiliationIds = new ArraySet<>();
454 // Used for initialization of users created by createAndManageUsers.
455 boolean mAdminBroadcastPending = false;
456 PersistableBundle mInitBundle = null;
458 public DevicePolicyData(int userHandle) {
459 mUserHandle = userHandle;
463 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
465 final Handler mHandler;
467 BroadcastReceiver mReceiver = new BroadcastReceiver() {
469 public void onReceive(Context context, Intent intent) {
470 final String action = intent.getAction();
471 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
474 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
475 && userHandle == mOwners.getDeviceOwnerUserId()
476 && getDeviceOwnerRemoteBugreportUri() != null) {
477 IntentFilter filterConsent = new IntentFilter();
478 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
479 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
480 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
481 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
482 RemoteBugreportUtils.NOTIFICATION_ID,
483 RemoteBugreportUtils.buildNotification(mContext,
484 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
487 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
488 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
490 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
491 + action + " for user " + userHandle);
493 mHandler.post(new Runnable() {
496 handlePasswordExpirationNotification(userHandle);
500 if (Intent.ACTION_USER_UNLOCKED.equals(action)
501 || Intent.ACTION_USER_STARTED.equals(action)
502 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
503 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
504 new MonitoringCertNotificationTask().execute(userId);
506 if (Intent.ACTION_USER_ADDED.equals(action)) {
507 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
508 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
509 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
510 removeUserData(userHandle);
511 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
512 synchronized (DevicePolicyManagerService.this) {
513 // Reset the policy data
514 mUserData.remove(userHandle);
515 sendAdminEnabledBroadcastLocked(userHandle);
517 handlePackagesChanged(null /* check all admins */, userHandle);
518 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
519 handlePackagesChanged(null /* check all admins */, userHandle);
520 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
521 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
522 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
523 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
524 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
525 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
526 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
527 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
528 clearWipeProfileNotification();
533 static class ActiveAdmin {
534 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
535 private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
536 private static final String TAG_DISABLE_CAMERA = "disable-camera";
537 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
538 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
539 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
540 = "disable-bt-contacts-sharing";
541 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
542 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
543 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
544 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
545 private static final String TAG_ACCOUNT_TYPE = "account-type";
546 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
547 = "permitted-accessiblity-services";
548 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
549 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
550 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
551 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
552 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
553 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
554 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
555 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
556 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
557 private static final String TAG_PERMITTED_IMES = "permitted-imes";
558 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
559 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
560 private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
561 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
562 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
563 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
564 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
565 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
566 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
567 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
568 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
569 private static final String ATTR_VALUE = "value";
570 private static final String TAG_PASSWORD_QUALITY = "password-quality";
571 private static final String TAG_POLICIES = "policies";
572 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
573 "cross-profile-widget-providers";
574 private static final String TAG_PROVIDER = "provider";
575 private static final String TAG_PACKAGE_LIST_ITEM = "item";
576 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
577 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
578 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
579 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
580 private static final String TAG_PARENT_ADMIN = "parent-admin";
581 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
582 private static final String TAG_ORGANIZATION_NAME = "organization-name";
584 final DeviceAdminInfo info;
586 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
588 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
589 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
591 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
592 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
594 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
595 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
597 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
598 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
600 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
601 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
603 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
604 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
606 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
607 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
609 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
610 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
612 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
613 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
615 long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
617 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
618 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
620 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
621 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
623 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
624 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
626 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
628 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
630 boolean encryptionRequested = false;
631 boolean testOnlyAdmin = false;
632 boolean disableCamera = false;
633 boolean disableCallerId = false;
634 boolean disableContactsSearch = false;
635 boolean disableBluetoothContactSharing = true;
636 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
637 boolean requireAutoTime = false; // Can only be set by a device owner.
638 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
640 ActiveAdmin parentAdmin;
641 final boolean isParent;
643 static class TrustAgentInfo {
644 public PersistableBundle options;
645 TrustAgentInfo(PersistableBundle bundle) {
650 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
652 // The list of permitted accessibility services package namesas set by a profile
653 // or device owner. Null means all accessibility services are allowed, empty means
654 // none except system services are allowed.
655 List<String> permittedAccessiblityServices;
657 // The list of permitted input methods package names as set by a profile or device owner.
658 // Null means all input methods are allowed, empty means none except system imes are
660 List<String> permittedInputMethods;
662 // List of package names to keep cached.
663 List<String> keepUninstalledPackages;
665 // TODO: review implementation decisions with frameworks team
666 boolean specifiesGlobalProxy = false;
667 String globalProxySpec = null;
668 String globalProxyExclusionList = null;
670 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
672 List<String> crossProfileWidgetProviders;
674 Bundle userRestrictions;
676 // Support text provided by the admin to display to the user.
677 CharSequence shortSupportMessage = null;
678 CharSequence longSupportMessage = null;
680 // Background color of confirm credentials screen. Default: teal.
681 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
682 int organizationColor = DEF_ORGANIZATION_COLOR;
684 // Default title of confirm credentials screen
685 String organizationName = null;
687 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
692 ActiveAdmin getParentActiveAdmin() {
693 Preconditions.checkState(!isParent);
695 if (parentAdmin == null) {
696 parentAdmin = new ActiveAdmin(info, /* parent */ true);
701 boolean hasParentActiveAdmin() {
702 return parentAdmin != null;
705 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
707 public UserHandle getUserHandle() {
708 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
711 void writeToXml(XmlSerializer out)
712 throws IllegalArgumentException, IllegalStateException, IOException {
713 out.startTag(null, TAG_POLICIES);
714 info.writePoliciesToXml(out);
715 out.endTag(null, TAG_POLICIES);
716 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
717 out.startTag(null, TAG_PASSWORD_QUALITY);
718 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
719 out.endTag(null, TAG_PASSWORD_QUALITY);
720 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
721 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
722 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
723 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
725 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
726 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
727 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
728 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
730 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
731 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
732 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
733 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
735 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
736 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
737 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
738 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
740 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
741 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
742 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
743 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
745 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
746 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
747 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
748 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
750 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
751 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
752 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
753 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
755 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
756 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
757 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
758 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
761 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
762 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
763 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
764 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
766 if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
767 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
768 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
769 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
771 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
772 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
773 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
774 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
776 if (specifiesGlobalProxy) {
777 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
778 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
779 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
780 if (globalProxySpec != null) {
781 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
782 out.attribute(null, ATTR_VALUE, globalProxySpec);
783 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
785 if (globalProxyExclusionList != null) {
786 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
787 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
788 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
791 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
792 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
793 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
794 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
796 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
797 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
798 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
799 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
801 if (encryptionRequested) {
802 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
803 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
804 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
807 out.startTag(null, TAG_TEST_ONLY_ADMIN);
808 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
809 out.endTag(null, TAG_TEST_ONLY_ADMIN);
812 out.startTag(null, TAG_DISABLE_CAMERA);
813 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
814 out.endTag(null, TAG_DISABLE_CAMERA);
816 if (disableCallerId) {
817 out.startTag(null, TAG_DISABLE_CALLER_ID);
818 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
819 out.endTag(null, TAG_DISABLE_CALLER_ID);
821 if (disableContactsSearch) {
822 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
823 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
824 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
826 if (!disableBluetoothContactSharing) {
827 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
828 out.attribute(null, ATTR_VALUE,
829 Boolean.toString(disableBluetoothContactSharing));
830 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
832 if (disableScreenCapture) {
833 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
834 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
835 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
837 if (requireAutoTime) {
838 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
839 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
840 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
842 if (forceEphemeralUsers) {
843 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
844 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
845 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
847 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
848 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
849 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
850 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
852 if (!accountTypesWithManagementDisabled.isEmpty()) {
853 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
854 for (String ac : accountTypesWithManagementDisabled) {
855 out.startTag(null, TAG_ACCOUNT_TYPE);
856 out.attribute(null, ATTR_VALUE, ac);
857 out.endTag(null, TAG_ACCOUNT_TYPE);
859 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
861 if (!trustAgentInfos.isEmpty()) {
862 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
863 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
864 for (Entry<String, TrustAgentInfo> entry : set) {
865 TrustAgentInfo trustAgentInfo = entry.getValue();
866 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
867 out.attribute(null, ATTR_VALUE, entry.getKey());
868 if (trustAgentInfo.options != null) {
869 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
871 trustAgentInfo.options.saveToXml(out);
872 } catch (XmlPullParserException e) {
873 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
875 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
877 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
879 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
881 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
882 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
883 final int providerCount = crossProfileWidgetProviders.size();
884 for (int i = 0; i < providerCount; i++) {
885 String provider = crossProfileWidgetProviders.get(i);
886 out.startTag(null, TAG_PROVIDER);
887 out.attribute(null, ATTR_VALUE, provider);
888 out.endTag(null, TAG_PROVIDER);
890 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
892 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
893 permittedAccessiblityServices);
894 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
895 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
896 if (hasUserRestrictions()) {
897 UserRestrictionsUtils.writeRestrictions(
898 out, userRestrictions, TAG_USER_RESTRICTIONS);
900 if (!TextUtils.isEmpty(shortSupportMessage)) {
901 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
902 out.text(shortSupportMessage.toString());
903 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
905 if (!TextUtils.isEmpty(longSupportMessage)) {
906 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
907 out.text(longSupportMessage.toString());
908 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
910 if (parentAdmin != null) {
911 out.startTag(null, TAG_PARENT_ADMIN);
912 parentAdmin.writeToXml(out);
913 out.endTag(null, TAG_PARENT_ADMIN);
915 if (organizationColor != DEF_ORGANIZATION_COLOR) {
916 out.startTag(null, TAG_ORGANIZATION_COLOR);
917 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
918 out.endTag(null, TAG_ORGANIZATION_COLOR);
920 if (organizationName != null) {
921 out.startTag(null, TAG_ORGANIZATION_NAME);
922 out.text(organizationName);
923 out.endTag(null, TAG_ORGANIZATION_NAME);
927 void writePackageListToXml(XmlSerializer out, String outerTag,
928 List<String> packageList)
929 throws IllegalArgumentException, IllegalStateException, IOException {
930 if (packageList == null) {
934 out.startTag(null, outerTag);
935 for (String packageName : packageList) {
936 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
937 out.attribute(null, ATTR_VALUE, packageName);
938 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
940 out.endTag(null, outerTag);
943 void readFromXml(XmlPullParser parser)
944 throws XmlPullParserException, IOException {
945 int outerDepth = parser.getDepth();
947 while ((type=parser.next()) != END_DOCUMENT
948 && (type != END_TAG || parser.getDepth() > outerDepth)) {
949 if (type == END_TAG || type == TEXT) {
952 String tag = parser.getName();
953 if (TAG_POLICIES.equals(tag)) {
954 info.readPoliciesFromXml(parser);
955 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
956 passwordQuality = Integer.parseInt(
957 parser.getAttributeValue(null, ATTR_VALUE));
958 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
959 minimumPasswordLength = Integer.parseInt(
960 parser.getAttributeValue(null, ATTR_VALUE));
961 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
962 passwordHistoryLength = Integer.parseInt(
963 parser.getAttributeValue(null, ATTR_VALUE));
964 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
965 minimumPasswordUpperCase = Integer.parseInt(
966 parser.getAttributeValue(null, ATTR_VALUE));
967 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
968 minimumPasswordLowerCase = Integer.parseInt(
969 parser.getAttributeValue(null, ATTR_VALUE));
970 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
971 minimumPasswordLetters = Integer.parseInt(
972 parser.getAttributeValue(null, ATTR_VALUE));
973 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
974 minimumPasswordNumeric = Integer.parseInt(
975 parser.getAttributeValue(null, ATTR_VALUE));
976 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
977 minimumPasswordSymbols = Integer.parseInt(
978 parser.getAttributeValue(null, ATTR_VALUE));
979 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
980 minimumPasswordNonLetter = Integer.parseInt(
981 parser.getAttributeValue(null, ATTR_VALUE));
982 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
983 maximumTimeToUnlock = Long.parseLong(
984 parser.getAttributeValue(null, ATTR_VALUE));
985 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
986 strongAuthUnlockTimeout = Long.parseLong(
987 parser.getAttributeValue(null, ATTR_VALUE));
988 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
989 maximumFailedPasswordsForWipe = Integer.parseInt(
990 parser.getAttributeValue(null, ATTR_VALUE));
991 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
992 specifiesGlobalProxy = Boolean.parseBoolean(
993 parser.getAttributeValue(null, ATTR_VALUE));
994 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
996 parser.getAttributeValue(null, ATTR_VALUE);
997 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
998 globalProxyExclusionList =
999 parser.getAttributeValue(null, ATTR_VALUE);
1000 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1001 passwordExpirationTimeout = Long.parseLong(
1002 parser.getAttributeValue(null, ATTR_VALUE));
1003 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1004 passwordExpirationDate = Long.parseLong(
1005 parser.getAttributeValue(null, ATTR_VALUE));
1006 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1007 encryptionRequested = Boolean.parseBoolean(
1008 parser.getAttributeValue(null, ATTR_VALUE));
1009 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1010 testOnlyAdmin = Boolean.parseBoolean(
1011 parser.getAttributeValue(null, ATTR_VALUE));
1012 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1013 disableCamera = Boolean.parseBoolean(
1014 parser.getAttributeValue(null, ATTR_VALUE));
1015 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1016 disableCallerId = Boolean.parseBoolean(
1017 parser.getAttributeValue(null, ATTR_VALUE));
1018 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1019 disableContactsSearch = Boolean.parseBoolean(
1020 parser.getAttributeValue(null, ATTR_VALUE));
1021 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1022 disableBluetoothContactSharing = Boolean.parseBoolean(parser
1023 .getAttributeValue(null, ATTR_VALUE));
1024 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1025 disableScreenCapture = Boolean.parseBoolean(
1026 parser.getAttributeValue(null, ATTR_VALUE));
1027 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1028 requireAutoTime = Boolean.parseBoolean(
1029 parser.getAttributeValue(null, ATTR_VALUE));
1030 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1031 forceEphemeralUsers = Boolean.parseBoolean(
1032 parser.getAttributeValue(null, ATTR_VALUE));
1033 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1034 disabledKeyguardFeatures = Integer.parseInt(
1035 parser.getAttributeValue(null, ATTR_VALUE));
1036 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1037 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
1038 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1039 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1040 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1041 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
1042 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1043 permittedAccessiblityServices = readPackageList(parser, tag);
1044 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1045 permittedInputMethods = readPackageList(parser, tag);
1046 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1047 keepUninstalledPackages = readPackageList(parser, tag);
1048 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1049 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
1050 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1051 type = parser.next();
1052 if (type == XmlPullParser.TEXT) {
1053 shortSupportMessage = parser.getText();
1055 Log.w(LOG_TAG, "Missing text when loading short support message");
1057 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1058 type = parser.next();
1059 if (type == XmlPullParser.TEXT) {
1060 longSupportMessage = parser.getText();
1062 Log.w(LOG_TAG, "Missing text when loading long support message");
1064 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1065 Preconditions.checkState(!isParent);
1067 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1068 parentAdmin.readFromXml(parser);
1069 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1070 organizationColor = Integer.parseInt(
1071 parser.getAttributeValue(null, ATTR_VALUE));
1072 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1073 type = parser.next();
1074 if (type == XmlPullParser.TEXT) {
1075 organizationName = parser.getText();
1077 Log.w(LOG_TAG, "Missing text when loading organization name");
1080 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1081 XmlUtils.skipCurrentTag(parser);
1086 private List<String> readPackageList(XmlPullParser parser,
1087 String tag) throws XmlPullParserException, IOException {
1088 List<String> result = new ArrayList<String>();
1089 int outerDepth = parser.getDepth();
1091 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1092 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1093 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1096 String outerTag = parser.getName();
1097 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1098 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1099 if (packageName != null) {
1100 result.add(packageName);
1102 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1105 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1111 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1112 throws XmlPullParserException, IOException {
1113 int outerDepthDAM = parser.getDepth();
1115 Set<String> result = new ArraySet<>();
1116 while ((typeDAM=parser.next()) != END_DOCUMENT
1117 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1118 if (typeDAM == END_TAG || typeDAM == TEXT) {
1121 String tagDAM = parser.getName();
1122 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1123 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1125 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1131 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1132 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1133 int outerDepthDAM = parser.getDepth();
1135 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1136 while ((typeDAM=parser.next()) != END_DOCUMENT
1137 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1138 if (typeDAM == END_TAG || typeDAM == TEXT) {
1141 String tagDAM = parser.getName();
1142 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1143 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1144 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1145 result.put(component, trustAgentInfo);
1147 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1153 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1154 throws XmlPullParserException, IOException {
1155 int outerDepthDAM = parser.getDepth();
1157 TrustAgentInfo result = new TrustAgentInfo(null);
1158 while ((typeDAM=parser.next()) != END_DOCUMENT
1159 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1160 if (typeDAM == END_TAG || typeDAM == TEXT) {
1163 String tagDAM = parser.getName();
1164 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1165 result.options = PersistableBundle.restoreFromXml(parser);
1167 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1173 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1174 throws XmlPullParserException, IOException {
1175 int outerDepthDAM = parser.getDepth();
1177 ArrayList<String> result = null;
1178 while ((typeDAM=parser.next()) != END_DOCUMENT
1179 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1180 if (typeDAM == END_TAG || typeDAM == TEXT) {
1183 String tagDAM = parser.getName();
1184 if (TAG_PROVIDER.equals(tagDAM)) {
1185 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1186 if (result == null) {
1187 result = new ArrayList<>();
1189 result.add(provider);
1191 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1197 boolean hasUserRestrictions() {
1198 return userRestrictions != null && userRestrictions.size() > 0;
1201 Bundle ensureUserRestrictions() {
1202 if (userRestrictions == null) {
1203 userRestrictions = new Bundle();
1205 return userRestrictions;
1208 void dump(String prefix, PrintWriter pw) {
1209 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1210 pw.print(prefix); pw.print("testOnlyAdmin=");
1211 pw.println(testOnlyAdmin);
1212 pw.print(prefix); pw.println("policies:");
1213 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1215 for (int i=0; i<pols.size(); i++) {
1216 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1219 pw.print(prefix); pw.print("passwordQuality=0x");
1220 pw.println(Integer.toHexString(passwordQuality));
1221 pw.print(prefix); pw.print("minimumPasswordLength=");
1222 pw.println(minimumPasswordLength);
1223 pw.print(prefix); pw.print("passwordHistoryLength=");
1224 pw.println(passwordHistoryLength);
1225 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1226 pw.println(minimumPasswordUpperCase);
1227 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1228 pw.println(minimumPasswordLowerCase);
1229 pw.print(prefix); pw.print("minimumPasswordLetters=");
1230 pw.println(minimumPasswordLetters);
1231 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1232 pw.println(minimumPasswordNumeric);
1233 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1234 pw.println(minimumPasswordSymbols);
1235 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1236 pw.println(minimumPasswordNonLetter);
1237 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1238 pw.println(maximumTimeToUnlock);
1239 pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1240 pw.println(strongAuthUnlockTimeout);
1241 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1242 pw.println(maximumFailedPasswordsForWipe);
1243 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1244 pw.println(specifiesGlobalProxy);
1245 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1246 pw.println(passwordExpirationTimeout);
1247 pw.print(prefix); pw.print("passwordExpirationDate=");
1248 pw.println(passwordExpirationDate);
1249 if (globalProxySpec != null) {
1250 pw.print(prefix); pw.print("globalProxySpec=");
1251 pw.println(globalProxySpec);
1253 if (globalProxyExclusionList != null) {
1254 pw.print(prefix); pw.print("globalProxyEclusionList=");
1255 pw.println(globalProxyExclusionList);
1257 pw.print(prefix); pw.print("encryptionRequested=");
1258 pw.println(encryptionRequested);
1259 pw.print(prefix); pw.print("disableCamera=");
1260 pw.println(disableCamera);
1261 pw.print(prefix); pw.print("disableCallerId=");
1262 pw.println(disableCallerId);
1263 pw.print(prefix); pw.print("disableContactsSearch=");
1264 pw.println(disableContactsSearch);
1265 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1266 pw.println(disableBluetoothContactSharing);
1267 pw.print(prefix); pw.print("disableScreenCapture=");
1268 pw.println(disableScreenCapture);
1269 pw.print(prefix); pw.print("requireAutoTime=");
1270 pw.println(requireAutoTime);
1271 pw.print(prefix); pw.print("forceEphemeralUsers=");
1272 pw.println(forceEphemeralUsers);
1273 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1274 pw.println(disabledKeyguardFeatures);
1275 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1276 pw.println(crossProfileWidgetProviders);
1277 if (permittedAccessiblityServices != null) {
1278 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1279 pw.println(permittedAccessiblityServices);
1281 if (permittedInputMethods != null) {
1282 pw.print(prefix); pw.print("permittedInputMethods=");
1283 pw.println(permittedInputMethods);
1285 if (keepUninstalledPackages != null) {
1286 pw.print(prefix); pw.print("keepUninstalledPackages=");
1287 pw.println(keepUninstalledPackages);
1289 pw.print(prefix); pw.print("organizationColor=");
1290 pw.println(organizationColor);
1291 if (organizationName != null) {
1292 pw.print(prefix); pw.print("organizationName=");
1293 pw.println(organizationName);
1295 pw.print(prefix); pw.println("userRestrictions:");
1296 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1297 pw.print(prefix); pw.print("isParent=");
1298 pw.println(isParent);
1299 if (parentAdmin != null) {
1300 pw.print(prefix); pw.println("parentAdmin:");
1301 parentAdmin.dump(prefix + " ", pw);
1306 private void handlePackagesChanged(String packageName, int userHandle) {
1307 boolean removed = false;
1308 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1309 DevicePolicyData policy = getUserData(userHandle);
1310 synchronized (this) {
1311 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1312 ActiveAdmin aa = policy.mAdminList.get(i);
1314 // If we're checking all packages or if the specific one we're checking matches,
1315 // then check if the package and receiver still exist.
1316 final String adminPackage = aa.info.getPackageName();
1317 if (packageName == null || packageName.equals(adminPackage)) {
1318 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1319 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1320 PackageManager.MATCH_DIRECT_BOOT_AWARE
1321 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1322 userHandle) == null) {
1324 policy.mAdminList.remove(i);
1325 policy.mAdminMap.remove(aa.info.getComponent());
1328 } catch (RemoteException re) {
1333 validatePasswordOwnerLocked(policy);
1334 saveSettingsLocked(policy.mUserHandle);
1337 // Check if delegated cert installer or app restrictions managing packages are removed.
1338 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1339 policy.mDelegatedCertInstallerPackage = null;
1340 saveSettingsLocked(policy.mUserHandle);
1342 if (isRemovedPackage(
1343 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1344 policy.mApplicationRestrictionsManagingPackage = null;
1345 saveSettingsLocked(policy.mUserHandle);
1349 // The removed admin might have disabled camera, so update user restrictions.
1350 pushUserRestrictions(userHandle);
1354 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1356 return targetPackage != null
1357 && (changedPackage == null || changedPackage.equals(targetPackage))
1358 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1359 } catch (RemoteException e) {
1367 * Unit test will subclass it to inject mocks.
1370 static class Injector {
1372 private final Context mContext;
1374 Injector(Context context) {
1378 Owners newOwners() {
1379 return new Owners(getUserManager(), getUserManagerInternal(),
1380 getPackageManagerInternal());
1383 UserManager getUserManager() {
1384 return UserManager.get(mContext);
1387 UserManagerInternal getUserManagerInternal() {
1388 return LocalServices.getService(UserManagerInternal.class);
1391 PackageManagerInternal getPackageManagerInternal() {
1392 return LocalServices.getService(PackageManagerInternal.class);
1395 NotificationManager getNotificationManager() {
1396 return mContext.getSystemService(NotificationManager.class);
1399 PowerManagerInternal getPowerManagerInternal() {
1400 return LocalServices.getService(PowerManagerInternal.class);
1403 TelephonyManager getTelephonyManager() {
1404 return TelephonyManager.from(mContext);
1407 TrustManager getTrustManager() {
1408 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1411 IWindowManager getIWindowManager() {
1412 return IWindowManager.Stub
1413 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1416 IActivityManager getIActivityManager() {
1417 return ActivityManagerNative.getDefault();
1420 IPackageManager getIPackageManager() {
1421 return AppGlobals.getPackageManager();
1424 IBackupManager getIBackupManager() {
1425 return IBackupManager.Stub.asInterface(
1426 ServiceManager.getService(Context.BACKUP_SERVICE));
1429 IAudioService getIAudioService() {
1430 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1433 LockPatternUtils newLockPatternUtils() {
1434 return new LockPatternUtils(mContext);
1437 boolean storageManagerIsFileBasedEncryptionEnabled() {
1438 return StorageManager.isFileEncryptedNativeOnly();
1441 boolean storageManagerIsNonDefaultBlockEncrypted() {
1442 long identity = Binder.clearCallingIdentity();
1444 return StorageManager.isNonDefaultBlockEncrypted();
1446 Binder.restoreCallingIdentity(identity);
1450 boolean storageManagerIsEncrypted() {
1451 return StorageManager.isEncrypted();
1454 boolean storageManagerIsEncryptable() {
1455 return StorageManager.isEncryptable();
1458 Looper getMyLooper() {
1459 return Looper.myLooper();
1462 WifiManager getWifiManager() {
1463 return mContext.getSystemService(WifiManager.class);
1466 long binderClearCallingIdentity() {
1467 return Binder.clearCallingIdentity();
1470 void binderRestoreCallingIdentity(long token) {
1471 Binder.restoreCallingIdentity(token);
1474 int binderGetCallingUid() {
1475 return Binder.getCallingUid();
1478 int binderGetCallingPid() {
1479 return Binder.getCallingPid();
1482 UserHandle binderGetCallingUserHandle() {
1483 return Binder.getCallingUserHandle();
1486 boolean binderIsCallingUidMyUid() {
1487 return getCallingUid() == Process.myUid();
1490 final int userHandleGetCallingUserId() {
1491 return UserHandle.getUserId(binderGetCallingUid());
1494 File environmentGetUserSystemDirectory(int userId) {
1495 return Environment.getUserSystemDirectory(userId);
1498 void powerManagerGoToSleep(long time, int reason, int flags) {
1499 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1502 void powerManagerReboot(String reason) {
1503 mContext.getSystemService(PowerManager.class).reboot(reason);
1506 boolean systemPropertiesGetBoolean(String key, boolean def) {
1507 return SystemProperties.getBoolean(key, def);
1510 long systemPropertiesGetLong(String key, long def) {
1511 return SystemProperties.getLong(key, def);
1514 String systemPropertiesGet(String key, String def) {
1515 return SystemProperties.get(key, def);
1518 String systemPropertiesGet(String key) {
1519 return SystemProperties.get(key);
1522 void systemPropertiesSet(String key, String value) {
1523 SystemProperties.set(key, value);
1526 boolean userManagerIsSplitSystemUser() {
1527 return UserManager.isSplitSystemUser();
1530 String getDevicePolicyFilePathForSystemUser() {
1531 return "/data/system/";
1534 void registerContentObserver(Uri uri, boolean notifyForDescendents,
1535 ContentObserver observer, int userHandle) {
1536 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1537 observer, userHandle);
1540 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1541 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1542 name, def, userHandle);
1545 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1546 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1547 name, value, userHandle);
1550 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1551 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1552 name, value, userHandle);
1555 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1556 Settings.Global.putStringForUser(mContext.getContentResolver(),
1557 name, value, userHandle);
1560 void settingsSecurePutInt(String name, int value) {
1561 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1564 int settingsGlobalGetInt(String name, int def) {
1565 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1568 void settingsGlobalPutInt(String name, int value) {
1569 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1572 void settingsSecurePutString(String name, String value) {
1573 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1576 void settingsGlobalPutString(String name, String value) {
1577 Settings.Global.putString(mContext.getContentResolver(), name, value);
1580 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1581 SecurityLog.setLoggingEnabledProperty(enabled);
1584 boolean securityLogGetLoggingEnabledProperty() {
1585 return SecurityLog.getLoggingEnabledProperty();
1588 boolean securityLogIsLoggingEnabled() {
1589 return SecurityLog.isLoggingEnabled();
1594 * Instantiates the service.
1596 public DevicePolicyManagerService(Context context) {
1597 this(new Injector(context));
1601 DevicePolicyManagerService(Injector injector) {
1602 mInjector = injector;
1603 mContext = Preconditions.checkNotNull(injector.mContext);
1604 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1605 mOwners = Preconditions.checkNotNull(injector.newOwners());
1607 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1608 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1609 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1610 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1612 mLocalService = new LocalService();
1613 mLockPatternUtils = injector.newLockPatternUtils();
1615 mSecurityLogMonitor = new SecurityLogMonitor(this);
1617 mHasFeature = mContext.getPackageManager()
1618 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1620 // Skip the rest of the initialization
1623 IntentFilter filter = new IntentFilter();
1624 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1625 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1626 filter.addAction(Intent.ACTION_USER_ADDED);
1627 filter.addAction(Intent.ACTION_USER_REMOVED);
1628 filter.addAction(Intent.ACTION_USER_STARTED);
1629 filter.addAction(Intent.ACTION_USER_UNLOCKED);
1630 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1631 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1632 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1633 filter = new IntentFilter();
1634 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1635 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1636 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1637 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1638 filter.addDataScheme("package");
1639 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1640 filter = new IntentFilter();
1641 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1642 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1644 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1648 * Creates and loads the policy data from xml.
1649 * @param userHandle the user for whom to load the policy data
1653 DevicePolicyData getUserData(int userHandle) {
1654 synchronized (this) {
1655 DevicePolicyData policy = mUserData.get(userHandle);
1656 if (policy == null) {
1657 policy = new DevicePolicyData(userHandle);
1658 mUserData.append(userHandle, policy);
1659 loadSettingsLocked(policy, userHandle);
1666 * Creates and loads the policy data from xml for data that is shared between
1667 * various profiles of a user. In contrast to {@link #getUserData(int)}
1668 * it allows access to data of users other than the calling user.
1670 * This function should only be used for shared data, e.g. everything regarding
1671 * passwords and should be removed once multiple screen locks are present.
1672 * @param userHandle the user for whom to load the policy data
1675 DevicePolicyData getUserDataUnchecked(int userHandle) {
1676 long ident = mInjector.binderClearCallingIdentity();
1678 return getUserData(userHandle);
1680 mInjector.binderRestoreCallingIdentity(ident);
1684 void removeUserData(int userHandle) {
1685 synchronized (this) {
1686 if (userHandle == UserHandle.USER_SYSTEM) {
1687 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1690 mOwners.removeProfileOwner(userHandle);
1691 mOwners.writeProfileOwner(userHandle);
1693 DevicePolicyData policy = mUserData.get(userHandle);
1694 if (policy != null) {
1695 mUserData.remove(userHandle);
1697 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1698 DEVICE_POLICIES_XML);
1699 policyFile.delete();
1700 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1702 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1706 synchronized (this) {
1708 setDeviceOwnerSystemPropertyLocked();
1709 findOwnerComponentIfNecessaryLocked();
1710 migrateUserRestrictionsIfNecessaryLocked();
1712 // TODO PO may not have a class name either due to b/17652534. Address that too.
1714 updateDeviceOwnerLocked();
1718 private void setDeviceOwnerSystemPropertyLocked() {
1719 // Device owner may still be provisioned, do not set the read-only system property yet.
1720 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1723 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1724 // always false at this point.
1725 if (StorageManager.inCryptKeeperBounce()) {
1729 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1730 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1732 if (mOwners.hasDeviceOwner()) {
1733 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1734 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1735 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
1736 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1737 mSecurityLogMonitor.start();
1740 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1741 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1746 private void findOwnerComponentIfNecessaryLocked() {
1747 if (!mOwners.hasDeviceOwner()) {
1750 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1752 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1753 return; // Already a full component name.
1756 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1757 doComponentName.getPackageName(),
1758 mOwners.getDeviceOwnerUserId());
1759 if (doComponent == null) {
1760 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1762 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1764 mOwners.getDeviceOwnerName(),
1765 mOwners.getDeviceOwnerUserId(),
1766 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1767 mOwners.writeDeviceOwner();
1769 Log.v(LOG_TAG, "Device owner component filled in");
1775 * We didn't use to persist user restrictions for each owners but only persisted in user
1778 private void migrateUserRestrictionsIfNecessaryLocked() {
1779 boolean migrated = false;
1780 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1781 // except for the "system controlled" ones.
1782 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1784 Log.v(LOG_TAG, "Migrating DO user restrictions");
1788 // Migrate user 0 restrictions to DO.
1789 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1791 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1792 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1794 // Push DO user restrictions to user manager.
1795 pushUserRestrictions(UserHandle.USER_SYSTEM);
1797 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1802 // The following restrictions can be set on secondary users by the device owner, so we
1803 // assume they're not from the PO.
1804 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1805 UserManager.DISALLOW_OUTGOING_CALLS,
1806 UserManager.DISALLOW_SMS);
1808 for (UserInfo ui : mUserManager.getUsers()) {
1809 final int userId = ui.id;
1810 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1812 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1816 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1818 final Set<String> exceptionList =
1819 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1821 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1822 exceptionList, /* isDeviceOwner =*/ false);
1824 // Note if a secondary user has no PO but has a DA that disables camera, we
1825 // don't get here and won't push the camera user restriction to UserManager
1826 // here. That's okay because we'll push user restrictions anyway when a user
1827 // starts. But we still do it because we want to let user manager persist
1829 pushUserRestrictions(userId);
1831 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1834 if (VERBOSE_LOG && migrated) {
1835 Log.v(LOG_TAG, "User restrictions migrated.");
1839 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1840 Set<String> exceptionList, boolean isDeviceOwner) {
1841 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1842 user.getIdentifier());
1844 final Bundle newBaseRestrictions = new Bundle();
1845 final Bundle newOwnerRestrictions = new Bundle();
1847 for (String key : origRestrictions.keySet()) {
1848 if (!origRestrictions.getBoolean(key)) {
1851 final boolean canOwnerChange = isDeviceOwner
1852 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1853 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1855 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1856 newBaseRestrictions.putBoolean(key, true);
1858 newOwnerRestrictions.putBoolean(key, true);
1863 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1864 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1865 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1867 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1868 newBaseRestrictions);
1870 if (admin != null) {
1871 admin.ensureUserRestrictions().clear();
1872 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1874 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1876 saveSettingsLocked(user.getIdentifier());
1879 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1880 final DevicePolicyData policy = getUserData(userId);
1881 final int n = policy.mAdminList.size();
1882 ComponentName found = null;
1884 for (int i = 0; i < n; i++) {
1885 final ActiveAdmin admin = policy.mAdminList.get(i);
1886 if (packageName.equals(admin.info.getPackageName())) {
1889 found = admin.info.getComponent();
1895 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1901 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1902 * reminders. Clears alarm if no expirations are configured.
1904 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1905 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1906 final long now = System.currentTimeMillis();
1907 final long timeToExpire = expiration - now;
1908 final long alarmTime;
1909 if (expiration == 0) {
1910 // No expirations are currently configured: Cancel alarm.
1912 } else if (timeToExpire <= 0) {
1913 // The password has already expired: Repeat every 24 hours.
1914 alarmTime = now + MS_PER_DAY;
1916 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1917 // the expiration time.
1918 long alarmInterval = timeToExpire % MS_PER_DAY;
1919 if (alarmInterval == 0) {
1920 alarmInterval = MS_PER_DAY;
1922 alarmTime = now + alarmInterval;
1925 long token = mInjector.binderClearCallingIdentity();
1927 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1928 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1929 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1930 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1931 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1932 UserHandle.of(affectedUserHandle));
1934 if (alarmTime != 0) {
1935 am.set(AlarmManager.RTC, alarmTime, pi);
1938 mInjector.binderRestoreCallingIdentity(token);
1942 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1943 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1945 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1946 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1952 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
1954 enforceManagedProfile(userHandle, "call APIs on the parent profile");
1956 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1957 if (admin != null && parent) {
1958 admin = admin.getParentActiveAdmin();
1963 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1964 throws SecurityException {
1965 final int callingUid = mInjector.binderGetCallingUid();
1967 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1968 if (result != null) {
1973 final int userId = UserHandle.getUserId(callingUid);
1974 final DevicePolicyData policy = getUserData(userId);
1975 ActiveAdmin admin = policy.mAdminMap.get(who);
1976 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1977 throw new SecurityException("Admin " + admin.info.getComponent()
1978 + " does not own the device");
1980 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1981 throw new SecurityException("Admin " + admin.info.getComponent()
1982 + " does not own the profile");
1984 throw new SecurityException("Admin " + admin.info.getComponent()
1985 + " did not specify uses-policy for: "
1986 + admin.info.getTagForPolicy(reqPolicy));
1988 throw new SecurityException("No active admin owned by uid "
1989 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
1993 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
1994 throws SecurityException {
1996 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
1997 "call APIs on the parent profile");
1999 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2000 return parent ? admin.getParentActiveAdmin() : admin;
2003 * Find the admin for the component and userId bit of the uid, then check
2004 * the admin's uid matches the uid.
2006 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2007 final int userId = UserHandle.getUserId(uid);
2008 final DevicePolicyData policy = getUserData(userId);
2009 ActiveAdmin admin = policy.mAdminMap.get(who);
2010 if (admin == null) {
2011 throw new SecurityException("No active admin " + who);
2013 if (admin.getUid() != uid) {
2014 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2019 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2021 // Try to find an admin which can use reqPolicy
2022 final int userId = UserHandle.getUserId(uid);
2023 final DevicePolicyData policy = getUserData(userId);
2025 ActiveAdmin admin = policy.mAdminMap.get(who);
2026 if (admin == null) {
2027 throw new SecurityException("No active admin " + who);
2029 if (admin.getUid() != uid) {
2030 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2032 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2036 for (ActiveAdmin admin : policy.mAdminList) {
2037 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2048 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2050 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2051 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2053 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2055 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2056 // DO always has the PO power.
2057 return ownsDevice || ownsProfile;
2059 return admin.info.usesPolicy(reqPolicy);
2063 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2064 sendAdminCommandLocked(admin, action, null);
2067 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2068 sendAdminCommandLocked(admin, action, null, result);
2072 * Send an update to one specific admin, get notified when that admin returns a result.
2074 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2075 BroadcastReceiver result) {
2076 Intent intent = new Intent(action);
2077 intent.setComponent(admin.info.getComponent());
2078 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2079 intent.putExtra("expiration", admin.passwordExpirationDate);
2081 if (adminExtras != null) {
2082 intent.putExtras(adminExtras);
2084 if (result != null) {
2085 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2086 null, result, mHandler, Activity.RESULT_OK, null, null);
2088 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2093 * Send an update to all admins of a user that enforce a specified policy.
2095 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2096 final DevicePolicyData policy = getUserData(userHandle);
2097 final int count = policy.mAdminList.size();
2099 for (int i = 0; i < count; i++) {
2100 final ActiveAdmin admin = policy.mAdminList.get(i);
2101 if (admin.info.usesPolicy(reqPolicy)) {
2102 sendAdminCommandLocked(admin, action);
2109 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2110 * enforce a specified policy.
2112 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2114 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2115 for (int profileId : profileIds) {
2116 sendAdminCommandLocked(action, reqPolicy, profileId);
2121 * Sends a broadcast to each profile that share the password unlock with the given user id.
2123 private void sendAdminCommandForLockscreenPoliciesLocked(
2124 String action, int reqPolicy, int userHandle) {
2125 if (isSeparateProfileChallengeEnabled(userHandle)) {
2126 sendAdminCommandLocked(action, reqPolicy, userHandle);
2128 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2132 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2133 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2134 DevicePolicyData policy = getUserData(userHandle);
2135 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2136 policy.mRemovingAdmins.add(adminReceiver);
2137 sendAdminCommandLocked(admin,
2138 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2139 new BroadcastReceiver() {
2141 public void onReceive(Context context, Intent intent) {
2142 removeAdminArtifacts(adminReceiver, userHandle);
2143 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2150 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2151 boolean throwForMissiongPermission) {
2155 enforceFullCrossUsersPermission(userHandle);
2156 ActivityInfo ai = null;
2158 ai = mIPackageManager.getReceiverInfo(adminName,
2159 PackageManager.GET_META_DATA |
2160 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2161 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2162 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2163 } catch (RemoteException e) {
2164 // shouldn't happen.
2167 throw new IllegalArgumentException("Unknown admin: " + adminName);
2170 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2171 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2172 + permission.BIND_DEVICE_ADMIN;
2173 Slog.w(LOG_TAG, message);
2174 if (throwForMissiongPermission &&
2175 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2176 throw new IllegalArgumentException(message);
2181 return new DeviceAdminInfo(mContext, ai);
2182 } catch (XmlPullParserException | IOException e) {
2183 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2189 private JournaledFile makeJournaledFile(int userHandle) {
2190 final String base = userHandle == UserHandle.USER_SYSTEM
2191 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2192 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2193 DEVICE_POLICIES_XML).getAbsolutePath();
2195 Log.v(LOG_TAG, "Opening " + base);
2197 return new JournaledFile(new File(base), new File(base + ".tmp"));
2200 private void saveSettingsLocked(int userHandle) {
2201 DevicePolicyData policy = getUserData(userHandle);
2202 JournaledFile journal = makeJournaledFile(userHandle);
2203 FileOutputStream stream = null;
2205 stream = new FileOutputStream(journal.chooseForWrite(), false);
2206 XmlSerializer out = new FastXmlSerializer();
2207 out.setOutput(stream, StandardCharsets.UTF_8.name());
2208 out.startDocument(null, true);
2210 out.startTag(null, "policies");
2211 if (policy.mRestrictionsProvider != null) {
2212 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2213 policy.mRestrictionsProvider.flattenToString());
2215 if (policy.mUserSetupComplete) {
2216 out.attribute(null, ATTR_SETUP_COMPLETE,
2217 Boolean.toString(true));
2219 if (policy.mDeviceProvisioningConfigApplied) {
2220 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2221 Boolean.toString(true));
2223 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2224 out.attribute(null, ATTR_PROVISIONING_STATE,
2225 Integer.toString(policy.mUserProvisioningState));
2227 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2228 out.attribute(null, ATTR_PERMISSION_POLICY,
2229 Integer.toString(policy.mPermissionPolicy));
2231 if (policy.mDelegatedCertInstallerPackage != null) {
2232 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2233 policy.mDelegatedCertInstallerPackage);
2235 if (policy.mApplicationRestrictionsManagingPackage != null) {
2236 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2237 policy.mApplicationRestrictionsManagingPackage);
2240 final int N = policy.mAdminList.size();
2241 for (int i=0; i<N; i++) {
2242 ActiveAdmin ap = policy.mAdminList.get(i);
2244 out.startTag(null, "admin");
2245 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2247 out.endTag(null, "admin");
2251 if (policy.mPasswordOwner >= 0) {
2252 out.startTag(null, "password-owner");
2253 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2254 out.endTag(null, "password-owner");
2257 if (policy.mFailedPasswordAttempts != 0) {
2258 out.startTag(null, "failed-password-attempts");
2259 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2260 out.endTag(null, "failed-password-attempts");
2263 // Don't save metrics for FBE devices
2264 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
2265 && (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2266 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2267 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2268 || policy.mActivePasswordSymbols != 0
2269 || policy.mActivePasswordNonLetter != 0)) {
2270 out.startTag(null, "active-password");
2271 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2272 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2273 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2274 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2275 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2276 out.attribute(null, "numeric", Integer
2277 .toString(policy.mActivePasswordNumeric));
2278 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2279 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2280 out.endTag(null, "active-password");
2283 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2284 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2285 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2286 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2289 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2290 String component = policy.mLockTaskPackages.get(i);
2291 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2292 out.attribute(null, "name", component);
2293 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2296 if (policy.mStatusBarDisabled) {
2297 out.startTag(null, TAG_STATUS_BAR);
2298 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2299 out.endTag(null, TAG_STATUS_BAR);
2302 if (policy.doNotAskCredentialsOnBoot) {
2303 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2304 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2307 for (String id : policy.mAffiliationIds) {
2308 out.startTag(null, TAG_AFFILIATION_ID);
2309 out.attribute(null, "id", id);
2310 out.endTag(null, TAG_AFFILIATION_ID);
2313 if (policy.mAdminBroadcastPending) {
2314 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2315 out.attribute(null, ATTR_VALUE,
2316 Boolean.toString(policy.mAdminBroadcastPending));
2317 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2320 if (policy.mInitBundle != null) {
2321 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2322 policy.mInitBundle.saveToXml(out);
2323 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2326 out.endTag(null, "policies");
2330 FileUtils.sync(stream);
2333 sendChangedNotification(userHandle);
2334 } catch (XmlPullParserException | IOException e) {
2335 Slog.w(LOG_TAG, "failed writing file", e);
2337 if (stream != null) {
2340 } catch (IOException ex) {
2347 private void sendChangedNotification(int userHandle) {
2348 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2349 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2350 long ident = mInjector.binderClearCallingIdentity();
2352 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2354 mInjector.binderRestoreCallingIdentity(ident);
2358 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2359 JournaledFile journal = makeJournaledFile(userHandle);
2360 FileInputStream stream = null;
2361 File file = journal.chooseForRead();
2362 boolean needsRewrite = false;
2364 stream = new FileInputStream(file);
2365 XmlPullParser parser = Xml.newPullParser();
2366 parser.setInput(stream, StandardCharsets.UTF_8.name());
2369 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2370 && type != XmlPullParser.START_TAG) {
2372 String tag = parser.getName();
2373 if (!"policies".equals(tag)) {
2374 throw new XmlPullParserException(
2375 "Settings do not start with policies tag: found " + tag);
2378 // Extract the permission provider component name if available
2379 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2380 if (permissionProvider != null) {
2381 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2383 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2384 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2385 policy.mUserSetupComplete = true;
2387 String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2388 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2389 if (deviceProvisioningConfigApplied != null
2390 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2391 policy.mDeviceProvisioningConfigApplied = true;
2393 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2394 if (!TextUtils.isEmpty(provisioningState)) {
2395 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2397 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2398 if (!TextUtils.isEmpty(permissionPolicy)) {
2399 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2401 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2402 ATTR_DELEGATED_CERT_INSTALLER);
2403 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2404 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2406 type = parser.next();
2407 int outerDepth = parser.getDepth();
2408 policy.mLockTaskPackages.clear();
2409 policy.mAdminList.clear();
2410 policy.mAdminMap.clear();
2411 policy.mAffiliationIds.clear();
2412 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2413 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2414 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2417 tag = parser.getName();
2418 if ("admin".equals(tag)) {
2419 String name = parser.getAttributeValue(null, "name");
2421 DeviceAdminInfo dai = findAdmin(
2422 ComponentName.unflattenFromString(name), userHandle,
2423 /* throwForMissionPermission= */ false);
2425 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2427 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2428 + dai.getActivityInfo().applicationInfo.uid + " for user "
2432 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2433 ap.readFromXml(parser);
2434 policy.mAdminMap.put(ap.info.getComponent(), ap);
2436 } catch (RuntimeException e) {
2437 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2439 } else if ("failed-password-attempts".equals(tag)) {
2440 policy.mFailedPasswordAttempts = Integer.parseInt(
2441 parser.getAttributeValue(null, "value"));
2442 } else if ("password-owner".equals(tag)) {
2443 policy.mPasswordOwner = Integer.parseInt(
2444 parser.getAttributeValue(null, "value"));
2445 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2446 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2447 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2448 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2449 } else if (TAG_STATUS_BAR.equals(tag)) {
2450 policy.mStatusBarDisabled = Boolean.parseBoolean(
2451 parser.getAttributeValue(null, ATTR_DISABLED));
2452 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2453 policy.doNotAskCredentialsOnBoot = true;
2454 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2455 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2456 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2457 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2458 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2459 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2460 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2461 } else if ("active-password".equals(tag)) {
2462 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2463 // Remove this from FBE devices
2464 needsRewrite = true;
2466 policy.mActivePasswordQuality = Integer.parseInt(
2467 parser.getAttributeValue(null, "quality"));
2468 policy.mActivePasswordLength = Integer.parseInt(
2469 parser.getAttributeValue(null, "length"));
2470 policy.mActivePasswordUpperCase = Integer.parseInt(
2471 parser.getAttributeValue(null, "uppercase"));
2472 policy.mActivePasswordLowerCase = Integer.parseInt(
2473 parser.getAttributeValue(null, "lowercase"));
2474 policy.mActivePasswordLetters = Integer.parseInt(
2475 parser.getAttributeValue(null, "letters"));
2476 policy.mActivePasswordNumeric = Integer.parseInt(
2477 parser.getAttributeValue(null, "numeric"));
2478 policy.mActivePasswordSymbols = Integer.parseInt(
2479 parser.getAttributeValue(null, "symbols"));
2480 policy.mActivePasswordNonLetter = Integer.parseInt(
2481 parser.getAttributeValue(null, "nonletter"));
2484 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2485 XmlUtils.skipCurrentTag(parser);
2488 } catch (FileNotFoundException e) {
2489 // Don't be noisy, this is normal if we haven't defined any policies.
2490 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2491 | IndexOutOfBoundsException e) {
2492 Slog.w(LOG_TAG, "failed parsing " + file, e);
2495 if (stream != null) {
2498 } catch (IOException e) {
2502 // Generate a list of admins from the admin map
2503 policy.mAdminList.addAll(policy.mAdminMap.values());
2505 // Might need to upgrade the file by rewriting it
2507 saveSettingsLocked(userHandle);
2510 validatePasswordOwnerLocked(policy);
2511 updateMaximumTimeToLockLocked(userHandle);
2512 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2513 if (policy.mStatusBarDisabled) {
2514 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2518 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2519 long ident = mInjector.binderClearCallingIdentity();
2521 mInjector.getIActivityManager()
2522 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2523 } catch (RemoteException e) {
2524 // Not gonna happen.
2526 mInjector.binderRestoreCallingIdentity(ident);
2530 private void updateDeviceOwnerLocked() {
2531 long ident = mInjector.binderClearCallingIdentity();
2533 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2534 // user id and also protect all other DAs too.
2535 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2536 if (deviceOwnerComponent != null) {
2537 mInjector.getIActivityManager()
2538 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2540 } catch (RemoteException e) {
2541 // Not gonna happen.
2543 mInjector.binderRestoreCallingIdentity(ident);
2547 static void validateQualityConstant(int quality) {
2549 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2550 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2551 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2552 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2553 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2554 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2555 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2556 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2557 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2560 throw new IllegalArgumentException("Invalid quality constant: 0x"
2561 + Integer.toHexString(quality));
2564 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2565 if (policy.mPasswordOwner >= 0) {
2566 boolean haveOwner = false;
2567 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2568 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2574 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2575 + " no longer active; disabling");
2576 policy.mPasswordOwner = -1;
2582 void systemReady(int phase) {
2587 case SystemService.PHASE_LOCK_SETTINGS_READY:
2588 onLockSettingsReady();
2590 case SystemService.PHASE_BOOT_COMPLETED:
2591 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2596 private void onLockSettingsReady() {
2597 getUserData(UserHandle.USER_SYSTEM);
2601 onStartUser(UserHandle.USER_SYSTEM);
2603 // Register an observer for watching for user setup complete.
2604 new SetupContentObserver(mHandler).register();
2605 // Initialize the user setup state, to handle the upgrade case.
2606 updateUserSetupComplete();
2608 List<String> packageList;
2609 synchronized (this) {
2610 packageList = getKeepUninstalledPackagesLocked();
2612 if (packageList != null) {
2613 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2616 synchronized (this) {
2617 // push the force-ephemeral-users policy to the user manager.
2618 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2619 if (deviceOwner != null) {
2620 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2625 private void ensureDeviceOwnerUserStarted() {
2627 synchronized (this) {
2628 if (!mOwners.hasDeviceOwner()) {
2631 userId = mOwners.getDeviceOwnerUserId();
2634 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2636 if (userId != UserHandle.USER_SYSTEM) {
2638 mInjector.getIActivityManager().startUserInBackground(userId);
2640 // STOPSHIP Prevent the DO user from being killed.
2642 } catch (RemoteException e) {
2643 Slog.w(LOG_TAG, "Exception starting user", e);
2648 private void onStartUser(int userId) {
2649 updateScreenCaptureDisabledInWindowManager(userId,
2650 getScreenCaptureDisabled(null, userId));
2651 pushUserRestrictions(userId);
2654 private void cleanUpOldUsers() {
2655 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2657 Set<Integer> usersWithProfileOwners;
2658 Set<Integer> usersWithData;
2659 synchronized(this) {
2660 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2661 usersWithData = new ArraySet<>();
2662 for (int i = 0; i < mUserData.size(); i++) {
2663 usersWithData.add(mUserData.keyAt(i));
2666 List<UserInfo> allUsers = mUserManager.getUsers();
2668 Set<Integer> deletedUsers = new ArraySet<>();
2669 deletedUsers.addAll(usersWithProfileOwners);
2670 deletedUsers.addAll(usersWithData);
2671 for (UserInfo userInfo : allUsers) {
2672 deletedUsers.remove(userInfo.id);
2674 for (Integer userId : deletedUsers) {
2675 removeUserData(userId);
2679 private void handlePasswordExpirationNotification(int userHandle) {
2680 synchronized (this) {
2681 final long now = System.currentTimeMillis();
2683 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2684 userHandle, /* parent */ false);
2685 final int N = admins.size();
2686 for (int i = 0; i < N; i++) {
2687 ActiveAdmin admin = admins.get(i);
2688 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2689 && admin.passwordExpirationTimeout > 0L
2690 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2691 && admin.passwordExpirationDate > 0L) {
2692 sendAdminCommandLocked(admin,
2693 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2696 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2700 private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2702 protected Void doInBackground(Integer... params) {
2703 int userHandle = params[0];
2705 if (userHandle == UserHandle.USER_ALL) {
2706 for (UserInfo userInfo : mUserManager.getUsers(true)) {
2707 manageNotification(userInfo.getUserHandle());
2710 manageNotification(UserHandle.of(userHandle));
2715 private void manageNotification(UserHandle userHandle) {
2716 if (!mUserManager.isUserUnlocked(userHandle)) {
2720 // Call out to KeyChain to check for CAs which are waiting for approval.
2721 final List<String> pendingCertificates;
2723 pendingCertificates = getInstalledCaCertificates(userHandle);
2724 } catch (RemoteException | RuntimeException e) {
2725 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2729 synchronized (DevicePolicyManagerService.this) {
2730 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2732 // Remove deleted certificates. Flush xml if necessary.
2733 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2734 saveSettingsLocked(userHandle.getIdentifier());
2736 // Trim to approved certificates.
2737 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2740 if (pendingCertificates.isEmpty()) {
2741 mInjector.getNotificationManager().cancelAsUser(
2742 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2746 // Build and show a warning notification
2749 int parentUserId = userHandle.getIdentifier();
2750 if (getProfileOwner(userHandle.getIdentifier()) != null) {
2751 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2752 getProfileOwnerName(userHandle.getIdentifier()));
2753 smallIconId = R.drawable.stat_sys_certificate_info;
2754 parentUserId = getProfileParentId(userHandle.getIdentifier());
2755 } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
2756 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2757 getDeviceOwnerName());
2758 smallIconId = R.drawable.stat_sys_certificate_info;
2760 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2761 smallIconId = android.R.drawable.stat_sys_warning;
2764 final int numberOfCertificates = pendingCertificates.size();
2765 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2766 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2767 dialogIntent.setPackage("com.android.settings");
2768 dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
2769 dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
2770 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2771 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
2772 new UserHandle(parentUserId));
2774 final Context userContext;
2776 final String packageName = mContext.getPackageName();
2777 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
2778 } catch (PackageManager.NameNotFoundException e) {
2779 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2782 final Notification noti = new Notification.Builder(userContext)
2783 .setSmallIcon(smallIconId)
2784 .setContentTitle(mContext.getResources().getQuantityText(
2785 R.plurals.ssl_ca_cert_warning, numberOfCertificates))
2786 .setContentText(contentText)
2787 .setContentIntent(notifyIntent)
2788 .setPriority(Notification.PRIORITY_HIGH)
2790 .setColor(mContext.getColor(
2791 com.android.internal.R.color.system_notification_accent_color))
2794 mInjector.getNotificationManager().notifyAsUser(
2795 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2798 private List<String> getInstalledCaCertificates(UserHandle userHandle)
2799 throws RemoteException, RuntimeException {
2800 KeyChainConnection conn = null;
2802 conn = KeyChain.bindAsUser(mContext, userHandle);
2803 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
2804 List<String> result = new ArrayList<>(aliases.size());
2805 for (int i = 0; i < aliases.size(); i++) {
2806 result.add(aliases.get(i).string);
2809 } catch (InterruptedException e) {
2810 Thread.currentThread().interrupt();
2812 } catch (AssertionError e) {
2813 throw new RuntimeException(e);
2823 * @param adminReceiver The admin to add
2824 * @param refreshing true = update an active admin, no error
2827 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2831 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2834 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2835 Bundle onEnableData) {
2836 mContext.enforceCallingOrSelfPermission(
2837 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2838 enforceFullCrossUsersPermission(userHandle);
2840 DevicePolicyData policy = getUserData(userHandle);
2841 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2842 /* throwForMissionPermission= */ true);
2844 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2846 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2847 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2850 synchronized (this) {
2851 long ident = mInjector.binderClearCallingIdentity();
2853 final ActiveAdmin existingAdmin
2854 = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2855 if (!refreshing && existingAdmin != null) {
2856 throw new IllegalArgumentException("Admin is already added");
2858 if (policy.mRemovingAdmins.contains(adminReceiver)) {
2859 throw new IllegalArgumentException(
2860 "Trying to set an admin which is being removed");
2862 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2863 newAdmin.testOnlyAdmin =
2864 (existingAdmin != null) ? existingAdmin.testOnlyAdmin
2865 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
2866 policy.mAdminMap.put(adminReceiver, newAdmin);
2867 int replaceIndex = -1;
2868 final int N = policy.mAdminList.size();
2869 for (int i=0; i < N; i++) {
2870 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2871 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2876 if (replaceIndex == -1) {
2877 policy.mAdminList.add(newAdmin);
2878 enableIfNecessary(info.getPackageName(), userHandle);
2880 policy.mAdminList.set(replaceIndex, newAdmin);
2882 saveSettingsLocked(userHandle);
2883 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2884 onEnableData, null);
2886 mInjector.binderRestoreCallingIdentity(ident);
2892 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2896 enforceFullCrossUsersPermission(userHandle);
2897 synchronized (this) {
2898 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2903 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2907 enforceFullCrossUsersPermission(userHandle);
2908 synchronized (this) {
2909 DevicePolicyData policyData = getUserData(userHandle);
2910 return policyData.mRemovingAdmins.contains(adminReceiver);
2915 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2919 enforceFullCrossUsersPermission(userHandle);
2920 synchronized (this) {
2921 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2922 if (administrator == null) {
2923 throw new SecurityException("No active admin " + adminReceiver);
2925 return administrator.info.usesPolicy(policyId);
2930 @SuppressWarnings("unchecked")
2931 public List<ComponentName> getActiveAdmins(int userHandle) {
2933 return Collections.EMPTY_LIST;
2936 enforceFullCrossUsersPermission(userHandle);
2937 synchronized (this) {
2938 DevicePolicyData policy = getUserData(userHandle);
2939 final int N = policy.mAdminList.size();
2943 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2944 for (int i=0; i<N; i++) {
2945 res.add(policy.mAdminList.get(i).info.getComponent());
2952 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2956 enforceFullCrossUsersPermission(userHandle);
2957 synchronized (this) {
2958 DevicePolicyData policy = getUserData(userHandle);
2959 final int N = policy.mAdminList.size();
2960 for (int i=0; i<N; i++) {
2961 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2969 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
2973 Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
2974 enforceShell("forceRemoveActiveAdmin");
2975 long ident = mInjector.binderClearCallingIdentity();
2977 synchronized (this) {
2978 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
2979 throw new SecurityException("Attempt to remove non-test admin "
2980 + adminReceiver + " " + userHandle);
2983 // If admin is a device or profile owner tidy that up first.
2984 if (isDeviceOwner(adminReceiver, userHandle)) {
2985 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
2987 if (isProfileOwner(adminReceiver, userHandle)) {
2988 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
2989 userHandle, /* parent */ false);
2990 clearProfileOwnerLocked(admin, userHandle);
2993 // Remove the admin skipping sending the broadcast.
2994 removeAdminArtifacts(adminReceiver, userHandle);
2995 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
2997 mInjector.binderRestoreCallingIdentity(ident);
3002 * Return if a given package has testOnly="true", in which case we'll relax certain rules
3005 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked}
3006 * to check wehter an active admin is test-only or not.
3008 * The system allows this flag to be changed when an app is updated, which is not good
3009 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3010 * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3012 private boolean isPackageTestOnly(String packageName, int userHandle) {
3013 final ApplicationInfo ai;
3015 ai = mIPackageManager.getApplicationInfo(packageName,
3016 (PackageManager.MATCH_DIRECT_BOOT_AWARE
3017 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3018 } catch (RemoteException e) {
3019 throw new IllegalStateException(e);
3022 throw new IllegalStateException("Couldn't find package: "
3023 + packageName + " on user " + userHandle);
3025 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3029 * See {@link #isPackageTestOnly}.
3031 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3032 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3033 return (admin != null) && admin.testOnlyAdmin;
3036 private void enforceShell(String method) {
3037 final int callingUid = Binder.getCallingUid();
3038 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3039 throw new SecurityException("Non-shell user attempted to call " + method);
3044 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3048 enforceFullCrossUsersPermission(userHandle);
3049 enforceUserUnlocked(userHandle);
3050 synchronized (this) {
3051 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3052 if (admin == null) {
3055 // Active device/profile owners must remain active admins.
3056 if (isDeviceOwner(adminReceiver, userHandle)
3057 || isProfileOwner(adminReceiver, userHandle)) {
3058 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3062 if (admin.getUid() != mInjector.binderGetCallingUid()) {
3063 mContext.enforceCallingOrSelfPermission(
3064 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3066 long ident = mInjector.binderClearCallingIdentity();
3068 removeActiveAdminLocked(adminReceiver, userHandle);
3070 mInjector.binderRestoreCallingIdentity(ident);
3076 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3077 ComponentName profileOwner = getProfileOwner(userHandle);
3078 // Profile challenge is supported on N or newer release.
3079 return profileOwner != null &&
3080 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3084 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3088 Preconditions.checkNotNull(who, "ComponentName is null");
3089 validateQualityConstant(quality);
3091 synchronized (this) {
3092 ActiveAdmin ap = getActiveAdminForCallerLocked(
3093 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3094 if (ap.passwordQuality != quality) {
3095 ap.passwordQuality = quality;
3096 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3102 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3104 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3106 enforceFullCrossUsersPermission(userHandle);
3107 synchronized (this) {
3108 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3111 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3112 return admin != null ? admin.passwordQuality : mode;
3115 // Return the strictest policy across all participating admins.
3116 List<ActiveAdmin> admins =
3117 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3118 final int N = admins.size();
3119 for (int i = 0; i < N; i++) {
3120 ActiveAdmin admin = admins.get(i);
3121 if (mode < admin.passwordQuality) {
3122 mode = admin.passwordQuality;
3129 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3130 int userHandle, boolean parent) {
3131 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3132 // If this user has a separate challenge, only return its restrictions.
3133 return getUserDataUnchecked(userHandle).mAdminList;
3135 // Return all admins for this user and the profiles that are visible from this
3136 // user that do not use a separate work challenge.
3137 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3138 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3139 DevicePolicyData policy = getUserData(userInfo.id);
3140 if (!userInfo.isManagedProfile()) {
3141 admins.addAll(policy.mAdminList);
3143 // For managed profiles, we always include the policies set on the parent
3144 // profile. Additionally, we include the ones set on the managed profile
3145 // if no separate challenge is in place.
3146 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3147 final int N = policy.mAdminList.size();
3148 for (int i = 0; i < N; i++) {
3149 ActiveAdmin admin = policy.mAdminList.get(i);
3150 if (admin.hasParentActiveAdmin()) {
3151 admins.add(admin.getParentActiveAdmin());
3153 if (!hasSeparateChallenge) {
3163 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3164 long ident = mInjector.binderClearCallingIdentity();
3166 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3168 mInjector.binderRestoreCallingIdentity(ident);
3173 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3177 Preconditions.checkNotNull(who, "ComponentName is null");
3178 synchronized (this) {
3179 ActiveAdmin ap = getActiveAdminForCallerLocked(
3180 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3181 if (ap.minimumPasswordLength != length) {
3182 ap.minimumPasswordLength = length;
3183 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3189 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3193 enforceFullCrossUsersPermission(userHandle);
3194 synchronized (this) {
3198 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3199 return admin != null ? admin.minimumPasswordLength : length;
3202 // Return the strictest policy across all participating admins.
3203 List<ActiveAdmin> admins =
3204 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3205 final int N = admins.size();
3206 for (int i = 0; i < N; i++) {
3207 ActiveAdmin admin = admins.get(i);
3208 if (length < admin.minimumPasswordLength) {
3209 length = admin.minimumPasswordLength;
3217 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3221 Preconditions.checkNotNull(who, "ComponentName is null");
3222 synchronized (this) {
3223 ActiveAdmin ap = getActiveAdminForCallerLocked(
3224 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3225 if (ap.passwordHistoryLength != length) {
3226 ap.passwordHistoryLength = length;
3227 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3233 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3237 enforceFullCrossUsersPermission(userHandle);
3238 synchronized (this) {
3242 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3243 return admin != null ? admin.passwordHistoryLength : length;
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 (length < admin.passwordHistoryLength) {
3253 length = admin.passwordHistoryLength;
3262 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3266 Preconditions.checkNotNull(who, "ComponentName is null");
3267 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3268 final int userHandle = mInjector.userHandleGetCallingUserId();
3269 synchronized (this) {
3270 ActiveAdmin ap = getActiveAdminForCallerLocked(
3271 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3272 // Calling this API automatically bumps the expiration date
3273 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3274 ap.passwordExpirationDate = expiration;
3275 ap.passwordExpirationTimeout = timeout;
3277 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3278 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3279 .format(new Date(expiration)));
3281 saveSettingsLocked(userHandle);
3283 // in case this is the first one, set the alarm on the appropriate user.
3284 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3289 * Return a single admin's expiration cycle time, or the min of all cycle times.
3290 * Returns 0 if not configured.
3293 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3297 enforceFullCrossUsersPermission(userHandle);
3298 synchronized (this) {
3302 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3303 return admin != null ? admin.passwordExpirationTimeout : timeout;
3306 // Return the strictest policy across all participating admins.
3307 List<ActiveAdmin> admins =
3308 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3309 final int N = admins.size();
3310 for (int i = 0; i < N; i++) {
3311 ActiveAdmin admin = admins.get(i);
3312 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3313 && timeout > admin.passwordExpirationTimeout)) {
3314 timeout = admin.passwordExpirationTimeout;
3322 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3323 final int userId = UserHandle.getCallingUserId();
3324 List<String> changedProviders = null;
3326 synchronized (this) {
3327 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3328 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3329 if (activeAdmin.crossProfileWidgetProviders == null) {
3330 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3332 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3333 if (!providers.contains(packageName)) {
3334 providers.add(packageName);
3335 changedProviders = new ArrayList<>(providers);
3336 saveSettingsLocked(userId);
3340 if (changedProviders != null) {
3341 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3349 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3350 final int userId = UserHandle.getCallingUserId();
3351 List<String> changedProviders = null;
3353 synchronized (this) {
3354 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3355 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3356 if (activeAdmin.crossProfileWidgetProviders == null) {
3359 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3360 if (providers.remove(packageName)) {
3361 changedProviders = new ArrayList<>(providers);
3362 saveSettingsLocked(userId);
3366 if (changedProviders != null) {
3367 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3375 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3376 synchronized (this) {
3377 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3378 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3379 if (activeAdmin.crossProfileWidgetProviders == null
3380 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3383 if (mInjector.binderIsCallingUidMyUid()) {
3384 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3386 return activeAdmin.crossProfileWidgetProviders;
3392 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3393 * Returns 0 if not configured.
3395 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3399 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3400 return admin != null ? admin.passwordExpirationDate : timeout;
3403 // Return the strictest policy across all participating admins.
3404 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3405 final int N = admins.size();
3406 for (int i = 0; i < N; i++) {
3407 ActiveAdmin admin = admins.get(i);
3408 if (timeout == 0L || (admin.passwordExpirationDate != 0
3409 && timeout > admin.passwordExpirationDate)) {
3410 timeout = admin.passwordExpirationDate;
3417 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3421 enforceFullCrossUsersPermission(userHandle);
3422 synchronized (this) {
3423 return getPasswordExpirationLocked(who, userHandle, parent);
3428 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3432 Preconditions.checkNotNull(who, "ComponentName is null");
3433 synchronized (this) {
3434 ActiveAdmin ap = getActiveAdminForCallerLocked(
3435 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3436 if (ap.minimumPasswordUpperCase != length) {
3437 ap.minimumPasswordUpperCase = length;
3438 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3444 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3448 enforceFullCrossUsersPermission(userHandle);
3449 synchronized (this) {
3453 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3454 return admin != null ? admin.minimumPasswordUpperCase : length;
3457 // Return the strictest policy across all participating admins.
3458 List<ActiveAdmin> admins =
3459 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3460 final int N = admins.size();
3461 for (int i = 0; i < N; i++) {
3462 ActiveAdmin admin = admins.get(i);
3463 if (length < admin.minimumPasswordUpperCase) {
3464 length = admin.minimumPasswordUpperCase;
3472 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3473 Preconditions.checkNotNull(who, "ComponentName is null");
3474 synchronized (this) {
3475 ActiveAdmin ap = getActiveAdminForCallerLocked(
3476 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3477 if (ap.minimumPasswordLowerCase != length) {
3478 ap.minimumPasswordLowerCase = length;
3479 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3485 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3489 enforceFullCrossUsersPermission(userHandle);
3490 synchronized (this) {
3494 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3495 return admin != null ? admin.minimumPasswordLowerCase : length;
3498 // Return the strictest policy across all participating admins.
3499 List<ActiveAdmin> admins =
3500 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3501 final int N = admins.size();
3502 for (int i = 0; i < N; i++) {
3503 ActiveAdmin admin = admins.get(i);
3504 if (length < admin.minimumPasswordLowerCase) {
3505 length = admin.minimumPasswordLowerCase;
3513 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3517 Preconditions.checkNotNull(who, "ComponentName is null");
3518 synchronized (this) {
3519 ActiveAdmin ap = getActiveAdminForCallerLocked(
3520 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3521 if (ap.minimumPasswordLetters != length) {
3522 ap.minimumPasswordLetters = length;
3523 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3529 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3533 enforceFullCrossUsersPermission(userHandle);
3534 synchronized (this) {
3538 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3539 return admin != null ? admin.minimumPasswordLetters : length;
3542 // Return the strictest policy across all participating admins.
3543 List<ActiveAdmin> admins =
3544 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3545 final int N = admins.size();
3546 for (int i = 0; i < N; i++) {
3547 ActiveAdmin admin = admins.get(i);
3548 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3551 if (length < admin.minimumPasswordLetters) {
3552 length = admin.minimumPasswordLetters;
3560 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3564 Preconditions.checkNotNull(who, "ComponentName is null");
3565 synchronized (this) {
3566 ActiveAdmin ap = getActiveAdminForCallerLocked(
3567 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3568 if (ap.minimumPasswordNumeric != length) {
3569 ap.minimumPasswordNumeric = length;
3570 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3576 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3580 enforceFullCrossUsersPermission(userHandle);
3581 synchronized (this) {
3585 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3586 return admin != null ? admin.minimumPasswordNumeric : length;
3589 // Return the strictest policy across all participating admins.
3590 List<ActiveAdmin> admins =
3591 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3592 final int N = admins.size();
3593 for (int i = 0; i < N; i++) {
3594 ActiveAdmin admin = admins.get(i);
3595 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3598 if (length < admin.minimumPasswordNumeric) {
3599 length = admin.minimumPasswordNumeric;
3607 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3611 Preconditions.checkNotNull(who, "ComponentName is null");
3612 synchronized (this) {
3613 ActiveAdmin ap = getActiveAdminForCallerLocked(
3614 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3615 if (ap.minimumPasswordSymbols != length) {
3616 ap.minimumPasswordSymbols = length;
3617 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3623 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3627 enforceFullCrossUsersPermission(userHandle);
3628 synchronized (this) {
3632 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3633 return admin != null ? admin.minimumPasswordSymbols : length;
3636 // Return the strictest policy across all participating admins.
3637 List<ActiveAdmin> admins =
3638 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3639 final int N = admins.size();
3640 for (int i = 0; i < N; i++) {
3641 ActiveAdmin admin = admins.get(i);
3642 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3645 if (length < admin.minimumPasswordSymbols) {
3646 length = admin.minimumPasswordSymbols;
3654 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3658 Preconditions.checkNotNull(who, "ComponentName is null");
3659 synchronized (this) {
3660 ActiveAdmin ap = getActiveAdminForCallerLocked(
3661 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3662 if (ap.minimumPasswordNonLetter != length) {
3663 ap.minimumPasswordNonLetter = length;
3664 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3670 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3674 enforceFullCrossUsersPermission(userHandle);
3675 synchronized (this) {
3679 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3680 return admin != null ? admin.minimumPasswordNonLetter : length;
3683 // Return the strictest policy across all participating admins.
3684 List<ActiveAdmin> admins =
3685 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3686 final int N = admins.size();
3687 for (int i = 0; i < N; i++) {
3688 ActiveAdmin admin = admins.get(i);
3689 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3692 if (length < admin.minimumPasswordNonLetter) {
3693 length = admin.minimumPasswordNonLetter;
3701 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3705 enforceFullCrossUsersPermission(userHandle);
3707 synchronized (this) {
3708 // This API can only be called by an active device admin,
3709 // so try to retrieve it to check that the caller is one.
3710 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3711 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3712 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3717 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3721 enforceFullCrossUsersPermission(userHandle);
3722 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3724 synchronized (this) {
3725 int targetUser = getProfileParentId(userHandle);
3726 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3727 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3731 private boolean isActivePasswordSufficientForUserLocked(
3732 DevicePolicyData policy, int userHandle, boolean parent) {
3733 enforceUserUnlocked(userHandle, parent);
3735 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
3736 if (policy.mActivePasswordQuality < requiredPasswordQuality) {
3739 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
3740 && policy.mActivePasswordLength < getPasswordMinimumLength(
3741 null, userHandle, parent)) {
3744 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3747 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3748 null, userHandle, parent)
3749 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3750 null, userHandle, parent)
3751 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3752 null, userHandle, parent)
3753 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3754 null, userHandle, parent)
3755 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3756 null, userHandle, parent)
3757 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3758 null, userHandle, parent);
3762 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3763 enforceFullCrossUsersPermission(userHandle);
3764 synchronized (this) {
3765 if (!isCallerWithSystemUid()) {
3766 // This API can only be called by an active device admin,
3767 // so try to retrieve it to check that the caller is one.
3768 getActiveAdminForCallerLocked(
3769 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3772 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3774 return policy.mFailedPasswordAttempts;
3779 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3783 Preconditions.checkNotNull(who, "ComponentName is null");
3784 synchronized (this) {
3785 // This API can only be called by an active device admin,
3786 // so try to retrieve it to check that the caller is one.
3787 getActiveAdminForCallerLocked(
3788 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3789 ActiveAdmin ap = getActiveAdminForCallerLocked(
3790 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3791 if (ap.maximumFailedPasswordsForWipe != num) {
3792 ap.maximumFailedPasswordsForWipe = num;
3793 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3799 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3803 enforceFullCrossUsersPermission(userHandle);
3804 synchronized (this) {
3805 ActiveAdmin admin = (who != null)
3806 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3807 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3808 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3813 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3815 return UserHandle.USER_NULL;
3817 enforceFullCrossUsersPermission(userHandle);
3818 synchronized (this) {
3819 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3820 userHandle, parent);
3821 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3826 * Returns the admin with the strictest policy on maximum failed passwords for:
3828 * <li>this user if it has a separate profile challenge, or
3829 * <li>this user and all profiles that don't have their own challenge otherwise.
3831 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3832 * the primary profile.
3833 * Returns {@code null} if no participating admin has that policy set.
3835 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3836 int userHandle, boolean parent) {
3838 ActiveAdmin strictestAdmin = null;
3840 // Return the strictest policy across all participating admins.
3841 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3842 final int N = admins.size();
3843 for (int i = 0; i < N; i++) {
3844 ActiveAdmin admin = admins.get(i);
3845 if (admin.maximumFailedPasswordsForWipe ==
3846 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3847 continue; // No max number of failed passwords policy set for this profile.
3850 // We always favor the primary profile if several profiles have the same value set.
3851 int userId = admin.getUserHandle().getIdentifier();
3853 count > admin.maximumFailedPasswordsForWipe ||
3854 (count == admin.maximumFailedPasswordsForWipe &&
3855 getUserInfo(userId).isPrimary())) {
3856 count = admin.maximumFailedPasswordsForWipe;
3857 strictestAdmin = admin;
3860 return strictestAdmin;
3863 private UserInfo getUserInfo(@UserIdInt int userId) {
3864 final long token = mInjector.binderClearCallingIdentity();
3866 return mUserManager.getUserInfo(userId);
3868 mInjector.binderRestoreCallingIdentity(token);
3873 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3877 final int callingUid = mInjector.binderGetCallingUid();
3878 final int userHandle = mInjector.userHandleGetCallingUserId();
3880 String password = passwordOrNull != null ? passwordOrNull : "";
3882 // Password resetting to empty/null is not allowed for managed profiles.
3883 if (TextUtils.isEmpty(password)) {
3884 enforceNotManagedProfile(userHandle, "clear the active password");
3888 synchronized (this) {
3889 // If caller has PO (or DO) it can change the password, so see if that's the case first.
3890 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3891 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3893 if (admin != null) {
3894 preN = getTargetSdk(admin.info.getPackageName(),
3895 userHandle) <= android.os.Build.VERSION_CODES.M;
3897 // Otherwise, make sure the caller has any active admin with the right policy.
3898 admin = getActiveAdminForCallerLocked(null,
3899 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3900 preN = getTargetSdk(admin.info.getPackageName(),
3901 userHandle) <= android.os.Build.VERSION_CODES.M;
3903 // As of N, password resetting to empty/null is not allowed anymore.
3904 // TODO Should we allow DO/PO to set an empty password?
3905 if (TextUtils.isEmpty(password)) {
3907 throw new SecurityException("Cannot call with null password");
3909 Slog.e(LOG_TAG, "Cannot call with null password");
3913 // As of N, password cannot be changed by the admin if it is already set.
3914 if (isLockScreenSecureUnchecked(userHandle)) {
3916 throw new SecurityException("Admin cannot change current password");
3918 Slog.e(LOG_TAG, "Admin cannot change current password");
3923 // Do not allow to reset password when current user has a managed profile
3924 if (!isManagedProfile(userHandle)) {
3925 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3926 if (userInfo.isManagedProfile()) {
3928 throw new IllegalStateException(
3929 "Cannot reset password on user has managed profile");
3931 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
3937 // Do not allow to reset password when user is locked
3938 if (!mUserManager.isUserUnlocked(userHandle)) {
3940 throw new IllegalStateException("Cannot reset password when user is locked");
3942 Slog.e(LOG_TAG, "Cannot reset password when user is locked");
3947 quality = getPasswordQuality(null, userHandle, /* parent */ false);
3948 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
3949 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3951 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
3952 int realQuality = LockPatternUtils.computePasswordQuality(password);
3953 if (realQuality < quality
3954 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3955 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
3956 + Integer.toHexString(realQuality)
3957 + " does not meet required quality 0x"
3958 + Integer.toHexString(quality));
3961 quality = Math.max(realQuality, quality);
3963 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
3964 if (password.length() < length) {
3965 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
3966 + " does not meet required length " + length);
3969 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3976 for (int i = 0; i < password.length(); i++) {
3977 char c = password.charAt(i);
3978 if (c >= 'A' && c <= 'Z') {
3981 } else if (c >= 'a' && c <= 'z') {
3984 } else if (c >= '0' && c <= '9') {
3992 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
3993 if(letters < neededLetters) {
3994 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
3995 + " does not meet required number of letters " + neededLetters);
3998 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
3999 if (numbers < neededNumbers) {
4000 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
4001 + " does not meet required number of numerical digits "
4005 int neededLowerCase = getPasswordMinimumLowerCase(
4006 null, userHandle, /* parent */ false);
4007 if (lowercase < neededLowerCase) {
4008 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
4009 + " does not meet required number of lowercase letters "
4013 int neededUpperCase = getPasswordMinimumUpperCase(
4014 null, userHandle, /* parent */ false);
4015 if (uppercase < neededUpperCase) {
4016 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
4017 + " does not meet required number of uppercase letters "
4021 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4022 if (symbols < neededSymbols) {
4023 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
4024 + " does not meet required number of special symbols " + neededSymbols);
4027 int neededNonLetter = getPasswordMinimumNonLetter(
4028 null, userHandle, /* parent */ false);
4029 if (nonletter < neededNonLetter) {
4030 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
4031 + " does not meet required number of non-letter characters "
4038 DevicePolicyData policy = getUserData(userHandle);
4039 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4040 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4044 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4045 boolean doNotAskCredentialsOnBoot =
4046 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4047 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4048 setDoNotAskCredentialsOnBoot();
4051 // Don't do this with the lock held, because it is going to call
4052 // back in to the service.
4053 final long ident = mInjector.binderClearCallingIdentity();
4055 if (!TextUtils.isEmpty(password)) {
4056 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4058 mLockPatternUtils.clearLock(userHandle);
4060 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4062 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4063 UserHandle.USER_ALL);
4065 synchronized (this) {
4066 int newOwner = requireEntry ? callingUid : -1;
4067 if (policy.mPasswordOwner != newOwner) {
4068 policy.mPasswordOwner = newOwner;
4069 saveSettingsLocked(userHandle);
4073 mInjector.binderRestoreCallingIdentity(ident);
4079 private boolean isLockScreenSecureUnchecked(int userId) {
4080 long ident = mInjector.binderClearCallingIdentity();
4082 return mLockPatternUtils.isSecure(userId);
4084 mInjector.binderRestoreCallingIdentity(ident);
4088 private void setDoNotAskCredentialsOnBoot() {
4089 synchronized (this) {
4090 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4091 if (!policyData.doNotAskCredentialsOnBoot) {
4092 policyData.doNotAskCredentialsOnBoot = true;
4093 saveSettingsLocked(UserHandle.USER_SYSTEM);
4099 public boolean getDoNotAskCredentialsOnBoot() {
4100 mContext.enforceCallingOrSelfPermission(
4101 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4102 synchronized (this) {
4103 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4104 return policyData.doNotAskCredentialsOnBoot;
4109 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4113 Preconditions.checkNotNull(who, "ComponentName is null");
4114 final int userHandle = mInjector.userHandleGetCallingUserId();
4115 synchronized (this) {
4116 ActiveAdmin ap = getActiveAdminForCallerLocked(
4117 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4118 if (ap.maximumTimeToUnlock != timeMs) {
4119 ap.maximumTimeToUnlock = timeMs;
4120 saveSettingsLocked(userHandle);
4121 updateMaximumTimeToLockLocked(userHandle);
4126 void updateMaximumTimeToLockLocked(int userHandle) {
4127 // Calculate the min timeout for all profiles - including the ones with a separate
4128 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4129 // challenge only and keep the screen on. However there is no easy way of doing that at the
4130 // moment so we set the screen off timeout regardless of whether it affects the parent user
4131 // or the profile challenge only.
4132 long timeMs = Long.MAX_VALUE;
4133 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4134 for (int profileId : profileIds) {
4135 DevicePolicyData policy = getUserDataUnchecked(profileId);
4136 final int N = policy.mAdminList.size();
4137 for (int i = 0; i < N; i++) {
4138 ActiveAdmin admin = policy.mAdminList.get(i);
4139 if (admin.maximumTimeToUnlock > 0
4140 && timeMs > admin.maximumTimeToUnlock) {
4141 timeMs = admin.maximumTimeToUnlock;
4143 // If userInfo.id is a managed profile, we also need to look at
4144 // the policies set on the parent.
4145 if (admin.hasParentActiveAdmin()) {
4146 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4147 if (parentAdmin.maximumTimeToUnlock > 0
4148 && timeMs > parentAdmin.maximumTimeToUnlock) {
4149 timeMs = parentAdmin.maximumTimeToUnlock;
4155 // We only store the last maximum time to lock on the parent profile. So if calling from a
4156 // managed profile, retrieve the policy for the parent.
4157 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4158 if (policy.mLastMaximumTimeToLock == timeMs) {
4161 policy.mLastMaximumTimeToLock = timeMs;
4163 final long ident = mInjector.binderClearCallingIdentity();
4165 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4166 // Make sure KEEP_SCREEN_ON is disabled, since that
4167 // would allow bypassing of the maximum time to lock.
4168 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4171 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4172 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4174 mInjector.binderRestoreCallingIdentity(ident);
4179 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4183 enforceFullCrossUsersPermission(userHandle);
4184 synchronized (this) {
4186 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4187 return admin != null ? admin.maximumTimeToUnlock : 0;
4189 // Return the strictest policy across all participating admins.
4190 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4191 userHandle, parent);
4192 return getMaximumTimeToLockPolicyFromAdmins(admins);
4197 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4201 enforceFullCrossUsersPermission(userHandle);
4202 synchronized (this) {
4203 // All admins for this user.
4204 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4205 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4206 DevicePolicyData policy = getUserData(userInfo.id);
4207 admins.addAll(policy.mAdminList);
4208 // If it is a managed profile, it may have parent active admins
4209 if (userInfo.isManagedProfile()) {
4210 for (ActiveAdmin admin : policy.mAdminList) {
4211 if (admin.hasParentActiveAdmin()) {
4212 admins.add(admin.getParentActiveAdmin());
4217 return getMaximumTimeToLockPolicyFromAdmins(admins);
4221 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4223 final int N = admins.size();
4224 for (int i = 0; i < N; i++) {
4225 ActiveAdmin admin = admins.get(i);
4227 time = admin.maximumTimeToUnlock;
4228 } else if (admin.maximumTimeToUnlock != 0
4229 && time > admin.maximumTimeToUnlock) {
4230 time = admin.maximumTimeToUnlock;
4237 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
4242 Preconditions.checkNotNull(who, "ComponentName is null");
4243 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
4244 // timeoutMs with value 0 means that the admin doesn't participate
4245 // timeoutMs is clamped to the interval in case the internal constants change in the future
4246 if (timeoutMs != 0 && timeoutMs < MINIMUM_STRONG_AUTH_TIMEOUT_MS) {
4247 timeoutMs = MINIMUM_STRONG_AUTH_TIMEOUT_MS;
4249 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
4250 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4253 final int userHandle = mInjector.userHandleGetCallingUserId();
4254 synchronized (this) {
4255 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4256 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4257 if (ap.strongAuthUnlockTimeout != timeoutMs) {
4258 ap.strongAuthUnlockTimeout = timeoutMs;
4259 saveSettingsLocked(userHandle);
4265 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
4266 * admins if who is null.
4267 * Returns 0 if not configured for the provided admin.
4270 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
4272 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4274 enforceFullCrossUsersPermission(userId);
4275 synchronized (this) {
4277 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
4278 return admin != null ? admin.strongAuthUnlockTimeout : 0;
4281 // Return the strictest policy across all participating admins.
4282 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
4284 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4285 for (int i = 0; i < admins.size(); i++) {
4286 final long timeout = admins.get(i).strongAuthUnlockTimeout;
4287 if (timeout != 0) { // take only participating admins into account
4288 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
4291 return Math.max(strongAuthUnlockTimeout, MINIMUM_STRONG_AUTH_TIMEOUT_MS);
4296 public void lockNow(boolean parent) {
4300 synchronized (this) {
4301 // This API can only be called by an active device admin,
4302 // so try to retrieve it to check that the caller is one.
4303 getActiveAdminForCallerLocked(
4304 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4306 int userToLock = mInjector.userHandleGetCallingUserId();
4308 // Unless this is a managed profile with work challenge enabled, lock all users.
4309 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4310 userToLock = UserHandle.USER_ALL;
4312 final long ident = mInjector.binderClearCallingIdentity();
4314 mLockPatternUtils.requireStrongAuth(
4315 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4316 if (userToLock == UserHandle.USER_ALL) {
4317 // Power off the display
4318 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4319 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4320 mInjector.getIWindowManager().lockNow(null);
4322 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4324 } catch (RemoteException e) {
4326 mInjector.binderRestoreCallingIdentity(ident);
4332 public void enforceCanManageCaCerts(ComponentName who) {
4334 if (!isCallerDelegatedCertInstaller()) {
4335 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4338 synchronized (this) {
4339 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4344 private void enforceCanManageInstalledKeys(ComponentName who) {
4346 if (!isCallerDelegatedCertInstaller()) {
4347 throw new SecurityException("who == null, but caller is not cert installer");
4350 synchronized (this) {
4351 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4356 private boolean isCallerDelegatedCertInstaller() {
4357 final int callingUid = mInjector.binderGetCallingUid();
4358 final int userHandle = UserHandle.getUserId(callingUid);
4359 synchronized (this) {
4360 final DevicePolicyData policy = getUserData(userHandle);
4361 if (policy.mDelegatedCertInstallerPackage == null) {
4366 int uid = mContext.getPackageManager().getPackageUidAsUser(
4367 policy.mDelegatedCertInstallerPackage, userHandle);
4368 return uid == callingUid;
4369 } catch (NameNotFoundException e) {
4376 public boolean approveCaCert(String alias, int userId, boolean approval) {
4377 enforceManageUsers();
4378 synchronized (this) {
4379 Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4380 boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4384 saveSettingsLocked(userId);
4386 new MonitoringCertNotificationTask().execute(userId);
4391 public boolean isCaCertApproved(String alias, int userId) {
4392 enforceManageUsers();
4393 synchronized (this) {
4394 return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4398 private void removeCaApprovalsIfNeeded(int userId) {
4399 for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4400 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4401 if (userInfo.isManagedProfile()){
4402 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4405 synchronized (this) {
4406 getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4407 saveSettingsLocked(userInfo.id);
4410 new MonitoringCertNotificationTask().execute(userInfo.id);
4416 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4417 enforceCanManageCaCerts(admin);
4421 X509Certificate cert = parseCert(certBuffer);
4422 pemCert = Credentials.convertToPem(cert);
4423 } catch (CertificateException ce) {
4424 Log.e(LOG_TAG, "Problem converting cert", ce);
4426 } catch (IOException ioe) {
4427 Log.e(LOG_TAG, "Problem reading cert", ioe);
4431 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4432 final long id = mInjector.binderClearCallingIdentity();
4434 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4436 keyChainConnection.getService().installCaCertificate(pemCert);
4438 } catch (RemoteException e) {
4439 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4441 keyChainConnection.close();
4443 } catch (InterruptedException e1) {
4444 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4445 Thread.currentThread().interrupt();
4447 mInjector.binderRestoreCallingIdentity(id);
4452 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4453 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4454 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4459 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4460 enforceCanManageCaCerts(admin);
4462 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4463 final long id = mInjector.binderClearCallingIdentity();
4465 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4467 for (int i = 0 ; i < aliases.length; i++) {
4468 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4470 } catch (RemoteException e) {
4471 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4473 keyChainConnection.close();
4475 } catch (InterruptedException ie) {
4476 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4477 Thread.currentThread().interrupt();
4479 mInjector.binderRestoreCallingIdentity(id);
4484 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4485 String alias, boolean requestAccess) {
4486 enforceCanManageInstalledKeys(who);
4488 final int callingUid = mInjector.binderGetCallingUid();
4489 final long id = mInjector.binderClearCallingIdentity();
4491 final KeyChainConnection keyChainConnection =
4492 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4494 IKeyChainService keyChain = keyChainConnection.getService();
4495 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4498 if (requestAccess) {
4499 keyChain.setGrant(callingUid, alias, true);
4502 } catch (RemoteException e) {
4503 Log.e(LOG_TAG, "Installing certificate", e);
4505 keyChainConnection.close();
4507 } catch (InterruptedException e) {
4508 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4509 Thread.currentThread().interrupt();
4511 mInjector.binderRestoreCallingIdentity(id);
4517 public boolean removeKeyPair(ComponentName who, String alias) {
4518 enforceCanManageInstalledKeys(who);
4520 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4521 final long id = Binder.clearCallingIdentity();
4523 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4525 IKeyChainService keyChain = keyChainConnection.getService();
4526 return keyChain.removeKeyPair(alias);
4527 } catch (RemoteException e) {
4528 Log.e(LOG_TAG, "Removing keypair", e);
4530 keyChainConnection.close();
4532 } catch (InterruptedException e) {
4533 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4534 Thread.currentThread().interrupt();
4536 Binder.restoreCallingIdentity(id);
4542 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4543 final IBinder response) {
4544 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4545 if (!isCallerWithSystemUid()) {
4549 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4550 // If there is a profile owner, redirect to that; otherwise query the device owner.
4551 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4552 if (aliasChooser == null && caller.isSystem()) {
4553 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4554 if (deviceOwnerAdmin != null) {
4555 aliasChooser = deviceOwnerAdmin.info.getComponent();
4558 if (aliasChooser == null) {
4559 sendPrivateKeyAliasResponse(null, response);
4563 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4564 intent.setComponent(aliasChooser);
4565 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4566 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4567 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4568 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4569 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4571 final long id = mInjector.binderClearCallingIdentity();
4573 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4575 public void onReceive(Context context, Intent intent) {
4576 final String chosenAlias = getResultData();
4577 sendPrivateKeyAliasResponse(chosenAlias, response);
4579 }, null, Activity.RESULT_OK, null, null);
4581 mInjector.binderRestoreCallingIdentity(id);
4585 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4586 final IKeyChainAliasCallback keyChainAliasResponse =
4587 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4588 new AsyncTask<Void, Void, Void>() {
4590 protected Void doInBackground(Void... unused) {
4592 keyChainAliasResponse.alias(alias);
4593 } catch (Exception e) {
4594 // Catch everything (not just RemoteException): caller could throw a
4595 // RuntimeException back across processes.
4596 Log.e(LOG_TAG, "error while responding to callback", e);
4604 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4605 throws SecurityException {
4606 int userHandle = UserHandle.getCallingUserId();
4607 synchronized (this) {
4608 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4609 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4610 if (installerPackage != null &&
4611 !isPackageInstalledForUser(installerPackage, userHandle)) {
4612 throw new IllegalArgumentException("Package " + installerPackage
4613 + " is not installed on the current user");
4616 DevicePolicyData policy = getUserData(userHandle);
4617 policy.mDelegatedCertInstallerPackage = installerPackage;
4618 saveSettingsLocked(userHandle);
4623 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4624 int userHandle = UserHandle.getCallingUserId();
4625 synchronized (this) {
4626 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4627 DevicePolicyData policy = getUserData(userHandle);
4628 return policy.mDelegatedCertInstallerPackage;
4633 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4634 * not installed and therefore not available.
4636 * @throws SecurityException if the caller is not a profile or device owner.
4637 * @throws UnsupportedOperationException if the package does not support being set as always-on.
4640 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4641 throws SecurityException {
4642 synchronized (this) {
4643 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4646 final int userId = mInjector.userHandleGetCallingUserId();
4647 final long token = mInjector.binderClearCallingIdentity();
4649 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4652 ConnectivityManager connectivityManager = (ConnectivityManager)
4653 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4654 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4655 throw new UnsupportedOperationException();
4658 mInjector.binderRestoreCallingIdentity(token);
4664 public String getAlwaysOnVpnPackage(ComponentName admin)
4665 throws SecurityException {
4666 synchronized (this) {
4667 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4670 final int userId = mInjector.userHandleGetCallingUserId();
4671 final long token = mInjector.binderClearCallingIdentity();
4673 ConnectivityManager connectivityManager = (ConnectivityManager)
4674 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4675 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4677 mInjector.binderRestoreCallingIdentity(token);
4681 private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
4682 if (wipeExtRequested) {
4683 StorageManager sm = (StorageManager) mContext.getSystemService(
4684 Context.STORAGE_SERVICE);
4685 sm.wipeAdoptableDisks();
4688 RecoverySystem.rebootWipeUserData(mContext, reason);
4689 } catch (IOException | SecurityException e) {
4690 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4695 public void wipeData(int flags) {
4699 final int userHandle = mInjector.userHandleGetCallingUserId();
4700 enforceFullCrossUsersPermission(userHandle);
4702 final String source;
4703 synchronized (this) {
4704 // This API can only be called by an active device admin,
4705 // so try to retrieve it to check that the caller is one.
4706 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4707 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4708 source = admin.info.getComponent().flattenToShortString();
4710 long ident = mInjector.binderClearCallingIdentity();
4712 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4713 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4714 throw new SecurityException(
4715 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4717 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4718 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4719 if (manager != null) {
4724 mInjector.binderRestoreCallingIdentity(ident);
4727 final boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4728 wipeDeviceNoLock(wipeExtRequested, userHandle,
4729 "DevicePolicyManager.wipeData() from " + source);
4732 private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
4733 final long ident = mInjector.binderClearCallingIdentity();
4735 if (userHandle == UserHandle.USER_SYSTEM) {
4736 wipeDataNoLock(wipeExtRequested, reason);
4738 mHandler.post(new Runnable() {
4742 IActivityManager am = mInjector.getIActivityManager();
4743 if (am.getCurrentUser().id == userHandle) {
4744 am.switchUser(UserHandle.USER_SYSTEM);
4747 boolean isManagedProfile = isManagedProfile(userHandle);
4748 if (!mUserManager.removeUser(userHandle)) {
4749 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4750 } else if (isManagedProfile) {
4751 sendWipeProfileNotification();
4753 } catch (RemoteException re) {
4760 mInjector.binderRestoreCallingIdentity(ident);
4764 private void sendWipeProfileNotification() {
4765 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4766 Notification notification = new Notification.Builder(mContext)
4767 .setSmallIcon(android.R.drawable.stat_sys_warning)
4768 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4769 .setContentText(contentText)
4770 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4771 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4773 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4776 private void clearWipeProfileNotification() {
4777 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4781 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4785 enforceFullCrossUsersPermission(userHandle);
4786 mContext.enforceCallingOrSelfPermission(
4787 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4789 synchronized (this) {
4790 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4791 if (admin == null) {
4792 result.sendResult(null);
4795 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4796 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4797 intent.setComponent(admin.info.getComponent());
4798 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4799 null, new BroadcastReceiver() {
4801 public void onReceive(Context context, Intent intent) {
4802 result.sendResult(getResultExtras(false));
4804 }, null, Activity.RESULT_OK, null, null);
4809 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4810 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4814 enforceFullCrossUsersPermission(userHandle);
4815 mContext.enforceCallingOrSelfPermission(
4816 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4818 // If the managed profile doesn't have a separate password, set the metrics to default
4819 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
4820 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4830 validateQualityConstant(quality);
4831 DevicePolicyData policy = getUserData(userHandle);
4832 synchronized (this) {
4833 policy.mActivePasswordQuality = quality;
4834 policy.mActivePasswordLength = length;
4835 policy.mActivePasswordLetters = letters;
4836 policy.mActivePasswordLowerCase = lowercase;
4837 policy.mActivePasswordUpperCase = uppercase;
4838 policy.mActivePasswordNumeric = numbers;
4839 policy.mActivePasswordSymbols = symbols;
4840 policy.mActivePasswordNonLetter = nonletter;
4845 public void reportPasswordChanged(int userId) {
4849 enforceFullCrossUsersPermission(userId);
4851 // Managed Profile password can only be changed when it has a separate challenge.
4852 if (!isSeparateProfileChallengeEnabled(userId)) {
4853 enforceNotManagedProfile(userId, "set the active password");
4856 mContext.enforceCallingOrSelfPermission(
4857 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4859 DevicePolicyData policy = getUserData(userId);
4861 long ident = mInjector.binderClearCallingIdentity();
4863 synchronized (this) {
4864 policy.mFailedPasswordAttempts = 0;
4865 saveSettingsLocked(userId);
4866 updatePasswordExpirationsLocked(userId);
4867 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
4869 // Send a broadcast to each profile using this password as its primary unlock.
4870 sendAdminCommandForLockscreenPoliciesLocked(
4871 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4872 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
4874 removeCaApprovalsIfNeeded(userId);
4876 mInjector.binderRestoreCallingIdentity(ident);
4881 * Called any time the device password is updated. Resets all password expiration clocks.
4883 private void updatePasswordExpirationsLocked(int userHandle) {
4884 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4885 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4886 userHandle, /* parent */ false);
4887 final int N = admins.size();
4888 for (int i = 0; i < N; i++) {
4889 ActiveAdmin admin = admins.get(i);
4890 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4891 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4892 long timeout = admin.passwordExpirationTimeout;
4893 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4894 admin.passwordExpirationDate = expiration;
4897 for (int affectedUserId : affectedUserIds) {
4898 saveSettingsLocked(affectedUserId);
4903 public void reportFailedPasswordAttempt(int userHandle) {
4904 enforceFullCrossUsersPermission(userHandle);
4905 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4906 enforceNotManagedProfile(userHandle,
4907 "report failed password attempt if separate profile challenge is not in place");
4909 mContext.enforceCallingOrSelfPermission(
4910 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4912 final long ident = mInjector.binderClearCallingIdentity();
4914 boolean wipeData = false;
4916 synchronized (this) {
4917 DevicePolicyData policy = getUserData(userHandle);
4918 policy.mFailedPasswordAttempts++;
4919 saveSettingsLocked(userHandle);
4921 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4922 userHandle, /* parent */ false);
4923 int max = strictestAdmin != null
4924 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4925 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4926 // Wipe the user/profile associated with the policy that was violated. This
4927 // is not necessarily calling user: if the policy that fired was from a
4928 // managed profile rather than the main user profile, we wipe former only.
4930 identifier = strictestAdmin.getUserHandle().getIdentifier();
4933 sendAdminCommandForLockscreenPoliciesLocked(
4934 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
4935 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4939 // Call without holding lock.
4940 wipeDeviceNoLock(false, identifier,
4941 "reportFailedPasswordAttempt()");
4944 mInjector.binderRestoreCallingIdentity(ident);
4947 if (mInjector.securityLogIsLoggingEnabled()) {
4948 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4949 /*method strength*/ 1);
4954 public void reportSuccessfulPasswordAttempt(int userHandle) {
4955 enforceFullCrossUsersPermission(userHandle);
4956 mContext.enforceCallingOrSelfPermission(
4957 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4959 synchronized (this) {
4960 DevicePolicyData policy = getUserData(userHandle);
4961 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
4962 long ident = mInjector.binderClearCallingIdentity();
4964 policy.mFailedPasswordAttempts = 0;
4965 policy.mPasswordOwner = -1;
4966 saveSettingsLocked(userHandle);
4968 sendAdminCommandForLockscreenPoliciesLocked(
4969 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
4970 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4973 mInjector.binderRestoreCallingIdentity(ident);
4978 if (mInjector.securityLogIsLoggingEnabled()) {
4979 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4980 /*method strength*/ 1);
4985 public void reportFailedFingerprintAttempt(int userHandle) {
4986 enforceFullCrossUsersPermission(userHandle);
4987 mContext.enforceCallingOrSelfPermission(
4988 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4989 if (mInjector.securityLogIsLoggingEnabled()) {
4990 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4991 /*method strength*/ 0);
4996 public void reportSuccessfulFingerprintAttempt(int userHandle) {
4997 enforceFullCrossUsersPermission(userHandle);
4998 mContext.enforceCallingOrSelfPermission(
4999 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5000 if (mInjector.securityLogIsLoggingEnabled()) {
5001 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5002 /*method strength*/ 0);
5007 public void reportKeyguardDismissed(int userHandle) {
5008 enforceFullCrossUsersPermission(userHandle);
5009 mContext.enforceCallingOrSelfPermission(
5010 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5012 if (mInjector.securityLogIsLoggingEnabled()) {
5013 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
5018 public void reportKeyguardSecured(int userHandle) {
5019 enforceFullCrossUsersPermission(userHandle);
5020 mContext.enforceCallingOrSelfPermission(
5021 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5023 if (mInjector.securityLogIsLoggingEnabled()) {
5024 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
5029 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
5030 String exclusionList) {
5034 synchronized(this) {
5035 Preconditions.checkNotNull(who, "ComponentName is null");
5037 // Only check if system user has set global proxy. We don't allow other users to set it.
5038 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5039 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5040 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
5042 // Scan through active admins and find if anyone has already
5043 // set the global proxy.
5044 Set<ComponentName> compSet = policy.mAdminMap.keySet();
5045 for (ComponentName component : compSet) {
5046 ActiveAdmin ap = policy.mAdminMap.get(component);
5047 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
5048 // Another admin already sets the global proxy
5049 // Return it to the caller.
5054 // If the user is not system, don't set the global proxy. Fail silently.
5055 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
5056 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
5057 + UserHandle.getCallingUserId() + " is not permitted.");
5060 if (proxySpec == null) {
5061 admin.specifiesGlobalProxy = false;
5062 admin.globalProxySpec = null;
5063 admin.globalProxyExclusionList = null;
5066 admin.specifiesGlobalProxy = true;
5067 admin.globalProxySpec = proxySpec;
5068 admin.globalProxyExclusionList = exclusionList;
5071 // Reset the global proxy accordingly
5072 // Do this using system permissions, as apps cannot write to secure settings
5073 long origId = mInjector.binderClearCallingIdentity();
5075 resetGlobalProxyLocked(policy);
5077 mInjector.binderRestoreCallingIdentity(origId);
5084 public ComponentName getGlobalProxyAdmin(int userHandle) {
5088 enforceFullCrossUsersPermission(userHandle);
5089 synchronized(this) {
5090 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5091 // Scan through active admins and find if anyone has already
5092 // set the global proxy.
5093 final int N = policy.mAdminList.size();
5094 for (int i = 0; i < N; i++) {
5095 ActiveAdmin ap = policy.mAdminList.get(i);
5096 if (ap.specifiesGlobalProxy) {
5097 // Device admin sets the global proxy
5098 // Return it to the caller.
5099 return ap.info.getComponent();
5103 // No device admin sets the global proxy.
5108 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5109 synchronized (this) {
5110 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5112 long token = mInjector.binderClearCallingIdentity();
5114 ConnectivityManager connectivityManager = (ConnectivityManager)
5115 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5116 connectivityManager.setGlobalProxy(proxyInfo);
5118 mInjector.binderRestoreCallingIdentity(token);
5122 private void resetGlobalProxyLocked(DevicePolicyData policy) {
5123 final int N = policy.mAdminList.size();
5124 for (int i = 0; i < N; i++) {
5125 ActiveAdmin ap = policy.mAdminList.get(i);
5126 if (ap.specifiesGlobalProxy) {
5127 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5131 // No device admins defining global proxies - reset global proxy settings to none
5132 saveGlobalProxyLocked(null, null);
5135 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5136 if (exclusionList == null) {
5139 if (proxySpec == null) {
5142 // Remove white spaces
5143 proxySpec = proxySpec.trim();
5144 String data[] = proxySpec.split(":");
5145 int proxyPort = 8080;
5146 if (data.length > 1) {
5148 proxyPort = Integer.parseInt(data[1]);
5149 } catch (NumberFormatException e) {}
5151 exclusionList = exclusionList.trim();
5153 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5154 if (!proxyProperties.isValid()) {
5155 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5158 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5159 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5160 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5165 * Set the storage encryption request for a single admin. Returns the new total request
5166 * status (for all admins).
5169 public int setStorageEncryption(ComponentName who, boolean encrypt) {
5171 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5173 Preconditions.checkNotNull(who, "ComponentName is null");
5174 final int userHandle = UserHandle.getCallingUserId();
5175 synchronized (this) {
5176 // Check for permissions
5177 // Only system user can set storage encryption
5178 if (userHandle != UserHandle.USER_SYSTEM) {
5179 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5180 + UserHandle.getCallingUserId() + " is not permitted.");
5184 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5185 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5187 // Quick exit: If the filesystem does not support encryption, we can exit early.
5188 if (!isEncryptionSupported()) {
5189 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5192 // (1) Record the value for the admin so it's sticky
5193 if (ap.encryptionRequested != encrypt) {
5194 ap.encryptionRequested = encrypt;
5195 saveSettingsLocked(userHandle);
5198 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5199 // (2) Compute "max" for all admins
5200 boolean newRequested = false;
5201 final int N = policy.mAdminList.size();
5202 for (int i = 0; i < N; i++) {
5203 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5206 // Notify OS of new request
5207 setEncryptionRequested(newRequested);
5209 // Return the new global request status
5211 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5212 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5217 * Get the current storage encryption request status for a given admin, or aggregate of all
5221 public boolean getStorageEncryption(ComponentName who, int userHandle) {
5225 enforceFullCrossUsersPermission(userHandle);
5226 synchronized (this) {
5227 // Check for permissions if a particular caller is specified
5229 // When checking for a single caller, status is based on caller's request
5230 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5231 return ap != null ? ap.encryptionRequested : false;
5234 // If no particular caller is specified, return the aggregate set of requests.
5235 // This is short circuited by returning true on the first hit.
5236 DevicePolicyData policy = getUserData(userHandle);
5237 final int N = policy.mAdminList.size();
5238 for (int i = 0; i < N; i++) {
5239 if (policy.mAdminList.get(i).encryptionRequested) {
5248 * Get the current encryption status of the device.
5251 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5253 // Ok to return current status.
5255 enforceFullCrossUsersPermission(userHandle);
5257 // It's not critical here, but let's make sure the package name is correct, in case
5258 // we start using it for different purposes.
5259 ensureCallerPackage(callerPackage);
5261 final ApplicationInfo ai;
5263 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5264 } catch (RemoteException e) {
5265 throw new SecurityException(e);
5268 boolean legacyApp = false;
5269 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5273 final int rawStatus = getEncryptionStatus();
5274 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5275 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5281 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
5283 private boolean isEncryptionSupported() {
5284 // Note, this can be implemented as
5285 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5286 // But is provided as a separate internal method if there's a faster way to do a
5287 // simple check for supported-or-not.
5288 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5292 * Hook to low-levels: Reporting the current status of encryption.
5293 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5294 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5295 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5296 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5297 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5299 private int getEncryptionStatus() {
5300 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5301 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5302 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5303 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5304 } else if (mInjector.storageManagerIsEncrypted()) {
5305 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5306 } else if (mInjector.storageManagerIsEncryptable()) {
5307 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5309 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5314 * Hook to low-levels: If needed, record the new admin setting for encryption.
5316 private void setEncryptionRequested(boolean encrypt) {
5320 * Set whether the screen capture is disabled for the user managed by the specified admin.
5323 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5327 Preconditions.checkNotNull(who, "ComponentName is null");
5328 final int userHandle = UserHandle.getCallingUserId();
5329 synchronized (this) {
5330 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5331 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5332 if (ap.disableScreenCapture != disabled) {
5333 ap.disableScreenCapture = disabled;
5334 saveSettingsLocked(userHandle);
5335 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5341 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5342 * active admin (if given admin is null).
5345 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5349 synchronized (this) {
5351 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5352 return (admin != null) ? admin.disableScreenCapture : false;
5355 DevicePolicyData policy = getUserData(userHandle);
5356 final int N = policy.mAdminList.size();
5357 for (int i = 0; i < N; i++) {
5358 ActiveAdmin admin = policy.mAdminList.get(i);
5359 if (admin.disableScreenCapture) {
5367 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5368 final boolean disabled) {
5369 mHandler.post(new Runnable() {
5373 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5374 } catch (RemoteException e) {
5375 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5382 * Set whether auto time is required by the specified admin (must be device owner).
5385 public void setAutoTimeRequired(ComponentName who, boolean required) {
5389 Preconditions.checkNotNull(who, "ComponentName is null");
5390 final int userHandle = UserHandle.getCallingUserId();
5391 synchronized (this) {
5392 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5393 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5394 if (admin.requireAutoTime != required) {
5395 admin.requireAutoTime = required;
5396 saveSettingsLocked(userHandle);
5400 // Turn AUTO_TIME on in settings if it is required
5402 long ident = mInjector.binderClearCallingIdentity();
5404 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5406 mInjector.binderRestoreCallingIdentity(ident);
5412 * Returns whether or not auto time is required by the device owner.
5415 public boolean getAutoTimeRequired() {
5419 synchronized (this) {
5420 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5421 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5426 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5430 Preconditions.checkNotNull(who, "ComponentName is null");
5431 // Allow setting this policy to true only if there is a split system user.
5432 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5433 throw new UnsupportedOperationException(
5434 "Cannot force ephemeral users on systems without split system user.");
5436 boolean removeAllUsers = false;
5437 synchronized (this) {
5438 final ActiveAdmin deviceOwner =
5439 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5440 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5441 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5442 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5443 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5444 removeAllUsers = forceEphemeralUsers;
5447 if (removeAllUsers) {
5448 long identitity = mInjector.binderClearCallingIdentity();
5450 mUserManagerInternal.removeAllUsers();
5452 mInjector.binderRestoreCallingIdentity(identitity);
5458 public boolean getForceEphemeralUsers(ComponentName who) {
5462 Preconditions.checkNotNull(who, "ComponentName is null");
5463 synchronized (this) {
5464 final ActiveAdmin deviceOwner =
5465 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5466 return deviceOwner.forceEphemeralUsers;
5470 private boolean isDeviceOwnerManagedSingleUserDevice() {
5471 synchronized (this) {
5472 if (!mOwners.hasDeviceOwner()) {
5476 final long callingIdentity = mInjector.binderClearCallingIdentity();
5478 if (mInjector.userManagerIsSplitSystemUser()) {
5479 // In split system user mode, only allow the case where the device owner is managing
5480 // the only non-system user of the device
5481 return (mUserManager.getUserCount() == 2
5482 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5484 return mUserManager.getUserCount() == 1;
5487 mInjector.binderRestoreCallingIdentity(callingIdentity);
5491 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5492 synchronized (this) {
5493 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5495 if (!isDeviceOwnerManagedSingleUserDevice()) {
5496 throw new SecurityException(
5497 "There should only be one user, managed by Device Owner");
5502 public boolean requestBugreport(ComponentName who) {
5506 Preconditions.checkNotNull(who, "ComponentName is null");
5507 ensureDeviceOwnerManagingSingleUser(who);
5509 if (mRemoteBugreportServiceIsActive.get()
5510 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5511 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5515 final long callingIdentity = mInjector.binderClearCallingIdentity();
5517 ActivityManagerNative.getDefault().requestBugReport(
5518 ActivityManager.BUGREPORT_OPTION_REMOTE);
5520 mRemoteBugreportServiceIsActive.set(true);
5521 mRemoteBugreportSharingAccepted.set(false);
5522 registerRemoteBugreportReceivers();
5523 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5524 RemoteBugreportUtils.buildNotification(mContext,
5525 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5526 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5527 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5529 } catch (RemoteException re) {
5530 // should never happen
5531 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5534 mInjector.binderRestoreCallingIdentity(callingIdentity);
5538 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5539 Intent intent = new Intent(action);
5540 intent.setComponent(mOwners.getDeviceOwnerComponent());
5541 if (extras != null) {
5542 intent.putExtras(extras);
5544 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5547 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5548 return mOwners.getDeviceOwnerRemoteBugreportUri();
5551 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5552 String bugreportHash) {
5553 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5556 private void registerRemoteBugreportReceivers() {
5558 IntentFilter filterFinished = new IntentFilter(
5559 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5560 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5561 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5562 } catch (IntentFilter.MalformedMimeTypeException e) {
5563 // should never happen, as setting a constant
5564 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5566 IntentFilter filterConsent = new IntentFilter();
5567 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5568 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5569 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5572 private void onBugreportFinished(Intent intent) {
5573 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5574 mRemoteBugreportServiceIsActive.set(false);
5575 Uri bugreportUri = intent.getData();
5576 String bugreportUriString = null;
5577 if (bugreportUri != null) {
5578 bugreportUriString = bugreportUri.toString();
5580 String bugreportHash = intent.getStringExtra(
5581 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5582 if (mRemoteBugreportSharingAccepted.get()) {
5583 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5584 mInjector.getNotificationManager().cancel(LOG_TAG,
5585 RemoteBugreportUtils.NOTIFICATION_ID);
5587 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5588 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5589 RemoteBugreportUtils.buildNotification(mContext,
5590 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5593 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5596 private void onBugreportFailed() {
5597 mRemoteBugreportServiceIsActive.set(false);
5598 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5599 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5600 mRemoteBugreportSharingAccepted.set(false);
5601 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5602 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5603 Bundle extras = new Bundle();
5604 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5605 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5606 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5607 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5608 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5611 private void onBugreportSharingAccepted() {
5612 mRemoteBugreportSharingAccepted.set(true);
5613 String bugreportUriString = null;
5614 String bugreportHash = null;
5615 synchronized (this) {
5616 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5617 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5619 if (bugreportUriString != null) {
5620 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5621 } else if (mRemoteBugreportServiceIsActive.get()) {
5622 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5623 RemoteBugreportUtils.buildNotification(mContext,
5624 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5629 private void onBugreportSharingDeclined() {
5630 if (mRemoteBugreportServiceIsActive.get()) {
5631 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5632 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5633 mRemoteBugreportServiceIsActive.set(false);
5634 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5635 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5637 mRemoteBugreportSharingAccepted.set(false);
5638 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5639 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5642 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5643 String bugreportHash) {
5644 ParcelFileDescriptor pfd = null;
5646 if (bugreportUriString == null) {
5647 throw new FileNotFoundException();
5649 Uri bugreportUri = Uri.parse(bugreportUriString);
5650 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5652 synchronized (this) {
5653 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5654 intent.setComponent(mOwners.getDeviceOwnerComponent());
5655 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5656 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5657 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
5659 LocalServices.getService(ActivityManagerInternal.class)
5660 .grantUriPermissionFromIntent(Process.SHELL_UID,
5661 mOwners.getDeviceOwnerComponent().getPackageName(),
5662 intent, mOwners.getDeviceOwnerUserId());
5663 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5665 } catch (FileNotFoundException e) {
5666 Bundle extras = new Bundle();
5667 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5668 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5669 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5675 } catch (IOException ex) {
5678 mRemoteBugreportSharingAccepted.set(false);
5679 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5684 * Disables all device cameras according to the specified admin.
5687 public void setCameraDisabled(ComponentName who, boolean disabled) {
5691 Preconditions.checkNotNull(who, "ComponentName is null");
5692 final int userHandle = mInjector.userHandleGetCallingUserId();
5693 synchronized (this) {
5694 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5695 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5696 if (ap.disableCamera != disabled) {
5697 ap.disableCamera = disabled;
5698 saveSettingsLocked(userHandle);
5701 // Tell the user manager that the restrictions have changed.
5702 pushUserRestrictions(userHandle);
5706 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5710 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5711 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5714 private boolean getCameraDisabled(ComponentName who, int userHandle,
5715 boolean mergeDeviceOwnerRestriction) {
5719 synchronized (this) {
5721 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5722 return (admin != null) ? admin.disableCamera : false;
5724 // First, see if DO has set it. If so, it's device-wide.
5725 if (mergeDeviceOwnerRestriction) {
5726 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5727 if (deviceOwner != null && deviceOwner.disableCamera) {
5732 // Then check each device admin on the user.
5733 DevicePolicyData policy = getUserData(userHandle);
5734 // Determine whether or not the device camera is disabled for any active admins.
5735 final int N = policy.mAdminList.size();
5736 for (int i = 0; i < N; i++) {
5737 ActiveAdmin admin = policy.mAdminList.get(i);
5738 if (admin.disableCamera) {
5747 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5751 Preconditions.checkNotNull(who, "ComponentName is null");
5752 final int userHandle = mInjector.userHandleGetCallingUserId();
5753 if (isManagedProfile(userHandle)) {
5755 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5757 which = which & PROFILE_KEYGUARD_FEATURES;
5760 synchronized (this) {
5761 ActiveAdmin ap = getActiveAdminForCallerLocked(
5762 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5763 if (ap.disabledKeyguardFeatures != which) {
5764 ap.disabledKeyguardFeatures = which;
5765 saveSettingsLocked(userHandle);
5771 * Gets the disabled state for features in keyguard for the given admin,
5772 * or the aggregate of all active admins if who is null.
5775 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5779 enforceFullCrossUsersPermission(userHandle);
5780 final long ident = mInjector.binderClearCallingIdentity();
5782 synchronized (this) {
5784 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5785 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5788 final List<ActiveAdmin> admins;
5789 if (!parent && isManagedProfile(userHandle)) {
5790 // If we are being asked about a managed profile, just return keyguard features
5791 // disabled by admins in the profile.
5792 admins = getUserDataUnchecked(userHandle).mAdminList;
5794 // Otherwise return those set by admins in the user and its profiles.
5795 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5798 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5799 final int N = admins.size();
5800 for (int i = 0; i < N; i++) {
5801 ActiveAdmin admin = admins.get(i);
5802 int userId = admin.getUserHandle().getIdentifier();
5803 boolean isRequestedUser = !parent && (userId == userHandle);
5804 if (isRequestedUser || !isManagedProfile(userId)) {
5805 // If we are being asked explicitly about this user
5806 // return all disabled features even if its a managed profile.
5807 which |= admin.disabledKeyguardFeatures;
5809 // Otherwise a managed profile is only allowed to disable
5810 // some features on the parent user.
5811 which |= (admin.disabledKeyguardFeatures
5812 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5818 mInjector.binderRestoreCallingIdentity(ident);
5823 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5827 Preconditions.checkNotNull(who, "ComponentName is null");
5828 Preconditions.checkNotNull(packageList, "packageList is null");
5829 final int userHandle = UserHandle.getCallingUserId();
5830 synchronized (this) {
5831 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5832 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5833 admin.keepUninstalledPackages = packageList;
5834 saveSettingsLocked(userHandle);
5835 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5840 public List<String> getKeepUninstalledPackages(ComponentName who) {
5841 Preconditions.checkNotNull(who, "ComponentName is null");
5845 // TODO In split system user mode, allow apps on user 0 to query the list
5846 synchronized (this) {
5847 // Check if this is the device owner who is calling
5848 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5849 return getKeepUninstalledPackagesLocked();
5853 private List<String> getKeepUninstalledPackagesLocked() {
5854 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5855 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5859 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5864 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5865 throw new IllegalArgumentException("Invalid component " + admin
5866 + " for device owner");
5868 synchronized (this) {
5869 enforceCanSetDeviceOwnerLocked(admin, userId);
5870 if (getActiveAdminUncheckedLocked(admin, userId) == null
5871 || getUserData(userId).mRemovingAdmins.contains(admin)) {
5872 throw new IllegalArgumentException("Not active admin: " + admin);
5875 // Shutting down backup manager service permanently.
5876 long ident = mInjector.binderClearCallingIdentity();
5878 if (mInjector.getIBackupManager() != null) {
5879 mInjector.getIBackupManager()
5880 .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5882 } catch (RemoteException e) {
5883 throw new IllegalStateException("Failed deactivating backup service.", e);
5885 mInjector.binderRestoreCallingIdentity(ident);
5888 mOwners.setDeviceOwner(admin, ownerName, userId);
5889 mOwners.writeDeviceOwner();
5890 updateDeviceOwnerLocked();
5891 setDeviceOwnerSystemPropertyLocked();
5892 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5894 ident = mInjector.binderClearCallingIdentity();
5896 // TODO Send to system too?
5897 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5899 mInjector.binderRestoreCallingIdentity(ident);
5901 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
5906 public boolean isDeviceOwner(ComponentName who, int userId) {
5907 synchronized (this) {
5908 return mOwners.hasDeviceOwner()
5909 && mOwners.getDeviceOwnerUserId() == userId
5910 && mOwners.getDeviceOwnerComponent().equals(who);
5914 public boolean isProfileOwner(ComponentName who, int userId) {
5915 final ComponentName profileOwner = getProfileOwner(userId);
5916 return who != null && who.equals(profileOwner);
5920 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5924 if (!callingUserOnly) {
5925 enforceManageUsers();
5927 synchronized (this) {
5928 if (!mOwners.hasDeviceOwner()) {
5931 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
5932 mOwners.getDeviceOwnerUserId()) {
5935 return mOwners.getDeviceOwnerComponent();
5940 public int getDeviceOwnerUserId() {
5942 return UserHandle.USER_NULL;
5944 enforceManageUsers();
5945 synchronized (this) {
5946 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
5951 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
5955 public String getDeviceOwnerName() {
5959 enforceManageUsers();
5960 synchronized (this) {
5961 if (!mOwners.hasDeviceOwner()) {
5964 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
5965 // Should setDeviceOwner/ProfileOwner still take a name?
5966 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
5967 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
5971 // Returns the active device owner or null if there is no device owner.
5973 ActiveAdmin getDeviceOwnerAdminLocked() {
5974 ComponentName component = mOwners.getDeviceOwnerComponent();
5975 if (component == null) {
5979 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
5980 final int n = policy.mAdminList.size();
5981 for (int i = 0; i < n; i++) {
5982 ActiveAdmin admin = policy.mAdminList.get(i);
5983 if (component.equals(admin.info.getComponent())) {
5987 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
5992 public void clearDeviceOwner(String packageName) {
5993 Preconditions.checkNotNull(packageName, "packageName is null");
5994 final int callingUid = mInjector.binderGetCallingUid();
5996 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
5997 UserHandle.getUserId(callingUid));
5998 if (uid != callingUid) {
5999 throw new SecurityException("Invalid packageName");
6001 } catch (NameNotFoundException e) {
6002 throw new SecurityException(e);
6004 synchronized (this) {
6005 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6006 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6007 if (!mOwners.hasDeviceOwner()
6008 || !deviceOwnerComponent.getPackageName().equals(packageName)
6009 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
6010 throw new SecurityException(
6011 "clearDeviceOwner can only be called by the device owner");
6013 enforceUserUnlocked(deviceOwnerUserId);
6015 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
6016 long ident = mInjector.binderClearCallingIdentity();
6018 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
6019 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
6021 mInjector.binderRestoreCallingIdentity(ident);
6023 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
6027 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
6028 if (admin != null) {
6029 admin.disableCamera = false;
6030 admin.userRestrictions = null;
6031 admin.forceEphemeralUsers = false;
6032 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
6034 clearUserPoliciesLocked(userId);
6036 mOwners.clearDeviceOwner();
6037 mOwners.writeDeviceOwner();
6038 updateDeviceOwnerLocked();
6039 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
6041 // Reactivate backup service.
6042 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6043 } catch (RemoteException e) {
6044 throw new IllegalStateException("Failed reactivating backup service.", e);
6049 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6054 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6055 throw new IllegalArgumentException("Component " + who
6056 + " not installed for userId:" + userHandle);
6058 synchronized (this) {
6059 enforceCanSetProfileOwnerLocked(who, userHandle);
6061 if (getActiveAdminUncheckedLocked(who, userHandle) == null
6062 || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6063 throw new IllegalArgumentException("Not active admin: " + who);
6066 mOwners.setProfileOwner(who, ownerName, userHandle);
6067 mOwners.writeProfileOwner(userHandle);
6068 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6074 public void clearProfileOwner(ComponentName who) {
6078 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
6079 final int userId = callingUser.getIdentifier();
6080 enforceNotManagedProfile(userId, "clear profile owner");
6081 enforceUserUnlocked(userId);
6082 // Check if this is the profile owner who is calling
6083 final ActiveAdmin admin =
6084 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6085 synchronized (this) {
6086 final long ident = mInjector.binderClearCallingIdentity();
6088 clearProfileOwnerLocked(admin, userId);
6089 removeActiveAdminLocked(who, userId);
6091 mInjector.binderRestoreCallingIdentity(ident);
6093 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6097 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6098 if (admin != null) {
6099 admin.disableCamera = false;
6100 admin.userRestrictions = null;
6102 clearUserPoliciesLocked(userId);
6103 mOwners.removeProfileOwner(userId);
6104 mOwners.writeProfileOwner(userId);
6108 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6109 Preconditions.checkNotNull(who, "ComponentName is null");
6114 synchronized (this) {
6115 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6116 long token = mInjector.binderClearCallingIdentity();
6118 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6120 mInjector.binderRestoreCallingIdentity(token);
6126 public CharSequence getDeviceOwnerLockScreenInfo() {
6127 return mLockPatternUtils.getDeviceOwnerInfo();
6130 private void clearUserPoliciesLocked(int userId) {
6131 // Reset some of the user-specific policies
6132 DevicePolicyData policy = getUserData(userId);
6133 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6134 policy.mDelegatedCertInstallerPackage = null;
6135 policy.mApplicationRestrictionsManagingPackage = null;
6136 policy.mStatusBarDisabled = false;
6137 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6138 saveSettingsLocked(userId);
6141 mIPackageManager.updatePermissionFlagsForAllApps(
6142 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6143 0 /* flagValues */, userId);
6144 pushUserRestrictions(userId);
6145 } catch (RemoteException re) {
6146 // Shouldn't happen.
6151 public boolean hasUserSetupCompleted() {
6152 return hasUserSetupCompleted(UserHandle.getCallingUserId());
6155 private boolean hasUserSetupCompleted(int userHandle) {
6159 return getUserData(userHandle).mUserSetupComplete;
6163 public int getUserProvisioningState() {
6165 return DevicePolicyManager.STATE_USER_UNMANAGED;
6167 int userHandle = mInjector.userHandleGetCallingUserId();
6168 return getUserProvisioningState(userHandle);
6171 private int getUserProvisioningState(int userHandle) {
6172 return getUserData(userHandle).mUserProvisioningState;
6176 public void setUserProvisioningState(int newState, int userHandle) {
6181 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6182 && getManagedUserId(userHandle) == -1) {
6183 // No managed device, user or profile, so setting provisioning state makes no sense.
6184 throw new IllegalStateException("Not allowed to change provisioning state unless a "
6185 + "device or profile owner is set.");
6188 synchronized (this) {
6189 boolean transitionCheckNeeded = true;
6191 // Calling identity/permission checks.
6192 final int callingUid = mInjector.binderGetCallingUid();
6193 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6194 // ADB shell can only move directly from un-managed to finalized as part of directly
6195 // setting profile-owner or device-owner.
6196 if (getUserProvisioningState(userHandle) !=
6197 DevicePolicyManager.STATE_USER_UNMANAGED
6198 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6199 throw new IllegalStateException("Not allowed to change provisioning state "
6200 + "unless current provisioning state is unmanaged, and new state is "
6203 transitionCheckNeeded = false;
6205 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6206 enforceCanManageProfileAndDeviceOwners();
6209 final DevicePolicyData policyData = getUserData(userHandle);
6210 if (transitionCheckNeeded) {
6211 // Optional state transition check for non-ADB case.
6212 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6214 policyData.mUserProvisioningState = newState;
6215 saveSettingsLocked(userHandle);
6219 private void checkUserProvisioningStateTransition(int currentState, int newState) {
6220 // Valid transitions for normal use-cases.
6221 switch (currentState) {
6222 case DevicePolicyManager.STATE_USER_UNMANAGED:
6223 // Can move to any state from unmanaged (except itself as an edge case)..
6224 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6228 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6229 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6230 // Can only move to finalized from these states.
6231 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6235 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6236 // Current user has a managed-profile, but current user is not managed, so
6237 // rather than moving to finalized state, go back to unmanaged once
6238 // profile provisioning is complete.
6239 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6243 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6244 // Cannot transition out of finalized.
6248 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6249 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6250 + "from state [" + currentState + "]");
6254 public void setProfileEnabled(ComponentName who) {
6258 Preconditions.checkNotNull(who, "ComponentName is null");
6259 synchronized (this) {
6260 // Check if this is the profile owner who is calling
6261 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6262 final int userId = UserHandle.getCallingUserId();
6263 enforceManagedProfile(userId, "enable the profile");
6265 long id = mInjector.binderClearCallingIdentity();
6267 mUserManager.setUserEnabled(userId);
6268 UserInfo parent = mUserManager.getProfileParent(userId);
6269 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6270 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6271 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6272 Intent.FLAG_RECEIVER_FOREGROUND);
6273 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6275 mInjector.binderRestoreCallingIdentity(id);
6281 public void setProfileName(ComponentName who, String profileName) {
6282 Preconditions.checkNotNull(who, "ComponentName is null");
6283 int userId = UserHandle.getCallingUserId();
6284 // Check if this is the profile owner (includes device owner).
6285 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6287 long id = mInjector.binderClearCallingIdentity();
6289 mUserManager.setUserName(userId, profileName);
6291 mInjector.binderRestoreCallingIdentity(id);
6296 public ComponentName getProfileOwner(int userHandle) {
6301 synchronized (this) {
6302 return mOwners.getProfileOwnerComponent(userHandle);
6306 // Returns the active profile owner for this user or null if the current user has no
6309 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6310 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6311 if (profileOwner == null) {
6314 DevicePolicyData policy = getUserData(userHandle);
6315 final int n = policy.mAdminList.size();
6316 for (int i = 0; i < n; i++) {
6317 ActiveAdmin admin = policy.mAdminList.get(i);
6318 if (profileOwner.equals(admin.info.getComponent())) {
6326 public String getProfileOwnerName(int userHandle) {
6330 enforceManageUsers();
6331 ComponentName profileOwner = getProfileOwner(userHandle);
6332 if (profileOwner == null) {
6335 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6339 * Canonical name for a given package.
6341 private String getApplicationLabel(String packageName, int userHandle) {
6342 long token = mInjector.binderClearCallingIdentity();
6344 final Context userContext;
6346 UserHandle handle = new UserHandle(userHandle);
6347 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6348 } catch (PackageManager.NameNotFoundException nnfe) {
6349 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6352 ApplicationInfo appInfo = userContext.getApplicationInfo();
6353 CharSequence result = null;
6354 if (appInfo != null) {
6355 PackageManager pm = userContext.getPackageManager();
6356 result = pm.getApplicationLabel(appInfo);
6358 return result != null ? result.toString() : null;
6360 mInjector.binderRestoreCallingIdentity(token);
6365 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6367 * The profile owner can only be set before the user setup phase has completed,
6370 * - adb if there are no accounts. (But see {@link #hasIncompatibleAccountsLocked})
6372 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle) {
6373 UserInfo info = getUserInfo(userHandle);
6375 // User doesn't exist.
6376 throw new IllegalArgumentException(
6377 "Attempted to set profile owner for invalid userId: " + userHandle);
6379 if (info.isGuest()) {
6380 throw new IllegalStateException("Cannot set a profile owner on a guest");
6382 if (mOwners.hasProfileOwner(userHandle)) {
6383 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6384 + "is already set.");
6386 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6387 throw new IllegalStateException("Trying to set the profile owner, but the user "
6388 + "already has a device owner.");
6390 int callingUid = mInjector.binderGetCallingUid();
6391 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6392 if (hasUserSetupCompleted(userHandle)
6393 && hasIncompatibleAccountsLocked(userHandle, owner)) {
6394 throw new IllegalStateException("Not allowed to set the profile owner because "
6395 + "there are already some accounts on the profile");
6399 enforceCanManageProfileAndDeviceOwners();
6400 if (hasUserSetupCompleted(userHandle) && !isCallerWithSystemUid()) {
6401 throw new IllegalStateException("Cannot set the profile owner on a user which is "
6402 + "already set-up");
6407 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6410 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId) {
6411 int callingUid = mInjector.binderGetCallingUid();
6412 boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6414 enforceCanManageProfileAndDeviceOwners();
6417 final int code = checkSetDeviceOwnerPreConditionLocked(owner, userId, isAdb);
6421 case CODE_HAS_DEVICE_OWNER:
6422 throw new IllegalStateException(
6423 "Trying to set the device owner, but device owner is already set.");
6424 case CODE_USER_HAS_PROFILE_OWNER:
6425 throw new IllegalStateException("Trying to set the device owner, but the user "
6426 + "already has a profile owner.");
6427 case CODE_USER_NOT_RUNNING:
6428 throw new IllegalStateException("User not running: " + userId);
6429 case CODE_NOT_SYSTEM_USER:
6430 throw new IllegalStateException("User is not system user");
6431 case CODE_USER_SETUP_COMPLETED:
6432 throw new IllegalStateException(
6433 "Cannot set the device owner if the device is already set-up");
6434 case CODE_NONSYSTEM_USER_EXISTS:
6435 throw new IllegalStateException("Not allowed to set the device owner because there "
6436 + "are already several users on the device");
6437 case CODE_ACCOUNTS_NOT_EMPTY:
6438 throw new IllegalStateException("Not allowed to set the device owner because there "
6439 + "are already some accounts on the device");
6441 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6445 private void enforceUserUnlocked(int userId) {
6446 // Since we're doing this operation on behalf of an app, we only
6447 // want to use the actual "unlocked" state.
6448 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6449 "User must be running and unlocked");
6452 private void enforceUserUnlocked(int userId, boolean parent) {
6454 enforceUserUnlocked(getProfileParentId(userId));
6456 enforceUserUnlocked(userId);
6460 private void enforceManageUsers() {
6461 final int callingUid = mInjector.binderGetCallingUid();
6462 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6463 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6467 private void enforceFullCrossUsersPermission(int userHandle) {
6468 enforceSystemUserOrPermission(userHandle,
6469 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6472 private void enforceCrossUsersPermission(int userHandle) {
6473 enforceSystemUserOrPermission(userHandle,
6474 android.Manifest.permission.INTERACT_ACROSS_USERS);
6477 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6478 if (userHandle < 0) {
6479 throw new IllegalArgumentException("Invalid userId " + userHandle);
6481 final int callingUid = mInjector.binderGetCallingUid();
6482 if (userHandle == UserHandle.getUserId(callingUid)) {
6485 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6486 mContext.enforceCallingOrSelfPermission(permission,
6487 "Must be system or have " + permission + " permission");
6491 private void enforceManagedProfile(int userHandle, String message) {
6492 if(!isManagedProfile(userHandle)) {
6493 throw new SecurityException("You can not " + message + " outside a managed profile.");
6497 private void enforceNotManagedProfile(int userHandle, String message) {
6498 if(isManagedProfile(userHandle)) {
6499 throw new SecurityException("You can not " + message + " for a managed profile.");
6503 private void ensureCallerPackage(@Nullable String packageName) {
6504 if (packageName == null) {
6505 Preconditions.checkState(isCallerWithSystemUid(),
6506 "Only caller can omit package name");
6508 final int callingUid = mInjector.binderGetCallingUid();
6509 final int userId = mInjector.userHandleGetCallingUserId();
6511 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6512 packageName, 0, userId);
6513 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6514 } catch (RemoteException e) {
6520 private boolean isCallerWithSystemUid() {
6521 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6524 private int getProfileParentId(int userHandle) {
6525 final long ident = mInjector.binderClearCallingIdentity();
6527 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6528 return parentUser != null ? parentUser.id : userHandle;
6530 mInjector.binderRestoreCallingIdentity(ident);
6534 private int getCredentialOwner(int userHandle, boolean parent) {
6535 final long ident = mInjector.binderClearCallingIdentity();
6538 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6539 if (parentProfile != null) {
6540 userHandle = parentProfile.id;
6543 return mUserManager.getCredentialOwnerProfile(userHandle);
6545 mInjector.binderRestoreCallingIdentity(ident);
6549 private boolean isManagedProfile(int userHandle) {
6550 return getUserInfo(userHandle).isManagedProfile();
6553 private void enableIfNecessary(String packageName, int userId) {
6555 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6556 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6558 if (ai.enabledSetting
6559 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6560 mIPackageManager.setApplicationEnabledSetting(packageName,
6561 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6562 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6564 } catch (RemoteException e) {
6569 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6570 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6571 != PackageManager.PERMISSION_GRANTED) {
6573 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6574 + mInjector.binderGetCallingPid()
6575 + ", uid=" + mInjector.binderGetCallingUid());
6579 synchronized (this) {
6580 pw.println("Current Device Policy Manager state:");
6581 mOwners.dump(" ", pw);
6582 int userCount = mUserData.size();
6583 for (int u = 0; u < userCount; u++) {
6584 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6586 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6587 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6588 final int N = policy.mAdminList.size();
6589 for (int i=0; i<N; i++) {
6590 ActiveAdmin ap = policy.mAdminList.get(i);
6592 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6597 if (!policy.mRemovingAdmins.isEmpty()) {
6598 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6599 + policy.mRemovingAdmins);
6603 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6606 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6610 private String getEncryptionStatusName(int encryptionStatus) {
6611 switch (encryptionStatus) {
6612 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6614 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6615 return "block default key";
6616 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6618 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6620 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6621 return "unsupported";
6622 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6623 return "activating";
6630 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6631 ComponentName activity) {
6632 Preconditions.checkNotNull(who, "ComponentName is null");
6633 final int userHandle = UserHandle.getCallingUserId();
6634 synchronized (this) {
6635 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6637 long id = mInjector.binderClearCallingIdentity();
6639 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6640 } catch (RemoteException re) {
6643 mInjector.binderRestoreCallingIdentity(id);
6649 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6650 Preconditions.checkNotNull(who, "ComponentName is null");
6651 final int userHandle = UserHandle.getCallingUserId();
6652 synchronized (this) {
6653 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6655 long id = mInjector.binderClearCallingIdentity();
6657 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6658 } catch (RemoteException re) {
6661 mInjector.binderRestoreCallingIdentity(id);
6667 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6668 String packageName) {
6669 Preconditions.checkNotNull(admin, "ComponentName is null");
6671 final int userHandle = mInjector.userHandleGetCallingUserId();
6672 synchronized (this) {
6673 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6674 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6677 DevicePolicyData policy = getUserData(userHandle);
6678 policy.mApplicationRestrictionsManagingPackage = packageName;
6679 saveSettingsLocked(userHandle);
6685 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6686 Preconditions.checkNotNull(admin, "ComponentName is null");
6688 final int userHandle = mInjector.userHandleGetCallingUserId();
6689 synchronized (this) {
6690 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6691 DevicePolicyData policy = getUserData(userHandle);
6692 return policy.mApplicationRestrictionsManagingPackage;
6697 public boolean isCallerApplicationRestrictionsManagingPackage() {
6698 final int callingUid = mInjector.binderGetCallingUid();
6699 final int userHandle = UserHandle.getUserId(callingUid);
6700 synchronized (this) {
6701 final DevicePolicyData policy = getUserData(userHandle);
6702 if (policy.mApplicationRestrictionsManagingPackage == null) {
6707 int uid = mContext.getPackageManager().getPackageUidAsUser(
6708 policy.mApplicationRestrictionsManagingPackage, userHandle);
6709 return uid == callingUid;
6710 } catch (NameNotFoundException e) {
6716 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6718 synchronized (this) {
6719 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6721 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6722 throw new SecurityException(
6723 "No admin component given, and caller cannot manage application restrictions "
6724 + "for other apps.");
6729 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6730 enforceCanManageApplicationRestrictions(who);
6732 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6733 final long id = mInjector.binderClearCallingIdentity();
6735 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6737 mInjector.binderRestoreCallingIdentity(id);
6742 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6743 PersistableBundle args, boolean parent) {
6747 Preconditions.checkNotNull(admin, "admin is null");
6748 Preconditions.checkNotNull(agent, "agent is null");
6749 final int userHandle = UserHandle.getCallingUserId();
6750 synchronized (this) {
6751 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6752 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6753 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6754 saveSettingsLocked(userHandle);
6759 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6760 ComponentName agent, int userHandle, boolean parent) {
6764 Preconditions.checkNotNull(agent, "agent null");
6765 enforceFullCrossUsersPermission(userHandle);
6767 synchronized (this) {
6768 final String componentName = agent.flattenToString();
6769 if (admin != null) {
6770 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6771 if (ap == null) return null;
6772 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6773 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6774 List<PersistableBundle> result = new ArrayList<>();
6775 result.add(trustAgentInfo.options);
6779 // Return strictest policy for this user and profiles that are visible from this user.
6780 List<PersistableBundle> result = null;
6781 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6782 // of the options. If any admin doesn't have options, discard options for the rest
6784 List<ActiveAdmin> admins =
6785 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6786 boolean allAdminsHaveOptions = true;
6787 final int N = admins.size();
6788 for (int i = 0; i < N; i++) {
6789 final ActiveAdmin active = admins.get(i);
6791 final boolean disablesTrust = (active.disabledKeyguardFeatures
6792 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6793 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6794 if (info != null && info.options != null && !info.options.isEmpty()) {
6795 if (disablesTrust) {
6796 if (result == null) {
6797 result = new ArrayList<>();
6799 result.add(info.options);
6801 Log.w(LOG_TAG, "Ignoring admin " + active.info
6802 + " because it has trust options but doesn't declare "
6803 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6805 } else if (disablesTrust) {
6806 allAdminsHaveOptions = false;
6810 return allAdminsHaveOptions ? result : null;
6815 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6816 Preconditions.checkNotNull(who, "ComponentName is null");
6817 synchronized (this) {
6818 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6820 int userHandle = UserHandle.getCallingUserId();
6821 DevicePolicyData userData = getUserData(userHandle);
6822 userData.mRestrictionsProvider = permissionProvider;
6823 saveSettingsLocked(userHandle);
6828 public ComponentName getRestrictionsProvider(int userHandle) {
6829 synchronized (this) {
6830 if (!isCallerWithSystemUid()) {
6831 throw new SecurityException("Only the system can query the permission provider");
6833 DevicePolicyData userData = getUserData(userHandle);
6834 return userData != null ? userData.mRestrictionsProvider : null;
6839 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6840 Preconditions.checkNotNull(who, "ComponentName is null");
6841 int callingUserId = UserHandle.getCallingUserId();
6842 synchronized (this) {
6843 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6845 long id = mInjector.binderClearCallingIdentity();
6847 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6848 if (parent == null) {
6849 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6853 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6854 mIPackageManager.addCrossProfileIntentFilter(
6855 filter, who.getPackageName(), callingUserId, parent.id, 0);
6857 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6858 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6859 parent.id, callingUserId, 0);
6861 } catch (RemoteException re) {
6864 mInjector.binderRestoreCallingIdentity(id);
6870 public void clearCrossProfileIntentFilters(ComponentName who) {
6871 Preconditions.checkNotNull(who, "ComponentName is null");
6872 int callingUserId = UserHandle.getCallingUserId();
6873 synchronized (this) {
6874 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6875 long id = mInjector.binderClearCallingIdentity();
6877 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6878 if (parent == null) {
6879 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6883 // Removing those that go from the managed profile to the parent.
6884 mIPackageManager.clearCrossProfileIntentFilters(
6885 callingUserId, who.getPackageName());
6886 // And those that go from the parent to the managed profile.
6887 // If we want to support multiple managed profiles, we will have to only remove
6888 // those that have callingUserId as their target.
6889 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6890 } catch (RemoteException re) {
6893 mInjector.binderRestoreCallingIdentity(id);
6899 * @return true if all packages in enabledPackages are either in the list
6900 * permittedList or are a system app.
6902 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6903 List<String> permittedList, int userIdToCheck) {
6904 long id = mInjector.binderClearCallingIdentity();
6906 // If we have an enabled packages list for a managed profile the packages
6907 // we should check are installed for the parent user.
6908 UserInfo user = getUserInfo(userIdToCheck);
6909 if (user.isManagedProfile()) {
6910 userIdToCheck = user.profileGroupId;
6913 for (String enabledPackage : enabledPackages) {
6914 boolean systemService = false;
6916 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
6917 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
6918 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6919 } catch (RemoteException e) {
6920 Log.i(LOG_TAG, "Can't talk to package managed", e);
6922 if (!systemService && !permittedList.contains(enabledPackage)) {
6927 mInjector.binderRestoreCallingIdentity(id);
6932 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
6933 // Not using AccessibilityManager.getInstance because that guesses
6934 // at the user you require based on callingUid and caches for a given
6936 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
6937 IAccessibilityManager service = iBinder == null
6938 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
6939 return new AccessibilityManager(mContext, service, userId);
6943 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
6947 Preconditions.checkNotNull(who, "ComponentName is null");
6949 if (packageList != null) {
6950 int userId = UserHandle.getCallingUserId();
6951 List<AccessibilityServiceInfo> enabledServices = null;
6952 long id = mInjector.binderClearCallingIdentity();
6954 UserInfo user = getUserInfo(userId);
6955 if (user.isManagedProfile()) {
6956 userId = user.profileGroupId;
6958 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
6959 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
6960 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
6962 mInjector.binderRestoreCallingIdentity(id);
6965 if (enabledServices != null) {
6966 List<String> enabledPackages = new ArrayList<String>();
6967 for (AccessibilityServiceInfo service : enabledServices) {
6968 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
6970 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6972 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
6973 + "because it contains already enabled accesibility services.");
6979 synchronized (this) {
6980 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6981 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6982 admin.permittedAccessiblityServices = packageList;
6983 saveSettingsLocked(UserHandle.getCallingUserId());
6989 public List getPermittedAccessibilityServices(ComponentName who) {
6993 Preconditions.checkNotNull(who, "ComponentName is null");
6995 synchronized (this) {
6996 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6997 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6998 return admin.permittedAccessiblityServices;
7003 public List getPermittedAccessibilityServicesForUser(int userId) {
7007 synchronized (this) {
7008 List<String> result = null;
7009 // If we have multiple profiles we return the intersection of the
7010 // permitted lists. This can happen in cases where we have a device
7011 // and profile owner.
7012 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7013 for (int profileId : profileIds) {
7014 // Just loop though all admins, only device or profiles
7015 // owners can have permitted lists set.
7016 DevicePolicyData policy = getUserDataUnchecked(profileId);
7017 final int N = policy.mAdminList.size();
7018 for (int j = 0; j < N; j++) {
7019 ActiveAdmin admin = policy.mAdminList.get(j);
7020 List<String> fromAdmin = admin.permittedAccessiblityServices;
7021 if (fromAdmin != null) {
7022 if (result == null) {
7023 result = new ArrayList<>(fromAdmin);
7025 result.retainAll(fromAdmin);
7031 // If we have a permitted list add all system accessibility services.
7032 if (result != null) {
7033 long id = mInjector.binderClearCallingIdentity();
7035 UserInfo user = getUserInfo(userId);
7036 if (user.isManagedProfile()) {
7037 userId = user.profileGroupId;
7039 AccessibilityManager accessibilityManager =
7040 getAccessibilityManagerForUser(userId);
7041 List<AccessibilityServiceInfo> installedServices =
7042 accessibilityManager.getInstalledAccessibilityServiceList();
7044 if (installedServices != null) {
7045 for (AccessibilityServiceInfo service : installedServices) {
7046 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7047 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7048 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7049 result.add(serviceInfo.packageName);
7054 mInjector.binderRestoreCallingIdentity(id);
7063 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7068 Preconditions.checkNotNull(who, "ComponentName is null");
7069 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7070 if (!isCallerWithSystemUid()){
7071 throw new SecurityException(
7072 "Only the system can query if an accessibility service is disabled by admin");
7074 synchronized (this) {
7075 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7076 if (admin == null) {
7079 if (admin.permittedAccessiblityServices == null) {
7082 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7083 admin.permittedAccessiblityServices, userHandle);
7087 private boolean checkCallerIsCurrentUserOrProfile() {
7088 int callingUserId = UserHandle.getCallingUserId();
7089 long token = mInjector.binderClearCallingIdentity();
7091 UserInfo currentUser;
7092 UserInfo callingUser = getUserInfo(callingUserId);
7094 currentUser = mInjector.getIActivityManager().getCurrentUser();
7095 } catch (RemoteException e) {
7096 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7100 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7101 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7102 + "of a user that isn't the foreground user.");
7105 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7106 Slog.e(LOG_TAG, "Cannot set permitted input methods "
7107 + "of a user that isn't the foreground user.");
7111 mInjector.binderRestoreCallingIdentity(token);
7117 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7121 Preconditions.checkNotNull(who, "ComponentName is null");
7123 // TODO When InputMethodManager supports per user calls remove
7124 // this restriction.
7125 if (!checkCallerIsCurrentUserOrProfile()) {
7129 if (packageList != null) {
7130 // InputMethodManager fetches input methods for current user.
7131 // So this can only be set when calling user is the current user
7132 // or parent is current user in case of managed profiles.
7133 InputMethodManager inputMethodManager =
7134 mContext.getSystemService(InputMethodManager.class);
7135 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7137 if (enabledImes != null) {
7138 List<String> enabledPackages = new ArrayList<String>();
7139 for (InputMethodInfo ime : enabledImes) {
7140 enabledPackages.add(ime.getPackageName());
7142 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7143 mInjector.binderGetCallingUserHandle().getIdentifier())) {
7144 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7145 + "because it contains already enabled input method.");
7151 synchronized (this) {
7152 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7153 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7154 admin.permittedInputMethods = packageList;
7155 saveSettingsLocked(UserHandle.getCallingUserId());
7161 public List getPermittedInputMethods(ComponentName who) {
7165 Preconditions.checkNotNull(who, "ComponentName is null");
7167 synchronized (this) {
7168 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7169 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7170 return admin.permittedInputMethods;
7175 public List getPermittedInputMethodsForCurrentUser() {
7176 UserInfo currentUser;
7178 currentUser = mInjector.getIActivityManager().getCurrentUser();
7179 } catch (RemoteException e) {
7180 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7181 // Activity managed is dead, just allow all IMEs
7185 int userId = currentUser.id;
7186 synchronized (this) {
7187 List<String> result = null;
7188 // If we have multiple profiles we return the intersection of the
7189 // permitted lists. This can happen in cases where we have a device
7190 // and profile owner.
7191 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7192 for (int profileId : profileIds) {
7193 // Just loop though all admins, only device or profiles
7194 // owners can have permitted lists set.
7195 DevicePolicyData policy = getUserDataUnchecked(profileId);
7196 final int N = policy.mAdminList.size();
7197 for (int j = 0; j < N; j++) {
7198 ActiveAdmin admin = policy.mAdminList.get(j);
7199 List<String> fromAdmin = admin.permittedInputMethods;
7200 if (fromAdmin != null) {
7201 if (result == null) {
7202 result = new ArrayList<String>(fromAdmin);
7204 result.retainAll(fromAdmin);
7210 // If we have a permitted list add all system input methods.
7211 if (result != null) {
7212 InputMethodManager inputMethodManager =
7213 mContext.getSystemService(InputMethodManager.class);
7214 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7215 long id = mInjector.binderClearCallingIdentity();
7218 for (InputMethodInfo ime : imes) {
7219 ServiceInfo serviceInfo = ime.getServiceInfo();
7220 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7221 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7222 result.add(serviceInfo.packageName);
7227 mInjector.binderRestoreCallingIdentity(id);
7235 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7240 Preconditions.checkNotNull(who, "ComponentName is null");
7241 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7242 if (!isCallerWithSystemUid()) {
7243 throw new SecurityException(
7244 "Only the system can query if an input method is disabled by admin");
7246 synchronized (this) {
7247 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7248 if (admin == null) {
7251 if (admin.permittedInputMethods == null) {
7254 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7255 admin.permittedInputMethods, userHandle);
7259 private void sendAdminEnabledBroadcastLocked(int userHandle) {
7260 DevicePolicyData policyData = getUserData(userHandle);
7261 if (policyData.mAdminBroadcastPending) {
7262 // Send the initialization data to profile owner and delete the data
7263 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7264 if (admin != null) {
7265 PersistableBundle initBundle = policyData.mInitBundle;
7266 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7267 initBundle == null ? null : new Bundle(initBundle), null);
7269 policyData.mInitBundle = null;
7270 policyData.mAdminBroadcastPending = false;
7271 saveSettingsLocked(userHandle);
7276 public UserHandle createAndManageUser(ComponentName admin, String name,
7277 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7278 Preconditions.checkNotNull(admin, "admin is null");
7279 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7280 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7281 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7282 + admin + " are not in the same package");
7284 // Only allow the system user to use this method
7285 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7286 throw new SecurityException("createAndManageUser was called from non-system user");
7288 if (!mInjector.userManagerIsSplitSystemUser()
7289 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7290 throw new IllegalArgumentException(
7291 "Ephemeral users are only supported on systems with a split system user.");
7294 UserHandle user = null;
7295 synchronized (this) {
7296 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7298 final long id = mInjector.binderClearCallingIdentity();
7300 int userInfoFlags = 0;
7301 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7302 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7304 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7306 if (userInfo != null) {
7307 user = userInfo.getUserHandle();
7310 mInjector.binderRestoreCallingIdentity(id);
7317 final long id = mInjector.binderClearCallingIdentity();
7319 final String adminPkg = admin.getPackageName();
7321 final int userHandle = user.getIdentifier();
7323 // Install the profile owner if not present.
7324 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7325 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7327 } catch (RemoteException e) {
7328 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7329 + "removing created user", e);
7330 mUserManager.removeUser(user.getIdentifier());
7334 setActiveAdmin(profileOwner, true, userHandle);
7335 // User is not started yet, the broadcast by setActiveAdmin will not be received.
7336 // So we store adminExtras for broadcasting when the user starts for first time.
7337 synchronized(this) {
7338 DevicePolicyData policyData = getUserData(userHandle);
7339 policyData.mInitBundle = adminExtras;
7340 policyData.mAdminBroadcastPending = true;
7341 saveSettingsLocked(userHandle);
7343 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7344 setProfileOwner(profileOwner, ownerName, userHandle);
7346 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7347 Settings.Secure.putIntForUser(mContext.getContentResolver(),
7348 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7353 mInjector.binderRestoreCallingIdentity(id);
7358 public boolean removeUser(ComponentName who, UserHandle userHandle) {
7359 Preconditions.checkNotNull(who, "ComponentName is null");
7360 synchronized (this) {
7361 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7363 long id = mInjector.binderClearCallingIdentity();
7365 return mUserManager.removeUser(userHandle.getIdentifier());
7367 mInjector.binderRestoreCallingIdentity(id);
7373 public boolean switchUser(ComponentName who, UserHandle userHandle) {
7374 Preconditions.checkNotNull(who, "ComponentName is null");
7375 synchronized (this) {
7376 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7378 long id = mInjector.binderClearCallingIdentity();
7380 int userId = UserHandle.USER_SYSTEM;
7381 if (userHandle != null) {
7382 userId = userHandle.getIdentifier();
7384 return mInjector.getIActivityManager().switchUser(userId);
7385 } catch (RemoteException e) {
7386 Log.e(LOG_TAG, "Couldn't switch user", e);
7389 mInjector.binderRestoreCallingIdentity(id);
7395 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7396 enforceCanManageApplicationRestrictions(who);
7398 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7399 final long id = mInjector.binderClearCallingIdentity();
7401 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7402 // if no restrictions were saved, mUserManager.getApplicationRestrictions
7403 // returns null, but DPM method should return an empty Bundle as per JavaDoc
7404 return bundle != null ? bundle : Bundle.EMPTY;
7406 mInjector.binderRestoreCallingIdentity(id);
7411 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7412 boolean suspended) {
7413 Preconditions.checkNotNull(who, "ComponentName is null");
7414 int callingUserId = UserHandle.getCallingUserId();
7415 synchronized (this) {
7416 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7418 long id = mInjector.binderClearCallingIdentity();
7420 return mIPackageManager.setPackagesSuspendedAsUser(
7421 packageNames, suspended, callingUserId);
7422 } catch (RemoteException re) {
7423 // Shouldn't happen.
7424 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7426 mInjector.binderRestoreCallingIdentity(id);
7428 return packageNames;
7433 public boolean isPackageSuspended(ComponentName who, String packageName) {
7434 Preconditions.checkNotNull(who, "ComponentName is null");
7435 int callingUserId = UserHandle.getCallingUserId();
7436 synchronized (this) {
7437 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7439 long id = mInjector.binderClearCallingIdentity();
7441 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7442 } catch (RemoteException re) {
7443 // Shouldn't happen.
7444 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7446 mInjector.binderRestoreCallingIdentity(id);
7453 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7454 Preconditions.checkNotNull(who, "ComponentName is null");
7455 if (!UserRestrictionsUtils.isValidRestriction(key)) {
7459 final int userHandle = mInjector.userHandleGetCallingUserId();
7460 synchronized (this) {
7461 ActiveAdmin activeAdmin =
7462 getActiveAdminForCallerLocked(who,
7463 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7464 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7465 if (isDeviceOwner) {
7466 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7467 throw new SecurityException("Device owner cannot set user restriction " + key);
7469 } else { // profile owner
7470 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7471 throw new SecurityException("Profile owner cannot set user restriction " + key);
7475 // Save the restriction to ActiveAdmin.
7476 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7477 saveSettingsLocked(userHandle);
7479 pushUserRestrictions(userHandle);
7481 sendChangedNotification(userHandle);
7485 private void pushUserRestrictions(int userId) {
7486 synchronized (this) {
7487 final Bundle global;
7488 final Bundle local = new Bundle();
7489 if (mOwners.isDeviceOwnerUserId(userId)) {
7490 global = new Bundle();
7492 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7493 if (deviceOwner == null) {
7494 return; // Shouldn't happen.
7497 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7499 // DO can disable camera globally.
7500 if (deviceOwner.disableCamera) {
7501 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7506 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7507 if (profileOwner != null) {
7508 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7511 // Also merge in *local* camera restriction.
7512 if (getCameraDisabled(/* who= */ null,
7513 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7514 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7516 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7521 public Bundle getUserRestrictions(ComponentName who) {
7525 Preconditions.checkNotNull(who, "ComponentName is null");
7526 synchronized (this) {
7527 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7528 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7529 return activeAdmin.userRestrictions;
7534 public boolean setApplicationHidden(ComponentName who, String packageName,
7536 Preconditions.checkNotNull(who, "ComponentName is null");
7537 int callingUserId = UserHandle.getCallingUserId();
7538 synchronized (this) {
7539 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7541 long id = mInjector.binderClearCallingIdentity();
7543 return mIPackageManager.setApplicationHiddenSettingAsUser(
7544 packageName, hidden, callingUserId);
7545 } catch (RemoteException re) {
7547 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7549 mInjector.binderRestoreCallingIdentity(id);
7556 public boolean isApplicationHidden(ComponentName who, String packageName) {
7557 Preconditions.checkNotNull(who, "ComponentName is null");
7558 int callingUserId = UserHandle.getCallingUserId();
7559 synchronized (this) {
7560 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7562 long id = mInjector.binderClearCallingIdentity();
7564 return mIPackageManager.getApplicationHiddenSettingAsUser(
7565 packageName, callingUserId);
7566 } catch (RemoteException re) {
7568 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7570 mInjector.binderRestoreCallingIdentity(id);
7577 public void enableSystemApp(ComponentName who, String packageName) {
7578 Preconditions.checkNotNull(who, "ComponentName is null");
7579 synchronized (this) {
7580 // This API can only be called by an active device admin,
7581 // so try to retrieve it to check that the caller is one.
7582 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7584 int userId = UserHandle.getCallingUserId();
7585 long id = mInjector.binderClearCallingIdentity();
7589 Slog.v(LOG_TAG, "installing " + packageName + " for "
7593 int parentUserId = getProfileParentId(userId);
7594 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7595 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7599 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7601 } catch (RemoteException re) {
7603 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7605 mInjector.binderRestoreCallingIdentity(id);
7611 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7612 Preconditions.checkNotNull(who, "ComponentName is null");
7613 synchronized (this) {
7614 // This API can only be called by an active device admin,
7615 // so try to retrieve it to check that the caller is one.
7616 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7618 int userId = UserHandle.getCallingUserId();
7619 long id = mInjector.binderClearCallingIdentity();
7622 int parentUserId = getProfileParentId(userId);
7623 List<ResolveInfo> activitiesToEnable = mIPackageManager
7624 .queryIntentActivities(intent,
7625 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7626 PackageManager.MATCH_DIRECT_BOOT_AWARE
7627 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7632 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7634 int numberOfAppsInstalled = 0;
7635 if (activitiesToEnable != null) {
7636 for (ResolveInfo info : activitiesToEnable) {
7637 if (info.activityInfo != null) {
7638 String packageName = info.activityInfo.packageName;
7639 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7640 numberOfAppsInstalled++;
7641 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7643 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7649 return numberOfAppsInstalled;
7650 } catch (RemoteException e) {
7652 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7655 mInjector.binderRestoreCallingIdentity(id);
7660 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7661 throws RemoteException {
7662 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7664 if (appInfo == null) {
7665 throw new IllegalArgumentException("The application " + packageName +
7666 " is not present on this device");
7668 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7672 public void setAccountManagementDisabled(ComponentName who, String accountType,
7677 Preconditions.checkNotNull(who, "ComponentName is null");
7678 synchronized (this) {
7679 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7680 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7682 ap.accountTypesWithManagementDisabled.add(accountType);
7684 ap.accountTypesWithManagementDisabled.remove(accountType);
7686 saveSettingsLocked(UserHandle.getCallingUserId());
7691 public String[] getAccountTypesWithManagementDisabled() {
7692 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7696 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7697 enforceFullCrossUsersPermission(userId);
7701 synchronized (this) {
7702 DevicePolicyData policy = getUserData(userId);
7703 final int N = policy.mAdminList.size();
7704 ArraySet<String> resultSet = new ArraySet<>();
7705 for (int i = 0; i < N; i++) {
7706 ActiveAdmin admin = policy.mAdminList.get(i);
7707 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7709 return resultSet.toArray(new String[resultSet.size()]);
7714 public void setUninstallBlocked(ComponentName who, String packageName,
7715 boolean uninstallBlocked) {
7716 Preconditions.checkNotNull(who, "ComponentName is null");
7717 final int userId = UserHandle.getCallingUserId();
7718 synchronized (this) {
7719 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7721 long id = mInjector.binderClearCallingIdentity();
7723 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7724 } catch (RemoteException re) {
7725 // Shouldn't happen.
7726 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7728 mInjector.binderRestoreCallingIdentity(id);
7734 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7735 // This function should return true if and only if the package is blocked by
7736 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7737 // when the package is a system app, or when it is an active device admin.
7738 final int userId = UserHandle.getCallingUserId();
7740 synchronized (this) {
7742 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7745 long id = mInjector.binderClearCallingIdentity();
7747 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7748 } catch (RemoteException re) {
7749 // Shouldn't happen.
7750 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7752 mInjector.binderRestoreCallingIdentity(id);
7759 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7763 Preconditions.checkNotNull(who, "ComponentName is null");
7764 synchronized (this) {
7765 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7766 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7767 if (admin.disableCallerId != disabled) {
7768 admin.disableCallerId = disabled;
7769 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7775 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7779 Preconditions.checkNotNull(who, "ComponentName is null");
7780 synchronized (this) {
7781 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7782 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7783 return admin.disableCallerId;
7788 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7789 enforceCrossUsersPermission(userId);
7790 synchronized (this) {
7791 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7792 return (admin != null) ? admin.disableCallerId : false;
7797 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7801 Preconditions.checkNotNull(who, "ComponentName is null");
7802 synchronized (this) {
7803 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7804 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7805 if (admin.disableContactsSearch != disabled) {
7806 admin.disableContactsSearch = disabled;
7807 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7813 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7817 Preconditions.checkNotNull(who, "ComponentName is null");
7818 synchronized (this) {
7819 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7820 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7821 return admin.disableContactsSearch;
7826 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7827 enforceCrossUsersPermission(userId);
7828 synchronized (this) {
7829 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7830 return (admin != null) ? admin.disableContactsSearch : false;
7835 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7836 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7837 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7838 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7839 final int callingUserId = UserHandle.getCallingUserId();
7841 final long ident = mInjector.binderClearCallingIdentity();
7843 synchronized (this) {
7844 final int managedUserId = getManagedUserId(callingUserId);
7845 if (managedUserId < 0) {
7848 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7851 "Cross-profile contacts access disabled for user " + managedUserId);
7855 ContactsInternal.startQuickContactWithErrorToastForUser(
7856 mContext, intent, new UserHandle(managedUserId));
7859 mInjector.binderRestoreCallingIdentity(ident);
7864 * @return true if cross-profile QuickContact is disabled
7866 private boolean isCrossProfileQuickContactDisabled(int userId) {
7867 return getCrossProfileCallerIdDisabledForUser(userId)
7868 && getCrossProfileContactsSearchDisabledForUser(userId);
7872 * @return the user ID of the managed user that is linked to the current user, if any.
7875 public int getManagedUserId(int callingUserId) {
7877 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7880 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7881 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7882 continue; // Caller user self, or not a managed profile. Skip.
7885 Log.v(LOG_TAG, "Managed user=" + ui.id);
7890 Log.v(LOG_TAG, "Managed user not found.");
7896 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7900 Preconditions.checkNotNull(who, "ComponentName is null");
7901 synchronized (this) {
7902 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7903 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7904 if (admin.disableBluetoothContactSharing != disabled) {
7905 admin.disableBluetoothContactSharing = disabled;
7906 saveSettingsLocked(UserHandle.getCallingUserId());
7912 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
7916 Preconditions.checkNotNull(who, "ComponentName is null");
7917 synchronized (this) {
7918 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7919 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7920 return admin.disableBluetoothContactSharing;
7925 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
7926 // TODO: Should there be a check to make sure this relationship is
7927 // within a profile group?
7928 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
7929 synchronized (this) {
7930 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7931 return (admin != null) ? admin.disableBluetoothContactSharing : false;
7936 * Sets which packages may enter lock task mode.
7938 * <p>This function can only be called by the device owner or alternatively by the profile owner
7939 * in case the user is affiliated.
7941 * @param packages The list of packages allowed to enter lock task mode.
7944 public void setLockTaskPackages(ComponentName who, String[] packages)
7945 throws SecurityException {
7946 Preconditions.checkNotNull(who, "ComponentName is null");
7947 synchronized (this) {
7948 ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
7949 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
7950 ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
7951 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
7952 if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
7953 int userHandle = mInjector.userHandleGetCallingUserId();
7954 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
7956 throw new SecurityException("Admin " + who +
7957 " is neither the device owner or affiliated user's profile owner.");
7962 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
7963 DevicePolicyData policy = getUserData(userHandle);
7964 policy.mLockTaskPackages = packages;
7966 // Store the settings persistently.
7967 saveSettingsLocked(userHandle);
7968 updateLockTaskPackagesLocked(packages, userHandle);
7972 * This function returns the list of components allowed to start the task lock mode.
7975 public String[] getLockTaskPackages(ComponentName who) {
7976 Preconditions.checkNotNull(who, "ComponentName is null");
7977 synchronized (this) {
7978 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7979 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
7980 final List<String> packages = getLockTaskPackagesLocked(userHandle);
7981 return packages.toArray(new String[packages.size()]);
7985 private List<String> getLockTaskPackagesLocked(int userHandle) {
7986 final DevicePolicyData policy = getUserData(userHandle);
7987 return policy.mLockTaskPackages;
7991 * This function lets the caller know whether the given package is allowed to start the
7993 * @param pkg The package to check
7996 public boolean isLockTaskPermitted(String pkg) {
7997 // Get current user's devicepolicy
7998 int uid = mInjector.binderGetCallingUid();
7999 int userHandle = UserHandle.getUserId(uid);
8000 DevicePolicyData policy = getUserData(userHandle);
8001 synchronized (this) {
8002 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
8003 String lockTaskPackage = policy.mLockTaskPackages.get(i);
8005 // If the given package equals one of the packages stored our list,
8006 // we allow this package to start lock task mode.
8007 if (lockTaskPackage.equals(pkg)) {
8016 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
8017 if (!isCallerWithSystemUid()) {
8018 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
8020 synchronized (this) {
8021 final DevicePolicyData policy = getUserData(userHandle);
8022 Bundle adminExtras = new Bundle();
8023 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
8024 for (ActiveAdmin admin : policy.mAdminList) {
8025 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
8026 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
8027 if (ownsDevice || ownsProfile) {
8029 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
8032 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
8040 public void setGlobalSetting(ComponentName who, String setting, String value) {
8041 Preconditions.checkNotNull(who, "ComponentName is null");
8043 synchronized (this) {
8044 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8046 // Some settings are no supported any more. However we do not want to throw a
8047 // SecurityException to avoid breaking apps.
8048 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
8049 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
8053 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
8054 throw new SecurityException(String.format(
8055 "Permission denial: device owners cannot update %1$s", setting));
8058 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
8059 // ignore if it contradicts an existing policy
8060 long timeMs = getMaximumTimeToLock(
8061 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
8062 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
8067 long id = mInjector.binderClearCallingIdentity();
8069 mInjector.settingsGlobalPutString(setting, value);
8071 mInjector.binderRestoreCallingIdentity(id);
8077 public void setSecureSetting(ComponentName who, String setting, String value) {
8078 Preconditions.checkNotNull(who, "ComponentName is null");
8079 int callingUserId = mInjector.userHandleGetCallingUserId();
8081 synchronized (this) {
8082 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8084 if (isDeviceOwner(who, callingUserId)) {
8085 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
8086 throw new SecurityException(String.format(
8087 "Permission denial: Device owners cannot update %1$s", setting));
8089 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
8090 throw new SecurityException(String.format(
8091 "Permission denial: Profile owners cannot update %1$s", setting));
8094 long id = mInjector.binderClearCallingIdentity();
8096 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
8098 mInjector.binderRestoreCallingIdentity(id);
8104 public void setMasterVolumeMuted(ComponentName who, boolean on) {
8105 Preconditions.checkNotNull(who, "ComponentName is null");
8106 synchronized (this) {
8107 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8108 setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
8113 public boolean isMasterVolumeMuted(ComponentName who) {
8114 Preconditions.checkNotNull(who, "ComponentName is null");
8115 synchronized (this) {
8116 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8118 AudioManager audioManager =
8119 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
8120 return audioManager.isMasterMute();
8125 public void setUserIcon(ComponentName who, Bitmap icon) {
8126 synchronized (this) {
8127 Preconditions.checkNotNull(who, "ComponentName is null");
8128 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8130 int userId = UserHandle.getCallingUserId();
8131 long id = mInjector.binderClearCallingIdentity();
8133 mUserManagerInternal.setUserIcon(userId, icon);
8135 mInjector.binderRestoreCallingIdentity(id);
8141 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8142 Preconditions.checkNotNull(who, "ComponentName is null");
8143 synchronized (this) {
8144 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8146 final int userId = UserHandle.getCallingUserId();
8148 long ident = mInjector.binderClearCallingIdentity();
8150 // disallow disabling the keyguard if a password is currently set
8151 if (disabled && mLockPatternUtils.isSecure(userId)) {
8154 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8156 mInjector.binderRestoreCallingIdentity(ident);
8162 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8163 int userId = UserHandle.getCallingUserId();
8164 synchronized (this) {
8165 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8166 DevicePolicyData policy = getUserData(userId);
8167 if (policy.mStatusBarDisabled != disabled) {
8168 if (!setStatusBarDisabledInternal(disabled, userId)) {
8171 policy.mStatusBarDisabled = disabled;
8172 saveSettingsLocked(userId);
8178 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8179 long ident = mInjector.binderClearCallingIdentity();
8181 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8182 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8183 if (statusBarService != null) {
8184 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8185 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8186 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8187 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8190 } catch (RemoteException e) {
8191 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8193 mInjector.binderRestoreCallingIdentity(ident);
8199 * We need to update the internal state of whether a user has completed setup once. After
8200 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
8201 * as we don't trust any apps that might try to reset it.
8203 * Unfortunately, we don't know which user's setup state was changed, so we write all of
8206 void updateUserSetupComplete() {
8207 List<UserInfo> users = mUserManager.getUsers(true);
8208 final int N = users.size();
8209 for (int i = 0; i < N; i++) {
8210 int userHandle = users.get(i).id;
8211 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8213 DevicePolicyData policy = getUserData(userHandle);
8214 if (!policy.mUserSetupComplete) {
8215 policy.mUserSetupComplete = true;
8216 synchronized (this) {
8217 saveSettingsLocked(userHandle);
8224 private class SetupContentObserver extends ContentObserver {
8226 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8227 Settings.Secure.USER_SETUP_COMPLETE);
8228 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8229 Settings.Global.DEVICE_PROVISIONED);
8231 public SetupContentObserver(Handler handler) {
8236 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8237 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8241 public void onChange(boolean selfChange, Uri uri) {
8242 if (mUserSetupComplete.equals(uri)) {
8243 updateUserSetupComplete();
8244 } else if (mDeviceProvisioned.equals(uri)) {
8245 synchronized (DevicePolicyManagerService.this) {
8246 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8247 // is delayed until device is marked as provisioned.
8248 setDeviceOwnerSystemPropertyLocked();
8255 final class LocalService extends DevicePolicyManagerInternal {
8256 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8259 public List<String> getCrossProfileWidgetProviders(int profileId) {
8260 synchronized (DevicePolicyManagerService.this) {
8261 if (mOwners == null) {
8262 return Collections.emptyList();
8264 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8265 if (ownerComponent == null) {
8266 return Collections.emptyList();
8269 DevicePolicyData policy = getUserDataUnchecked(profileId);
8270 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8272 if (admin == null || admin.crossProfileWidgetProviders == null
8273 || admin.crossProfileWidgetProviders.isEmpty()) {
8274 return Collections.emptyList();
8277 return admin.crossProfileWidgetProviders;
8282 public void addOnCrossProfileWidgetProvidersChangeListener(
8283 OnCrossProfileWidgetProvidersChangeListener listener) {
8284 synchronized (DevicePolicyManagerService.this) {
8285 if (mWidgetProviderListeners == null) {
8286 mWidgetProviderListeners = new ArrayList<>();
8288 if (!mWidgetProviderListeners.contains(listener)) {
8289 mWidgetProviderListeners.add(listener);
8295 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8296 synchronized(DevicePolicyManagerService.this) {
8297 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8301 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8302 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8303 synchronized (DevicePolicyManagerService.this) {
8304 listeners = new ArrayList<>(mWidgetProviderListeners);
8306 final int listenerCount = listeners.size();
8307 for (int i = 0; i < listenerCount; i++) {
8308 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8309 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8314 public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
8315 Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8316 intent.putExtra(Intent.EXTRA_USER_ID, userId);
8317 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8319 // This method is called from AM with its lock held, so don't take the DPMS lock.
8322 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8323 if (profileOwner != null) {
8324 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
8328 final Pair<Integer, ComponentName> deviceOwner =
8329 mOwners.getDeviceOwnerUserIdAndComponent();
8330 if (deviceOwner != null && deviceOwner.first == userId) {
8331 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
8335 // We're not specifying the device admin because there isn't one.
8341 * Returns true if specified admin is allowed to limit passwords and has a
8342 * {@code passwordQuality} of at least {@code minPasswordQuality}
8344 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8345 if (admin.passwordQuality < minPasswordQuality) {
8348 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8352 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8353 if (policy != null && !policy.isValid()) {
8354 throw new IllegalArgumentException("Invalid system update policy.");
8356 synchronized (this) {
8357 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8358 if (policy == null) {
8359 mOwners.clearSystemUpdatePolicy();
8361 mOwners.setSystemUpdatePolicy(policy);
8363 mOwners.writeDeviceOwner();
8365 mContext.sendBroadcastAsUser(
8366 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8371 public SystemUpdatePolicy getSystemUpdatePolicy() {
8372 if (UserManager.isDeviceInDemoMode(mContext)) {
8373 // Pretending to have an automatic update policy when the device is in retail demo
8374 // mode. This will allow the device to download and install an ota without
8375 // any user interaction.
8376 return SystemUpdatePolicy.createAutomaticInstallPolicy();
8378 synchronized (this) {
8379 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
8380 if (policy != null && !policy.isValid()) {
8381 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8389 * Checks if the caller of the method is the device owner app.
8391 * @param callerUid UID of the caller.
8392 * @return true if the caller is the device owner app
8395 boolean isCallerDeviceOwner(int callerUid) {
8396 synchronized (this) {
8397 if (!mOwners.hasDeviceOwner()) {
8400 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8403 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8405 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8407 for (String pkg : pkgs) {
8408 if (deviceOwnerPackageName.equals(pkg)) {
8418 public void notifyPendingSystemUpdate(long updateReceivedTime) {
8419 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8420 "Only the system update service can broadcast update information");
8422 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8423 Slog.w(LOG_TAG, "Only the system update service in the system user " +
8424 "can broadcast update information.");
8427 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8428 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8429 updateReceivedTime);
8431 synchronized (this) {
8432 final String deviceOwnerPackage =
8433 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8435 if (deviceOwnerPackage == null) {
8438 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8440 ActivityInfo[] receivers = null;
8442 receivers = mContext.getPackageManager().getPackageInfo(
8443 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8444 } catch (NameNotFoundException e) {
8445 Log.e(LOG_TAG, "Cannot find device owner package", e);
8447 if (receivers != null) {
8448 long ident = mInjector.binderClearCallingIdentity();
8450 for (int i = 0; i < receivers.length; i++) {
8451 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8452 intent.setComponent(new ComponentName(deviceOwnerPackage,
8453 receivers[i].name));
8454 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8458 mInjector.binderRestoreCallingIdentity(ident);
8465 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8466 int userId = UserHandle.getCallingUserId();
8467 synchronized (this) {
8468 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8469 DevicePolicyData userPolicy = getUserData(userId);
8470 if (userPolicy.mPermissionPolicy != policy) {
8471 userPolicy.mPermissionPolicy = policy;
8472 saveSettingsLocked(userId);
8478 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8479 int userId = UserHandle.getCallingUserId();
8480 synchronized (this) {
8481 DevicePolicyData userPolicy = getUserData(userId);
8482 return userPolicy.mPermissionPolicy;
8487 public boolean setPermissionGrantState(ComponentName admin, String packageName,
8488 String permission, int grantState) throws RemoteException {
8489 UserHandle user = mInjector.binderGetCallingUserHandle();
8490 synchronized (this) {
8491 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8492 long ident = mInjector.binderClearCallingIdentity();
8494 if (getTargetSdk(packageName, user.getIdentifier())
8495 < android.os.Build.VERSION_CODES.M) {
8498 final PackageManager packageManager = mContext.getPackageManager();
8499 switch (grantState) {
8500 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8501 packageManager.grantRuntimePermission(packageName, permission, user);
8502 packageManager.updatePermissionFlags(permission, packageName,
8503 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8504 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8507 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8508 packageManager.revokeRuntimePermission(packageName,
8510 packageManager.updatePermissionFlags(permission, packageName,
8511 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8512 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8515 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8516 packageManager.updatePermissionFlags(permission, packageName,
8517 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8521 } catch (SecurityException se) {
8524 mInjector.binderRestoreCallingIdentity(ident);
8530 public int getPermissionGrantState(ComponentName admin, String packageName,
8531 String permission) throws RemoteException {
8532 PackageManager packageManager = mContext.getPackageManager();
8534 UserHandle user = mInjector.binderGetCallingUserHandle();
8535 synchronized (this) {
8536 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8537 long ident = mInjector.binderClearCallingIdentity();
8539 int granted = mIPackageManager.checkPermission(permission,
8540 packageName, user.getIdentifier());
8541 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8542 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8543 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8544 // Not controlled by policy
8545 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8547 // Policy controlled so return result based on permission grant state
8548 return granted == PackageManager.PERMISSION_GRANTED
8549 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8550 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8553 mInjector.binderRestoreCallingIdentity(ident);
8558 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8560 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8562 return (pi != null) && (pi.applicationInfo.flags != 0);
8563 } catch (RemoteException re) {
8564 throw new RuntimeException("Package manager has died", re);
8569 public boolean isProvisioningAllowed(String action) {
8574 final int callingUserId = mInjector.userHandleGetCallingUserId();
8575 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8576 if (!hasFeatureManagedUsers()) {
8579 synchronized (this) {
8580 if (mOwners.hasDeviceOwner()) {
8581 if (!mInjector.userManagerIsSplitSystemUser()) {
8582 // Only split-system-user systems support managed-profiles in combination with
8586 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8587 // Only system device-owner supports managed-profiles. Non-system device-owner
8591 if (callingUserId == UserHandle.USER_SYSTEM) {
8592 // Managed-profiles cannot be setup on the system user, only regular users.
8597 if (getProfileOwner(callingUserId) != null) {
8598 // Managed user cannot have a managed profile.
8601 final long ident = mInjector.binderClearCallingIdentity();
8603 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8607 mInjector.binderRestoreCallingIdentity(ident);
8610 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8611 return isDeviceOwnerProvisioningAllowed(callingUserId);
8612 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8613 if (!hasFeatureManagedUsers()) {
8616 if (!mInjector.userManagerIsSplitSystemUser()) {
8617 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8620 if (callingUserId == UserHandle.USER_SYSTEM) {
8621 // System user cannot be a managed user.
8624 if (hasUserSetupCompleted(callingUserId)) {
8628 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8629 if (!mInjector.userManagerIsSplitSystemUser()) {
8630 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8633 return isDeviceOwnerProvisioningAllowed(callingUserId);
8635 throw new IllegalArgumentException("Unknown provisioning action " + action);
8639 * The device owner can only be set before the setup phase of the primary user has completed,
8640 * except for adb command if no accounts or additional users are present on the device.
8642 private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreConditionLocked(
8643 @Nullable ComponentName owner, int deviceOwnerUserId, boolean isAdb) {
8644 if (mOwners.hasDeviceOwner()) {
8645 return CODE_HAS_DEVICE_OWNER;
8647 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8648 return CODE_USER_HAS_PROFILE_OWNER;
8650 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8651 return CODE_USER_NOT_RUNNING;
8654 // if shell command runs after user setup completed check device status. Otherwise, OK.
8655 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8656 if (!mInjector.userManagerIsSplitSystemUser()) {
8657 if (mUserManager.getUserCount() > 1) {
8658 return CODE_NONSYSTEM_USER_EXISTS;
8660 if (hasIncompatibleAccountsLocked(UserHandle.USER_SYSTEM, owner)) {
8661 return CODE_ACCOUNTS_NOT_EMPTY;
8664 // STOPSHIP Do proper check in split user mode
8669 if (!mInjector.userManagerIsSplitSystemUser()) {
8670 // In non-split user mode, DO has to be user 0
8671 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8672 return CODE_NOT_SYSTEM_USER;
8674 // In non-split user mode, only provision DO before setup wizard completes
8675 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8676 return CODE_USER_SETUP_COMPLETED;
8679 // STOPSHIP Do proper check in split user mode
8685 private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8686 synchronized (this) {
8687 return CODE_OK == checkSetDeviceOwnerPreConditionLocked(
8688 /* owner unknown */ null, deviceOwnerUserId, /* isAdb */ false);
8692 private boolean hasFeatureManagedUsers() {
8694 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8695 } catch (RemoteException e) {
8701 public String getWifiMacAddress(ComponentName admin) {
8702 // Make sure caller has DO.
8703 synchronized (this) {
8704 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8707 final long ident = mInjector.binderClearCallingIdentity();
8709 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8710 if (wifiInfo == null) {
8713 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8715 mInjector.binderRestoreCallingIdentity(ident);
8720 * Returns the target sdk version number that the given packageName was built for
8721 * in the given user.
8723 private int getTargetSdk(String packageName, int userId) {
8724 final ApplicationInfo ai;
8726 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8727 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8728 return targetSdkVersion;
8729 } catch (RemoteException e) {
8736 public boolean isManagedProfile(ComponentName admin) {
8737 synchronized (this) {
8738 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8740 final int callingUserId = mInjector.userHandleGetCallingUserId();
8741 final UserInfo user = getUserInfo(callingUserId);
8742 return user != null && user.isManagedProfile();
8746 public boolean isSystemOnlyUser(ComponentName admin) {
8747 synchronized (this) {
8748 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8750 final int callingUserId = mInjector.userHandleGetCallingUserId();
8751 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8755 public void reboot(ComponentName admin) {
8756 Preconditions.checkNotNull(admin);
8757 // Make sure caller has DO.
8758 synchronized (this) {
8759 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8761 long ident = mInjector.binderClearCallingIdentity();
8763 // Make sure there are no ongoing calls on the device.
8764 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8765 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8767 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8769 mInjector.binderRestoreCallingIdentity(ident);
8774 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8778 Preconditions.checkNotNull(who, "ComponentName is null");
8779 final int userHandle = mInjector.userHandleGetCallingUserId();
8780 synchronized (this) {
8781 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8782 mInjector.binderGetCallingUid());
8783 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8784 admin.shortSupportMessage = message;
8785 saveSettingsLocked(userHandle);
8791 public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8795 Preconditions.checkNotNull(who, "ComponentName is null");
8796 synchronized (this) {
8797 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8798 mInjector.binderGetCallingUid());
8799 return admin.shortSupportMessage;
8804 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8808 Preconditions.checkNotNull(who, "ComponentName is null");
8809 final int userHandle = mInjector.userHandleGetCallingUserId();
8810 synchronized (this) {
8811 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8812 mInjector.binderGetCallingUid());
8813 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8814 admin.longSupportMessage = message;
8815 saveSettingsLocked(userHandle);
8821 public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8825 Preconditions.checkNotNull(who, "ComponentName is null");
8826 synchronized (this) {
8827 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8828 mInjector.binderGetCallingUid());
8829 return admin.longSupportMessage;
8834 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8838 Preconditions.checkNotNull(who, "ComponentName is null");
8839 if (!isCallerWithSystemUid()) {
8840 throw new SecurityException("Only the system can query support message for user");
8842 synchronized (this) {
8843 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8844 if (admin != null) {
8845 return admin.shortSupportMessage;
8852 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8856 Preconditions.checkNotNull(who, "ComponentName is null");
8857 if (!isCallerWithSystemUid()) {
8858 throw new SecurityException("Only the system can query support message for user");
8860 synchronized (this) {
8861 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8862 if (admin != null) {
8863 return admin.longSupportMessage;
8870 public void setOrganizationColor(@NonNull ComponentName who, int color) {
8874 Preconditions.checkNotNull(who, "ComponentName is null");
8875 final int userHandle = mInjector.userHandleGetCallingUserId();
8876 enforceManagedProfile(userHandle, "set organization color");
8877 synchronized (this) {
8878 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8879 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8880 admin.organizationColor = color;
8881 saveSettingsLocked(userHandle);
8886 public void setOrganizationColorForUser(int color, int userId) {
8890 enforceFullCrossUsersPermission(userId);
8891 enforceManageUsers();
8892 enforceManagedProfile(userId, "set organization color");
8893 synchronized (this) {
8894 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8895 admin.organizationColor = color;
8896 saveSettingsLocked(userId);
8901 public int getOrganizationColor(@NonNull ComponentName who) {
8903 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8905 Preconditions.checkNotNull(who, "ComponentName is null");
8906 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
8907 synchronized (this) {
8908 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8909 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8910 return admin.organizationColor;
8915 public int getOrganizationColorForUser(int userHandle) {
8917 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8919 enforceFullCrossUsersPermission(userHandle);
8920 enforceManagedProfile(userHandle, "get organization color");
8921 synchronized (this) {
8922 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8923 return (profileOwner != null)
8924 ? profileOwner.organizationColor
8925 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
8930 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
8934 Preconditions.checkNotNull(who, "ComponentName is null");
8935 final int userHandle = mInjector.userHandleGetCallingUserId();
8936 enforceManagedProfile(userHandle, "set organization name");
8937 synchronized (this) {
8938 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8939 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8940 if (!TextUtils.equals(admin.organizationName, text)) {
8941 admin.organizationName = (text == null || text.length() == 0)
8942 ? null : text.toString();
8943 saveSettingsLocked(userHandle);
8949 public CharSequence getOrganizationName(@NonNull ComponentName who) {
8953 Preconditions.checkNotNull(who, "ComponentName is null");
8954 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
8955 synchronized(this) {
8956 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8957 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8958 return admin.organizationName;
8963 public CharSequence getOrganizationNameForUser(int userHandle) {
8967 enforceFullCrossUsersPermission(userHandle);
8968 enforceManagedProfile(userHandle, "get organization name");
8969 synchronized (this) {
8970 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8971 return (profileOwner != null)
8972 ? profileOwner.organizationName
8978 public void setAffiliationIds(ComponentName admin, List<String> ids) {
8979 final Set<String> affiliationIds = new ArraySet<String>(ids);
8980 final int callingUserId = mInjector.userHandleGetCallingUserId();
8982 synchronized (this) {
8983 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8984 getUserData(callingUserId).mAffiliationIds = affiliationIds;
8985 saveSettingsLocked(callingUserId);
8986 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
8987 // Affiliation ids specified by the device owner are additionally stored in
8988 // UserHandle.USER_SYSTEM's DevicePolicyData.
8989 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
8990 saveSettingsLocked(UserHandle.USER_SYSTEM);
8996 public boolean isAffiliatedUser() {
8997 final int callingUserId = mInjector.userHandleGetCallingUserId();
8999 synchronized (this) {
9000 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
9001 // The user that the DO is installed on is always affiliated.
9004 final ComponentName profileOwner = getProfileOwner(callingUserId);
9005 if (profileOwner == null
9006 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
9009 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
9010 final Set<String> deviceAffiliationIds =
9011 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
9012 for (String id : userAffiliationIds) {
9013 if (deviceAffiliationIds.contains(id)) {
9021 private synchronized void disableDeviceOwnerManagedSingleUserFeaturesIfNeeded() {
9022 if (!isDeviceOwnerManagedSingleUserDevice()) {
9023 mInjector.securityLogSetLoggingEnabledProperty(false);
9024 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user device.");
9025 if (mOwners.hasDeviceOwner()) {
9026 setBackupServiceEnabledInternal(false);
9027 Slog.w(LOG_TAG, "Backup is off as it's a managed device that has more that one user.");
9033 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
9034 Preconditions.checkNotNull(admin);
9035 ensureDeviceOwnerManagingSingleUser(admin);
9037 synchronized (this) {
9038 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
9041 mInjector.securityLogSetLoggingEnabledProperty(enabled);
9043 mSecurityLogMonitor.start();
9045 mSecurityLogMonitor.stop();
9051 public boolean isSecurityLoggingEnabled(ComponentName admin) {
9052 Preconditions.checkNotNull(admin);
9053 synchronized (this) {
9054 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9055 return mInjector.securityLogGetLoggingEnabledProperty();
9060 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
9061 Preconditions.checkNotNull(admin);
9062 ensureDeviceOwnerManagingSingleUser(admin);
9064 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
9068 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
9070 SecurityLog.readPreviousEvents(output);
9071 return new ParceledListSlice<SecurityEvent>(output);
9072 } catch (IOException e) {
9073 Slog.w(LOG_TAG, "Fail to read previous events" , e);
9074 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
9079 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
9080 Preconditions.checkNotNull(admin);
9081 ensureDeviceOwnerManagingSingleUser(admin);
9083 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
9084 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
9087 private void enforceCanManageDeviceAdmin() {
9088 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
9092 private void enforceCanManageProfileAndDeviceOwners() {
9093 mContext.enforceCallingOrSelfPermission(
9094 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
9098 public boolean isUninstallInQueue(final String packageName) {
9099 enforceCanManageDeviceAdmin();
9100 final int userId = mInjector.userHandleGetCallingUserId();
9101 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9102 synchronized (this) {
9103 return mPackagesToRemove.contains(packageUserPair);
9108 public void uninstallPackageWithActiveAdmins(final String packageName) {
9109 enforceCanManageDeviceAdmin();
9110 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
9112 final int userId = mInjector.userHandleGetCallingUserId();
9114 enforceUserUnlocked(userId);
9116 final ComponentName profileOwner = getProfileOwner(userId);
9117 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
9118 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
9121 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
9122 if (getDeviceOwnerUserId() == userId && deviceOwner != null
9123 && packageName.equals(deviceOwner.getPackageName())) {
9124 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
9127 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9128 synchronized (this) {
9129 mPackagesToRemove.add(packageUserPair);
9132 // All active admins on the user.
9133 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
9135 // Active admins in the target package.
9136 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
9137 if (allActiveAdmins != null) {
9138 for (ComponentName activeAdmin : allActiveAdmins) {
9139 if (packageName.equals(activeAdmin.getPackageName())) {
9140 packageActiveAdmins.add(activeAdmin);
9141 removeActiveAdmin(activeAdmin, userId);
9145 if (packageActiveAdmins.size() == 0) {
9146 startUninstallIntent(packageName, userId);
9148 mHandler.postDelayed(new Runnable() {
9151 for (ComponentName activeAdmin : packageActiveAdmins) {
9152 removeAdminArtifacts(activeAdmin, userId);
9154 startUninstallIntent(packageName, userId);
9156 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9161 public boolean isDeviceProvisioned() {
9162 return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9165 private void removePackageIfRequired(final String packageName, final int userId) {
9166 if (!packageHasActiveAdmins(packageName, userId)) {
9167 // Will not do anything if uninstall was not requested or was already started.
9168 startUninstallIntent(packageName, userId);
9172 private void startUninstallIntent(final String packageName, final int userId) {
9173 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9174 synchronized (this) {
9175 if (!mPackagesToRemove.contains(packageUserPair)) {
9176 // Do nothing if uninstall was not requested or was already started.
9179 mPackagesToRemove.remove(packageUserPair);
9182 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9183 // Package does not exist. Nothing to do.
9186 } catch (RemoteException re) {
9187 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9190 try { // force stop the package before uninstalling
9191 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9192 } catch (RemoteException re) {
9193 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9195 final Uri packageURI = Uri.parse("package:" + packageName);
9196 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9197 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9198 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9202 * Removes the admin from the policy. Ideally called after the admin's
9203 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9205 * @param adminReceiver The admin to remove
9206 * @param userHandle The user for which this admin has to be removed.
9208 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9209 synchronized (this) {
9210 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9211 if (admin == null) {
9214 final DevicePolicyData policy = getUserData(userHandle);
9215 final boolean doProxyCleanup = admin.info.usesPolicy(
9216 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9217 policy.mAdminList.remove(admin);
9218 policy.mAdminMap.remove(adminReceiver);
9219 validatePasswordOwnerLocked(policy);
9220 if (doProxyCleanup) {
9221 resetGlobalProxyLocked(policy);
9223 saveSettingsLocked(userHandle);
9224 updateMaximumTimeToLockLocked(userHandle);
9225 policy.mRemovingAdmins.remove(adminReceiver);
9227 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
9229 // The removed admin might have disabled camera, so update user
9231 pushUserRestrictions(userHandle);
9235 public void setDeviceProvisioningConfigApplied() {
9236 enforceManageUsers();
9237 synchronized (this) {
9238 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9239 policy.mDeviceProvisioningConfigApplied = true;
9240 saveSettingsLocked(UserHandle.USER_SYSTEM);
9245 public boolean isDeviceProvisioningConfigApplied() {
9246 enforceManageUsers();
9247 synchronized (this) {
9248 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9249 return policy.mDeviceProvisioningConfigApplied;
9254 * Return true if a given user has any accounts that'll prevent installing a device or profile
9255 * owner {@code owner}.
9256 * - If the user has no accounts, then return false.
9257 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
9258 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
9259 * ..._DISALLOWED, return true.
9260 * - Otherwise return false.
9262 private boolean hasIncompatibleAccountsLocked(int userId, @Nullable ComponentName owner) {
9263 final long token = mInjector.binderClearCallingIdentity();
9265 final AccountManager am = AccountManager.get(mContext);
9266 final Account accounts[] = am.getAccountsAsUser(userId);
9267 if (accounts.length == 0) {
9270 final String[] feature_allow =
9271 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
9272 final String[] feature_disallow =
9273 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
9275 // Even if we find incompatible accounts along the way, we still check all accounts
9277 boolean compatible = true;
9278 for (Account account : accounts) {
9279 if (hasAccountFeatures(am, account, feature_disallow)) {
9280 Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
9283 if (!hasAccountFeatures(am, account, feature_allow)) {
9284 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
9289 Log.w(LOG_TAG, "All accounts are compatible");
9291 Log.e(LOG_TAG, "Found incompatible accounts");
9294 // Then check if the owner is test-only.
9296 if (owner == null) {
9297 // Owner is unknown. Suppose it's not test-only
9299 log = "Only test-only device/profile owner can be installed with accounts";
9300 } else if (isAdminTestOnlyLocked(owner, userId)) {
9302 log = "Installing test-only owner " + owner;
9304 log = "Can't install test-only owner " + owner + " with incompatible accounts";
9308 log = "Can't install non test-only owner " + owner + " with accounts";
9311 Log.w(LOG_TAG, log);
9313 Log.e(LOG_TAG, log);
9317 mInjector.binderRestoreCallingIdentity(token);
9321 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
9323 return am.hasFeatures(account, features, null, null).getResult();
9324 } catch (Exception e) {
9325 Log.w(LOG_TAG, "Failed to get account feature", e);
9331 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
9332 Preconditions.checkNotNull(admin);
9336 ensureDeviceOwnerManagingSingleUser(admin);
9337 setBackupServiceEnabledInternal(enabled);
9340 private synchronized void setBackupServiceEnabledInternal(boolean enabled) {
9341 long ident = mInjector.binderClearCallingIdentity();
9343 IBackupManager ibm = mInjector.getIBackupManager();
9345 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
9347 } catch (RemoteException e) {
9348 throw new IllegalStateException(
9349 "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
9351 mInjector.binderRestoreCallingIdentity(ident);
9356 public boolean isBackupServiceEnabled(ComponentName admin) {
9357 Preconditions.checkNotNull(admin);
9361 synchronized (this) {
9362 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9364 IBackupManager ibm = mInjector.getIBackupManager();
9365 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
9366 } catch (RemoteException e) {
9367 throw new IllegalStateException("Failed requesting backup service state.", e);