2 * Copyright (C) 2010 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.server.devicepolicy;
19 import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
20 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
21 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
22 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
23 import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
25 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
26 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
27 import static org.xmlpull.v1.XmlPullParser.END_TAG;
28 import static org.xmlpull.v1.XmlPullParser.TEXT;
30 import android.Manifest.permission;
31 import android.accessibilityservice.AccessibilityServiceInfo;
32 import android.accounts.Account;
33 import android.accounts.AccountManager;
34 import android.annotation.IntDef;
35 import android.annotation.NonNull;
36 import android.annotation.Nullable;
37 import android.annotation.UserIdInt;
38 import android.app.Activity;
39 import android.app.ActivityManager;
40 import android.app.ActivityManagerNative;
41 import android.app.AlarmManager;
42 import android.app.AppGlobals;
43 import android.app.IActivityManager;
44 import android.app.Notification;
45 import android.app.NotificationManager;
46 import android.app.PendingIntent;
47 import android.app.StatusBarManager;
48 import android.app.admin.DeviceAdminInfo;
49 import android.app.admin.DeviceAdminReceiver;
50 import android.app.admin.DevicePolicyManager;
51 import android.app.admin.DevicePolicyManagerInternal;
52 import android.app.admin.IDevicePolicyManager;
53 import android.app.admin.SecurityLog;
54 import android.app.admin.SecurityLog.SecurityEvent;
55 import android.app.admin.SystemUpdatePolicy;
56 import android.app.backup.IBackupManager;
57 import android.app.trust.TrustManager;
58 import android.content.BroadcastReceiver;
59 import android.content.ComponentName;
60 import android.content.Context;
61 import android.content.Intent;
62 import android.content.IntentFilter;
63 import android.content.pm.ActivityInfo;
64 import android.content.pm.ApplicationInfo;
65 import android.content.pm.IPackageManager;
66 import android.content.pm.PackageInfo;
67 import android.content.pm.PackageManager;
68 import android.content.pm.PackageManager.NameNotFoundException;
69 import android.content.pm.PackageManagerInternal;
70 import android.content.pm.ParceledListSlice;
71 import android.content.pm.ResolveInfo;
72 import android.content.pm.ServiceInfo;
73 import android.content.pm.UserInfo;
74 import android.database.ContentObserver;
75 import android.graphics.Bitmap;
76 import android.graphics.Color;
77 import android.media.AudioManager;
78 import android.media.IAudioService;
79 import android.net.ConnectivityManager;
80 import android.net.ProxyInfo;
81 import android.net.Uri;
82 import android.net.wifi.WifiInfo;
83 import android.net.wifi.WifiManager;
84 import android.os.AsyncTask;
85 import android.os.Binder;
86 import android.os.Build;
87 import android.os.Bundle;
88 import android.os.Environment;
89 import android.os.FileUtils;
90 import android.os.Handler;
91 import android.os.IBinder;
92 import android.os.Looper;
93 import android.os.ParcelFileDescriptor;
94 import android.os.PersistableBundle;
95 import android.os.PowerManager;
96 import android.os.PowerManagerInternal;
97 import android.os.Process;
98 import android.os.RecoverySystem;
99 import android.os.RemoteCallback;
100 import android.os.RemoteException;
101 import android.os.ServiceManager;
102 import android.os.SystemClock;
103 import android.os.SystemProperties;
104 import android.os.UserHandle;
105 import android.os.UserManager;
106 import android.os.UserManagerInternal;
107 import android.os.storage.StorageManager;
108 import android.provider.ContactsContract.QuickContact;
109 import android.provider.ContactsInternal;
110 import android.provider.Settings;
111 import android.security.Credentials;
112 import android.security.IKeyChainAliasCallback;
113 import android.security.IKeyChainService;
114 import android.security.KeyChain;
115 import android.security.KeyChain.KeyChainConnection;
116 import android.service.persistentdata.PersistentDataBlockManager;
117 import android.telephony.TelephonyManager;
118 import android.text.TextUtils;
119 import android.util.ArrayMap;
120 import android.util.ArraySet;
121 import android.util.Log;
122 import android.util.Pair;
123 import android.util.Slog;
124 import android.util.SparseArray;
125 import android.util.Xml;
126 import android.view.IWindowManager;
127 import android.view.accessibility.AccessibilityManager;
128 import android.view.accessibility.IAccessibilityManager;
129 import android.view.inputmethod.InputMethodInfo;
130 import android.view.inputmethod.InputMethodManager;
132 import com.android.internal.R;
133 import com.android.internal.annotations.VisibleForTesting;
134 import com.android.internal.statusbar.IStatusBarService;
135 import com.android.internal.util.FastXmlSerializer;
136 import com.android.internal.util.JournaledFile;
137 import com.android.internal.util.ParcelableString;
138 import com.android.internal.util.Preconditions;
139 import com.android.internal.util.XmlUtils;
140 import com.android.internal.widget.LockPatternUtils;
141 import com.android.server.LocalServices;
142 import com.android.server.SystemService;
143 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
144 import com.android.server.pm.UserRestrictionsUtils;
145 import com.google.android.collect.Sets;
147 import org.xmlpull.v1.XmlPullParser;
148 import org.xmlpull.v1.XmlPullParserException;
149 import org.xmlpull.v1.XmlSerializer;
151 import java.io.ByteArrayInputStream;
153 import java.io.FileDescriptor;
154 import java.io.FileInputStream;
155 import java.io.FileNotFoundException;
156 import java.io.FileOutputStream;
157 import java.io.IOException;
158 import java.io.PrintWriter;
159 import java.lang.annotation.Retention;
160 import java.lang.annotation.RetentionPolicy;
161 import java.nio.charset.StandardCharsets;
162 import java.security.cert.CertificateException;
163 import java.security.cert.CertificateFactory;
164 import java.security.cert.X509Certificate;
165 import java.text.DateFormat;
166 import java.util.ArrayList;
167 import java.util.Arrays;
168 import java.util.Collections;
169 import java.util.Date;
170 import java.util.List;
171 import java.util.Map.Entry;
172 import java.util.Set;
173 import java.util.concurrent.atomic.AtomicBoolean;
176 * Implementation of the device policy APIs.
178 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
180 private static final String LOG_TAG = "DevicePolicyManagerService";
182 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
184 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
186 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
188 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
190 private static final String TAG_STATUS_BAR = "statusbar";
192 private static final String ATTR_DISABLED = "disabled";
194 private static final String ATTR_NAME = "name";
196 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
197 "do-not-ask-credentials-on-boot";
199 private static final String TAG_AFFILIATION_ID = "affiliation-id";
201 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
203 private static final String ATTR_VALUE = "value";
205 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
207 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
209 private static final long MS_PER_DAY = 86400 * 1000;
211 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
213 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
214 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
216 private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
217 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
219 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
220 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
221 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
222 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
223 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
224 "device-provisioning-config-applied";
225 private static final String ATTR_DEVICE_PAIRED = "device-paired";
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;
305 private static final int CODE_HAS_PAIRED = 8;
307 @Retention(RetentionPolicy.SOURCE)
308 @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
309 CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
310 private @interface DeviceOwnerPreConditionCode {}
312 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
315 * Minimum timeout in milliseconds after which unlocking with weak auth times out,
316 * i.e. the user has to use a strong authentication method like password, PIN or pattern.
318 private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
320 final Context mContext;
321 final Injector mInjector;
322 final IPackageManager mIPackageManager;
323 final UserManager mUserManager;
324 final UserManagerInternal mUserManagerInternal;
325 final TelephonyManager mTelephonyManager;
326 private final LockPatternUtils mLockPatternUtils;
329 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
330 * is requested for user u.
332 private final Set<Pair<String, Integer>> mPackagesToRemove =
333 new ArraySet<Pair<String, Integer>>();
335 final LocalService mLocalService;
337 // Stores and loads state on device and profile owners.
339 final Owners mOwners;
341 private final Binder mToken = new Binder();
344 * Whether or not device admin feature is supported. If it isn't return defaults for all
350 * Whether or not this device is a watch.
354 private final SecurityLogMonitor mSecurityLogMonitor;
356 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
357 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
359 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
362 if(mRemoteBugreportServiceIsActive.get()) {
368 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
371 public void onReceive(Context context, Intent intent) {
372 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
373 && mRemoteBugreportServiceIsActive.get()) {
374 onBugreportFinished(intent);
379 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
382 public void onReceive(Context context, Intent intent) {
383 String action = intent.getAction();
384 mInjector.getNotificationManager().cancel(LOG_TAG,
385 RemoteBugreportUtils.NOTIFICATION_ID);
386 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
387 onBugreportSharingAccepted();
388 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
389 onBugreportSharingDeclined();
391 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
395 public static final class Lifecycle extends SystemService {
396 private DevicePolicyManagerService mService;
398 public Lifecycle(Context context) {
400 mService = new DevicePolicyManagerService(context);
404 public void onStart() {
405 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
409 public void onBootPhase(int phase) {
410 mService.systemReady(phase);
414 public void onStartUser(int userHandle) {
415 mService.onStartUser(userHandle);
419 public static class DevicePolicyData {
420 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
421 int mActivePasswordLength = 0;
422 int mActivePasswordUpperCase = 0;
423 int mActivePasswordLowerCase = 0;
424 int mActivePasswordLetters = 0;
425 int mActivePasswordNumeric = 0;
426 int mActivePasswordSymbols = 0;
427 int mActivePasswordNonLetter = 0;
428 int mFailedPasswordAttempts = 0;
431 int mPasswordOwner = -1;
432 long mLastMaximumTimeToLock = -1;
433 boolean mUserSetupComplete = false;
434 boolean mPaired = false;
435 int mUserProvisioningState;
436 int mPermissionPolicy;
438 boolean mDeviceProvisioningConfigApplied = false;
440 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
441 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
442 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
444 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
446 // This is the list of component allowed to start lock task mode.
447 List<String> mLockTaskPackages = new ArrayList<>();
449 boolean mStatusBarDisabled = false;
451 ComponentName mRestrictionsProvider;
453 String mDelegatedCertInstallerPackage;
455 boolean doNotAskCredentialsOnBoot = false;
457 String mApplicationRestrictionsManagingPackage;
459 Set<String> mAffiliationIds = new ArraySet<>();
461 // Used for initialization of users created by createAndManageUsers.
462 boolean mAdminBroadcastPending = false;
463 PersistableBundle mInitBundle = null;
465 public DevicePolicyData(int userHandle) {
466 mUserHandle = userHandle;
470 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
472 final Handler mHandler;
474 BroadcastReceiver mReceiver = new BroadcastReceiver() {
476 public void onReceive(Context context, Intent intent) {
477 final String action = intent.getAction();
478 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
481 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
482 && userHandle == mOwners.getDeviceOwnerUserId()
483 && getDeviceOwnerRemoteBugreportUri() != null) {
484 IntentFilter filterConsent = new IntentFilter();
485 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
486 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
487 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
488 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
489 RemoteBugreportUtils.NOTIFICATION_ID,
490 RemoteBugreportUtils.buildNotification(mContext,
491 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
494 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
495 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
497 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
498 + action + " for user " + userHandle);
500 mHandler.post(new Runnable() {
503 handlePasswordExpirationNotification(userHandle);
507 if (Intent.ACTION_USER_UNLOCKED.equals(action)
508 || Intent.ACTION_USER_STARTED.equals(action)
509 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
510 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
511 new MonitoringCertNotificationTask().execute(userId);
513 if (Intent.ACTION_USER_ADDED.equals(action)) {
514 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
515 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
516 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
517 removeUserData(userHandle);
518 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
519 synchronized (DevicePolicyManagerService.this) {
520 // Reset the policy data
521 mUserData.remove(userHandle);
522 sendAdminEnabledBroadcastLocked(userHandle);
524 handlePackagesChanged(null /* check all admins */, userHandle);
525 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
526 handlePackagesChanged(null /* check all admins */, userHandle);
527 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
528 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
529 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
530 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
531 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
532 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
533 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
534 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
535 clearWipeProfileNotification();
540 static class ActiveAdmin {
541 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
542 private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
543 private static final String TAG_DISABLE_CAMERA = "disable-camera";
544 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
545 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
546 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
547 = "disable-bt-contacts-sharing";
548 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
549 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
550 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
551 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
552 private static final String TAG_ACCOUNT_TYPE = "account-type";
553 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
554 = "permitted-accessiblity-services";
555 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
556 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
557 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
558 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
559 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
560 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
561 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
562 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
563 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
564 private static final String TAG_PERMITTED_IMES = "permitted-imes";
565 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
566 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
567 private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
568 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
569 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
570 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
571 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
572 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
573 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
574 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
575 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
576 private static final String ATTR_VALUE = "value";
577 private static final String TAG_PASSWORD_QUALITY = "password-quality";
578 private static final String TAG_POLICIES = "policies";
579 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
580 "cross-profile-widget-providers";
581 private static final String TAG_PROVIDER = "provider";
582 private static final String TAG_PACKAGE_LIST_ITEM = "item";
583 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
584 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
585 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
586 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
587 private static final String TAG_PARENT_ADMIN = "parent-admin";
588 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
589 private static final String TAG_ORGANIZATION_NAME = "organization-name";
591 final DeviceAdminInfo info;
593 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
595 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
596 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
598 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
599 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
601 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
602 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
604 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
605 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
607 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
608 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
610 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
611 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
613 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
614 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
616 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
617 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
619 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
620 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
622 long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
624 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
625 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
627 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
628 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
630 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
631 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
633 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
635 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
637 boolean encryptionRequested = false;
638 boolean testOnlyAdmin = false;
639 boolean disableCamera = false;
640 boolean disableCallerId = false;
641 boolean disableContactsSearch = false;
642 boolean disableBluetoothContactSharing = true;
643 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
644 boolean requireAutoTime = false; // Can only be set by a device owner.
645 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
647 ActiveAdmin parentAdmin;
648 final boolean isParent;
650 static class TrustAgentInfo {
651 public PersistableBundle options;
652 TrustAgentInfo(PersistableBundle bundle) {
657 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
659 // The list of permitted accessibility services package namesas set by a profile
660 // or device owner. Null means all accessibility services are allowed, empty means
661 // none except system services are allowed.
662 List<String> permittedAccessiblityServices;
664 // The list of permitted input methods package names as set by a profile or device owner.
665 // Null means all input methods are allowed, empty means none except system imes are
667 List<String> permittedInputMethods;
669 // List of package names to keep cached.
670 List<String> keepUninstalledPackages;
672 // TODO: review implementation decisions with frameworks team
673 boolean specifiesGlobalProxy = false;
674 String globalProxySpec = null;
675 String globalProxyExclusionList = null;
677 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
679 List<String> crossProfileWidgetProviders;
681 Bundle userRestrictions;
683 // Support text provided by the admin to display to the user.
684 CharSequence shortSupportMessage = null;
685 CharSequence longSupportMessage = null;
687 // Background color of confirm credentials screen. Default: teal.
688 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
689 int organizationColor = DEF_ORGANIZATION_COLOR;
691 // Default title of confirm credentials screen
692 String organizationName = null;
694 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
699 ActiveAdmin getParentActiveAdmin() {
700 Preconditions.checkState(!isParent);
702 if (parentAdmin == null) {
703 parentAdmin = new ActiveAdmin(info, /* parent */ true);
708 boolean hasParentActiveAdmin() {
709 return parentAdmin != null;
712 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
714 public UserHandle getUserHandle() {
715 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
718 void writeToXml(XmlSerializer out)
719 throws IllegalArgumentException, IllegalStateException, IOException {
720 out.startTag(null, TAG_POLICIES);
721 info.writePoliciesToXml(out);
722 out.endTag(null, TAG_POLICIES);
723 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
724 out.startTag(null, TAG_PASSWORD_QUALITY);
725 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
726 out.endTag(null, TAG_PASSWORD_QUALITY);
727 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
728 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
729 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
730 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
732 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
733 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
734 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
735 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
737 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
738 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
739 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
740 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
742 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
743 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
744 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
745 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
747 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
748 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
749 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
750 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
752 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
753 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
754 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
755 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
757 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
758 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
759 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
760 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
762 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
763 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
764 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
765 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
768 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
769 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
770 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
771 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
773 if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
774 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
775 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
776 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
778 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
779 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
780 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
781 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
783 if (specifiesGlobalProxy) {
784 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
785 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
786 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
787 if (globalProxySpec != null) {
788 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
789 out.attribute(null, ATTR_VALUE, globalProxySpec);
790 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
792 if (globalProxyExclusionList != null) {
793 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
794 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
795 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
798 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
799 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
800 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
801 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
803 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
804 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
805 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
806 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
808 if (encryptionRequested) {
809 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
810 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
811 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
814 out.startTag(null, TAG_TEST_ONLY_ADMIN);
815 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
816 out.endTag(null, TAG_TEST_ONLY_ADMIN);
819 out.startTag(null, TAG_DISABLE_CAMERA);
820 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
821 out.endTag(null, TAG_DISABLE_CAMERA);
823 if (disableCallerId) {
824 out.startTag(null, TAG_DISABLE_CALLER_ID);
825 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
826 out.endTag(null, TAG_DISABLE_CALLER_ID);
828 if (disableContactsSearch) {
829 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
830 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
831 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
833 if (!disableBluetoothContactSharing) {
834 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
835 out.attribute(null, ATTR_VALUE,
836 Boolean.toString(disableBluetoothContactSharing));
837 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
839 if (disableScreenCapture) {
840 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
841 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
842 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
844 if (requireAutoTime) {
845 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
846 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
847 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
849 if (forceEphemeralUsers) {
850 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
851 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
852 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
854 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
855 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
856 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
857 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
859 if (!accountTypesWithManagementDisabled.isEmpty()) {
860 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
861 for (String ac : accountTypesWithManagementDisabled) {
862 out.startTag(null, TAG_ACCOUNT_TYPE);
863 out.attribute(null, ATTR_VALUE, ac);
864 out.endTag(null, TAG_ACCOUNT_TYPE);
866 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
868 if (!trustAgentInfos.isEmpty()) {
869 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
870 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
871 for (Entry<String, TrustAgentInfo> entry : set) {
872 TrustAgentInfo trustAgentInfo = entry.getValue();
873 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
874 out.attribute(null, ATTR_VALUE, entry.getKey());
875 if (trustAgentInfo.options != null) {
876 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
878 trustAgentInfo.options.saveToXml(out);
879 } catch (XmlPullParserException e) {
880 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
882 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
884 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
886 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
888 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
889 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
890 final int providerCount = crossProfileWidgetProviders.size();
891 for (int i = 0; i < providerCount; i++) {
892 String provider = crossProfileWidgetProviders.get(i);
893 out.startTag(null, TAG_PROVIDER);
894 out.attribute(null, ATTR_VALUE, provider);
895 out.endTag(null, TAG_PROVIDER);
897 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
899 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
900 permittedAccessiblityServices);
901 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
902 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
903 if (hasUserRestrictions()) {
904 UserRestrictionsUtils.writeRestrictions(
905 out, userRestrictions, TAG_USER_RESTRICTIONS);
907 if (!TextUtils.isEmpty(shortSupportMessage)) {
908 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
909 out.text(shortSupportMessage.toString());
910 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
912 if (!TextUtils.isEmpty(longSupportMessage)) {
913 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
914 out.text(longSupportMessage.toString());
915 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
917 if (parentAdmin != null) {
918 out.startTag(null, TAG_PARENT_ADMIN);
919 parentAdmin.writeToXml(out);
920 out.endTag(null, TAG_PARENT_ADMIN);
922 if (organizationColor != DEF_ORGANIZATION_COLOR) {
923 out.startTag(null, TAG_ORGANIZATION_COLOR);
924 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
925 out.endTag(null, TAG_ORGANIZATION_COLOR);
927 if (organizationName != null) {
928 out.startTag(null, TAG_ORGANIZATION_NAME);
929 out.text(organizationName);
930 out.endTag(null, TAG_ORGANIZATION_NAME);
934 void writePackageListToXml(XmlSerializer out, String outerTag,
935 List<String> packageList)
936 throws IllegalArgumentException, IllegalStateException, IOException {
937 if (packageList == null) {
941 out.startTag(null, outerTag);
942 for (String packageName : packageList) {
943 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
944 out.attribute(null, ATTR_VALUE, packageName);
945 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
947 out.endTag(null, outerTag);
950 void readFromXml(XmlPullParser parser)
951 throws XmlPullParserException, IOException {
952 int outerDepth = parser.getDepth();
954 while ((type=parser.next()) != END_DOCUMENT
955 && (type != END_TAG || parser.getDepth() > outerDepth)) {
956 if (type == END_TAG || type == TEXT) {
959 String tag = parser.getName();
960 if (TAG_POLICIES.equals(tag)) {
961 info.readPoliciesFromXml(parser);
962 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
963 passwordQuality = Integer.parseInt(
964 parser.getAttributeValue(null, ATTR_VALUE));
965 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
966 minimumPasswordLength = Integer.parseInt(
967 parser.getAttributeValue(null, ATTR_VALUE));
968 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
969 passwordHistoryLength = Integer.parseInt(
970 parser.getAttributeValue(null, ATTR_VALUE));
971 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
972 minimumPasswordUpperCase = Integer.parseInt(
973 parser.getAttributeValue(null, ATTR_VALUE));
974 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
975 minimumPasswordLowerCase = Integer.parseInt(
976 parser.getAttributeValue(null, ATTR_VALUE));
977 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
978 minimumPasswordLetters = Integer.parseInt(
979 parser.getAttributeValue(null, ATTR_VALUE));
980 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
981 minimumPasswordNumeric = Integer.parseInt(
982 parser.getAttributeValue(null, ATTR_VALUE));
983 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
984 minimumPasswordSymbols = Integer.parseInt(
985 parser.getAttributeValue(null, ATTR_VALUE));
986 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
987 minimumPasswordNonLetter = Integer.parseInt(
988 parser.getAttributeValue(null, ATTR_VALUE));
989 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
990 maximumTimeToUnlock = Long.parseLong(
991 parser.getAttributeValue(null, ATTR_VALUE));
992 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
993 strongAuthUnlockTimeout = Long.parseLong(
994 parser.getAttributeValue(null, ATTR_VALUE));
995 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
996 maximumFailedPasswordsForWipe = Integer.parseInt(
997 parser.getAttributeValue(null, ATTR_VALUE));
998 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
999 specifiesGlobalProxy = Boolean.parseBoolean(
1000 parser.getAttributeValue(null, ATTR_VALUE));
1001 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1003 parser.getAttributeValue(null, ATTR_VALUE);
1004 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1005 globalProxyExclusionList =
1006 parser.getAttributeValue(null, ATTR_VALUE);
1007 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1008 passwordExpirationTimeout = Long.parseLong(
1009 parser.getAttributeValue(null, ATTR_VALUE));
1010 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1011 passwordExpirationDate = Long.parseLong(
1012 parser.getAttributeValue(null, ATTR_VALUE));
1013 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1014 encryptionRequested = Boolean.parseBoolean(
1015 parser.getAttributeValue(null, ATTR_VALUE));
1016 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1017 testOnlyAdmin = Boolean.parseBoolean(
1018 parser.getAttributeValue(null, ATTR_VALUE));
1019 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1020 disableCamera = Boolean.parseBoolean(
1021 parser.getAttributeValue(null, ATTR_VALUE));
1022 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1023 disableCallerId = Boolean.parseBoolean(
1024 parser.getAttributeValue(null, ATTR_VALUE));
1025 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1026 disableContactsSearch = Boolean.parseBoolean(
1027 parser.getAttributeValue(null, ATTR_VALUE));
1028 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1029 disableBluetoothContactSharing = Boolean.parseBoolean(parser
1030 .getAttributeValue(null, ATTR_VALUE));
1031 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1032 disableScreenCapture = Boolean.parseBoolean(
1033 parser.getAttributeValue(null, ATTR_VALUE));
1034 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1035 requireAutoTime = Boolean.parseBoolean(
1036 parser.getAttributeValue(null, ATTR_VALUE));
1037 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1038 forceEphemeralUsers = Boolean.parseBoolean(
1039 parser.getAttributeValue(null, ATTR_VALUE));
1040 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1041 disabledKeyguardFeatures = Integer.parseInt(
1042 parser.getAttributeValue(null, ATTR_VALUE));
1043 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1044 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
1045 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1046 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1047 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1048 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
1049 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1050 permittedAccessiblityServices = readPackageList(parser, tag);
1051 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1052 permittedInputMethods = readPackageList(parser, tag);
1053 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1054 keepUninstalledPackages = readPackageList(parser, tag);
1055 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1056 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
1057 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1058 type = parser.next();
1059 if (type == XmlPullParser.TEXT) {
1060 shortSupportMessage = parser.getText();
1062 Log.w(LOG_TAG, "Missing text when loading short support message");
1064 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1065 type = parser.next();
1066 if (type == XmlPullParser.TEXT) {
1067 longSupportMessage = parser.getText();
1069 Log.w(LOG_TAG, "Missing text when loading long support message");
1071 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1072 Preconditions.checkState(!isParent);
1074 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1075 parentAdmin.readFromXml(parser);
1076 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1077 organizationColor = Integer.parseInt(
1078 parser.getAttributeValue(null, ATTR_VALUE));
1079 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1080 type = parser.next();
1081 if (type == XmlPullParser.TEXT) {
1082 organizationName = parser.getText();
1084 Log.w(LOG_TAG, "Missing text when loading organization name");
1087 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1088 XmlUtils.skipCurrentTag(parser);
1093 private List<String> readPackageList(XmlPullParser parser,
1094 String tag) throws XmlPullParserException, IOException {
1095 List<String> result = new ArrayList<String>();
1096 int outerDepth = parser.getDepth();
1098 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1099 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1100 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1103 String outerTag = parser.getName();
1104 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1105 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1106 if (packageName != null) {
1107 result.add(packageName);
1109 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1112 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1118 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1119 throws XmlPullParserException, IOException {
1120 int outerDepthDAM = parser.getDepth();
1122 Set<String> result = new ArraySet<>();
1123 while ((typeDAM=parser.next()) != END_DOCUMENT
1124 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1125 if (typeDAM == END_TAG || typeDAM == TEXT) {
1128 String tagDAM = parser.getName();
1129 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1130 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1132 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1138 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1139 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1140 int outerDepthDAM = parser.getDepth();
1142 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1143 while ((typeDAM=parser.next()) != END_DOCUMENT
1144 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1145 if (typeDAM == END_TAG || typeDAM == TEXT) {
1148 String tagDAM = parser.getName();
1149 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1150 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1151 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1152 result.put(component, trustAgentInfo);
1154 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1160 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1161 throws XmlPullParserException, IOException {
1162 int outerDepthDAM = parser.getDepth();
1164 TrustAgentInfo result = new TrustAgentInfo(null);
1165 while ((typeDAM=parser.next()) != END_DOCUMENT
1166 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1167 if (typeDAM == END_TAG || typeDAM == TEXT) {
1170 String tagDAM = parser.getName();
1171 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1172 result.options = PersistableBundle.restoreFromXml(parser);
1174 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1180 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1181 throws XmlPullParserException, IOException {
1182 int outerDepthDAM = parser.getDepth();
1184 ArrayList<String> result = null;
1185 while ((typeDAM=parser.next()) != END_DOCUMENT
1186 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1187 if (typeDAM == END_TAG || typeDAM == TEXT) {
1190 String tagDAM = parser.getName();
1191 if (TAG_PROVIDER.equals(tagDAM)) {
1192 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1193 if (result == null) {
1194 result = new ArrayList<>();
1196 result.add(provider);
1198 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1204 boolean hasUserRestrictions() {
1205 return userRestrictions != null && userRestrictions.size() > 0;
1208 Bundle ensureUserRestrictions() {
1209 if (userRestrictions == null) {
1210 userRestrictions = new Bundle();
1212 return userRestrictions;
1215 void dump(String prefix, PrintWriter pw) {
1216 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1217 pw.print(prefix); pw.print("testOnlyAdmin=");
1218 pw.println(testOnlyAdmin);
1219 pw.print(prefix); pw.println("policies:");
1220 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1222 for (int i=0; i<pols.size(); i++) {
1223 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1226 pw.print(prefix); pw.print("passwordQuality=0x");
1227 pw.println(Integer.toHexString(passwordQuality));
1228 pw.print(prefix); pw.print("minimumPasswordLength=");
1229 pw.println(minimumPasswordLength);
1230 pw.print(prefix); pw.print("passwordHistoryLength=");
1231 pw.println(passwordHistoryLength);
1232 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1233 pw.println(minimumPasswordUpperCase);
1234 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1235 pw.println(minimumPasswordLowerCase);
1236 pw.print(prefix); pw.print("minimumPasswordLetters=");
1237 pw.println(minimumPasswordLetters);
1238 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1239 pw.println(minimumPasswordNumeric);
1240 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1241 pw.println(minimumPasswordSymbols);
1242 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1243 pw.println(minimumPasswordNonLetter);
1244 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1245 pw.println(maximumTimeToUnlock);
1246 pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1247 pw.println(strongAuthUnlockTimeout);
1248 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1249 pw.println(maximumFailedPasswordsForWipe);
1250 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1251 pw.println(specifiesGlobalProxy);
1252 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1253 pw.println(passwordExpirationTimeout);
1254 pw.print(prefix); pw.print("passwordExpirationDate=");
1255 pw.println(passwordExpirationDate);
1256 if (globalProxySpec != null) {
1257 pw.print(prefix); pw.print("globalProxySpec=");
1258 pw.println(globalProxySpec);
1260 if (globalProxyExclusionList != null) {
1261 pw.print(prefix); pw.print("globalProxyEclusionList=");
1262 pw.println(globalProxyExclusionList);
1264 pw.print(prefix); pw.print("encryptionRequested=");
1265 pw.println(encryptionRequested);
1266 pw.print(prefix); pw.print("disableCamera=");
1267 pw.println(disableCamera);
1268 pw.print(prefix); pw.print("disableCallerId=");
1269 pw.println(disableCallerId);
1270 pw.print(prefix); pw.print("disableContactsSearch=");
1271 pw.println(disableContactsSearch);
1272 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1273 pw.println(disableBluetoothContactSharing);
1274 pw.print(prefix); pw.print("disableScreenCapture=");
1275 pw.println(disableScreenCapture);
1276 pw.print(prefix); pw.print("requireAutoTime=");
1277 pw.println(requireAutoTime);
1278 pw.print(prefix); pw.print("forceEphemeralUsers=");
1279 pw.println(forceEphemeralUsers);
1280 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1281 pw.println(disabledKeyguardFeatures);
1282 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1283 pw.println(crossProfileWidgetProviders);
1284 if (permittedAccessiblityServices != null) {
1285 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1286 pw.println(permittedAccessiblityServices);
1288 if (permittedInputMethods != null) {
1289 pw.print(prefix); pw.print("permittedInputMethods=");
1290 pw.println(permittedInputMethods);
1292 if (keepUninstalledPackages != null) {
1293 pw.print(prefix); pw.print("keepUninstalledPackages=");
1294 pw.println(keepUninstalledPackages);
1296 pw.print(prefix); pw.print("organizationColor=");
1297 pw.println(organizationColor);
1298 if (organizationName != null) {
1299 pw.print(prefix); pw.print("organizationName=");
1300 pw.println(organizationName);
1302 pw.print(prefix); pw.println("userRestrictions:");
1303 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1304 pw.print(prefix); pw.print("isParent=");
1305 pw.println(isParent);
1306 if (parentAdmin != null) {
1307 pw.print(prefix); pw.println("parentAdmin:");
1308 parentAdmin.dump(prefix + " ", pw);
1313 private void handlePackagesChanged(String packageName, int userHandle) {
1314 boolean removed = false;
1315 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1316 DevicePolicyData policy = getUserData(userHandle);
1317 synchronized (this) {
1318 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1319 ActiveAdmin aa = policy.mAdminList.get(i);
1321 // If we're checking all packages or if the specific one we're checking matches,
1322 // then check if the package and receiver still exist.
1323 final String adminPackage = aa.info.getPackageName();
1324 if (packageName == null || packageName.equals(adminPackage)) {
1325 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1326 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1327 PackageManager.MATCH_DIRECT_BOOT_AWARE
1328 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1329 userHandle) == null) {
1331 policy.mAdminList.remove(i);
1332 policy.mAdminMap.remove(aa.info.getComponent());
1335 } catch (RemoteException re) {
1340 validatePasswordOwnerLocked(policy);
1341 saveSettingsLocked(policy.mUserHandle);
1344 // Check if delegated cert installer or app restrictions managing packages are removed.
1345 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1346 policy.mDelegatedCertInstallerPackage = null;
1347 saveSettingsLocked(policy.mUserHandle);
1349 if (isRemovedPackage(
1350 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1351 policy.mApplicationRestrictionsManagingPackage = null;
1352 saveSettingsLocked(policy.mUserHandle);
1356 // The removed admin might have disabled camera, so update user restrictions.
1357 pushUserRestrictions(userHandle);
1361 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1363 return targetPackage != null
1364 && (changedPackage == null || changedPackage.equals(targetPackage))
1365 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1366 } catch (RemoteException e) {
1374 * Unit test will subclass it to inject mocks.
1377 static class Injector {
1379 private final Context mContext;
1381 Injector(Context context) {
1385 Owners newOwners() {
1386 return new Owners(getUserManager(), getUserManagerInternal(),
1387 getPackageManagerInternal());
1390 UserManager getUserManager() {
1391 return UserManager.get(mContext);
1394 UserManagerInternal getUserManagerInternal() {
1395 return LocalServices.getService(UserManagerInternal.class);
1398 PackageManagerInternal getPackageManagerInternal() {
1399 return LocalServices.getService(PackageManagerInternal.class);
1402 NotificationManager getNotificationManager() {
1403 return mContext.getSystemService(NotificationManager.class);
1406 PowerManagerInternal getPowerManagerInternal() {
1407 return LocalServices.getService(PowerManagerInternal.class);
1410 TelephonyManager getTelephonyManager() {
1411 return TelephonyManager.from(mContext);
1414 TrustManager getTrustManager() {
1415 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1418 IWindowManager getIWindowManager() {
1419 return IWindowManager.Stub
1420 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1423 IActivityManager getIActivityManager() {
1424 return ActivityManagerNative.getDefault();
1427 IPackageManager getIPackageManager() {
1428 return AppGlobals.getPackageManager();
1431 IBackupManager getIBackupManager() {
1432 return IBackupManager.Stub.asInterface(
1433 ServiceManager.getService(Context.BACKUP_SERVICE));
1436 IAudioService getIAudioService() {
1437 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1440 LockPatternUtils newLockPatternUtils() {
1441 return new LockPatternUtils(mContext);
1444 boolean storageManagerIsFileBasedEncryptionEnabled() {
1445 return StorageManager.isFileEncryptedNativeOnly();
1448 boolean storageManagerIsNonDefaultBlockEncrypted() {
1449 long identity = Binder.clearCallingIdentity();
1451 return StorageManager.isNonDefaultBlockEncrypted();
1453 Binder.restoreCallingIdentity(identity);
1457 boolean storageManagerIsEncrypted() {
1458 return StorageManager.isEncrypted();
1461 boolean storageManagerIsEncryptable() {
1462 return StorageManager.isEncryptable();
1465 Looper getMyLooper() {
1466 return Looper.myLooper();
1469 WifiManager getWifiManager() {
1470 return mContext.getSystemService(WifiManager.class);
1473 long binderClearCallingIdentity() {
1474 return Binder.clearCallingIdentity();
1477 void binderRestoreCallingIdentity(long token) {
1478 Binder.restoreCallingIdentity(token);
1481 int binderGetCallingUid() {
1482 return Binder.getCallingUid();
1485 int binderGetCallingPid() {
1486 return Binder.getCallingPid();
1489 UserHandle binderGetCallingUserHandle() {
1490 return Binder.getCallingUserHandle();
1493 boolean binderIsCallingUidMyUid() {
1494 return getCallingUid() == Process.myUid();
1497 final int userHandleGetCallingUserId() {
1498 return UserHandle.getUserId(binderGetCallingUid());
1501 File environmentGetUserSystemDirectory(int userId) {
1502 return Environment.getUserSystemDirectory(userId);
1505 void powerManagerGoToSleep(long time, int reason, int flags) {
1506 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1509 void powerManagerReboot(String reason) {
1510 mContext.getSystemService(PowerManager.class).reboot(reason);
1513 boolean systemPropertiesGetBoolean(String key, boolean def) {
1514 return SystemProperties.getBoolean(key, def);
1517 long systemPropertiesGetLong(String key, long def) {
1518 return SystemProperties.getLong(key, def);
1521 String systemPropertiesGet(String key, String def) {
1522 return SystemProperties.get(key, def);
1525 String systemPropertiesGet(String key) {
1526 return SystemProperties.get(key);
1529 void systemPropertiesSet(String key, String value) {
1530 SystemProperties.set(key, value);
1533 boolean userManagerIsSplitSystemUser() {
1534 return UserManager.isSplitSystemUser();
1537 String getDevicePolicyFilePathForSystemUser() {
1538 return "/data/system/";
1541 void registerContentObserver(Uri uri, boolean notifyForDescendents,
1542 ContentObserver observer, int userHandle) {
1543 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1544 observer, userHandle);
1547 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1548 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1549 name, def, userHandle);
1552 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1553 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1554 name, value, userHandle);
1557 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1558 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1559 name, value, userHandle);
1562 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1563 Settings.Global.putStringForUser(mContext.getContentResolver(),
1564 name, value, userHandle);
1567 void settingsSecurePutInt(String name, int value) {
1568 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1571 int settingsGlobalGetInt(String name, int def) {
1572 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1575 void settingsGlobalPutInt(String name, int value) {
1576 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1579 void settingsSecurePutString(String name, String value) {
1580 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1583 void settingsGlobalPutString(String name, String value) {
1584 Settings.Global.putString(mContext.getContentResolver(), name, value);
1587 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1588 SecurityLog.setLoggingEnabledProperty(enabled);
1591 boolean securityLogGetLoggingEnabledProperty() {
1592 return SecurityLog.getLoggingEnabledProperty();
1595 boolean securityLogIsLoggingEnabled() {
1596 return SecurityLog.isLoggingEnabled();
1601 * Instantiates the service.
1603 public DevicePolicyManagerService(Context context) {
1604 this(new Injector(context));
1608 DevicePolicyManagerService(Injector injector) {
1609 mInjector = injector;
1610 mContext = Preconditions.checkNotNull(injector.mContext);
1611 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1612 mOwners = Preconditions.checkNotNull(injector.newOwners());
1614 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1615 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1616 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1617 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1619 mLocalService = new LocalService();
1620 mLockPatternUtils = injector.newLockPatternUtils();
1622 mSecurityLogMonitor = new SecurityLogMonitor(this);
1624 mHasFeature = mContext.getPackageManager()
1625 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1626 mIsWatch = mContext.getPackageManager()
1627 .hasSystemFeature(PackageManager.FEATURE_WATCH);
1629 // Skip the rest of the initialization
1632 IntentFilter filter = new IntentFilter();
1633 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1634 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1635 filter.addAction(Intent.ACTION_USER_ADDED);
1636 filter.addAction(Intent.ACTION_USER_REMOVED);
1637 filter.addAction(Intent.ACTION_USER_STARTED);
1638 filter.addAction(Intent.ACTION_USER_UNLOCKED);
1639 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1640 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1641 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1642 filter = new IntentFilter();
1643 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1644 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1645 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1646 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1647 filter.addDataScheme("package");
1648 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1649 filter = new IntentFilter();
1650 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1651 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1653 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1657 * Creates and loads the policy data from xml.
1658 * @param userHandle the user for whom to load the policy data
1662 DevicePolicyData getUserData(int userHandle) {
1663 synchronized (this) {
1664 DevicePolicyData policy = mUserData.get(userHandle);
1665 if (policy == null) {
1666 policy = new DevicePolicyData(userHandle);
1667 mUserData.append(userHandle, policy);
1668 loadSettingsLocked(policy, userHandle);
1675 * Creates and loads the policy data from xml for data that is shared between
1676 * various profiles of a user. In contrast to {@link #getUserData(int)}
1677 * it allows access to data of users other than the calling user.
1679 * This function should only be used for shared data, e.g. everything regarding
1680 * passwords and should be removed once multiple screen locks are present.
1681 * @param userHandle the user for whom to load the policy data
1684 DevicePolicyData getUserDataUnchecked(int userHandle) {
1685 long ident = mInjector.binderClearCallingIdentity();
1687 return getUserData(userHandle);
1689 mInjector.binderRestoreCallingIdentity(ident);
1693 void removeUserData(int userHandle) {
1694 synchronized (this) {
1695 if (userHandle == UserHandle.USER_SYSTEM) {
1696 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1699 mOwners.removeProfileOwner(userHandle);
1700 mOwners.writeProfileOwner(userHandle);
1702 DevicePolicyData policy = mUserData.get(userHandle);
1703 if (policy != null) {
1704 mUserData.remove(userHandle);
1706 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1707 DEVICE_POLICIES_XML);
1708 policyFile.delete();
1709 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1711 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1715 synchronized (this) {
1717 setDeviceOwnerSystemPropertyLocked();
1718 findOwnerComponentIfNecessaryLocked();
1719 migrateUserRestrictionsIfNecessaryLocked();
1721 // TODO PO may not have a class name either due to b/17652534. Address that too.
1723 updateDeviceOwnerLocked();
1727 private void setDeviceOwnerSystemPropertyLocked() {
1728 // Device owner may still be provisioned, do not set the read-only system property yet.
1729 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1732 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1733 // always false at this point.
1734 if (StorageManager.inCryptKeeperBounce()) {
1738 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1739 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1741 if (mOwners.hasDeviceOwner()) {
1742 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1743 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1744 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
1745 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1746 mSecurityLogMonitor.start();
1749 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1750 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1755 private void findOwnerComponentIfNecessaryLocked() {
1756 if (!mOwners.hasDeviceOwner()) {
1759 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1761 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1762 return; // Already a full component name.
1765 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1766 doComponentName.getPackageName(),
1767 mOwners.getDeviceOwnerUserId());
1768 if (doComponent == null) {
1769 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1771 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1773 mOwners.getDeviceOwnerName(),
1774 mOwners.getDeviceOwnerUserId(),
1775 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1776 mOwners.writeDeviceOwner();
1778 Log.v(LOG_TAG, "Device owner component filled in");
1784 * We didn't use to persist user restrictions for each owners but only persisted in user
1787 private void migrateUserRestrictionsIfNecessaryLocked() {
1788 boolean migrated = false;
1789 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1790 // except for the "system controlled" ones.
1791 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1793 Log.v(LOG_TAG, "Migrating DO user restrictions");
1797 // Migrate user 0 restrictions to DO.
1798 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1800 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1801 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1803 // Push DO user restrictions to user manager.
1804 pushUserRestrictions(UserHandle.USER_SYSTEM);
1806 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1811 // The following restrictions can be set on secondary users by the device owner, so we
1812 // assume they're not from the PO.
1813 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1814 UserManager.DISALLOW_OUTGOING_CALLS,
1815 UserManager.DISALLOW_SMS);
1817 for (UserInfo ui : mUserManager.getUsers()) {
1818 final int userId = ui.id;
1819 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1821 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1825 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1827 final Set<String> exceptionList =
1828 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1830 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1831 exceptionList, /* isDeviceOwner =*/ false);
1833 // Note if a secondary user has no PO but has a DA that disables camera, we
1834 // don't get here and won't push the camera user restriction to UserManager
1835 // here. That's okay because we'll push user restrictions anyway when a user
1836 // starts. But we still do it because we want to let user manager persist
1838 pushUserRestrictions(userId);
1840 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1843 if (VERBOSE_LOG && migrated) {
1844 Log.v(LOG_TAG, "User restrictions migrated.");
1848 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1849 Set<String> exceptionList, boolean isDeviceOwner) {
1850 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1851 user.getIdentifier());
1853 final Bundle newBaseRestrictions = new Bundle();
1854 final Bundle newOwnerRestrictions = new Bundle();
1856 for (String key : origRestrictions.keySet()) {
1857 if (!origRestrictions.getBoolean(key)) {
1860 final boolean canOwnerChange = isDeviceOwner
1861 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1862 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1864 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1865 newBaseRestrictions.putBoolean(key, true);
1867 newOwnerRestrictions.putBoolean(key, true);
1872 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1873 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1874 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1876 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1877 newBaseRestrictions);
1879 if (admin != null) {
1880 admin.ensureUserRestrictions().clear();
1881 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1883 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1885 saveSettingsLocked(user.getIdentifier());
1888 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1889 final DevicePolicyData policy = getUserData(userId);
1890 final int n = policy.mAdminList.size();
1891 ComponentName found = null;
1893 for (int i = 0; i < n; i++) {
1894 final ActiveAdmin admin = policy.mAdminList.get(i);
1895 if (packageName.equals(admin.info.getPackageName())) {
1898 found = admin.info.getComponent();
1904 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1910 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1911 * reminders. Clears alarm if no expirations are configured.
1913 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1914 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1915 final long now = System.currentTimeMillis();
1916 final long timeToExpire = expiration - now;
1917 final long alarmTime;
1918 if (expiration == 0) {
1919 // No expirations are currently configured: Cancel alarm.
1921 } else if (timeToExpire <= 0) {
1922 // The password has already expired: Repeat every 24 hours.
1923 alarmTime = now + MS_PER_DAY;
1925 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1926 // the expiration time.
1927 long alarmInterval = timeToExpire % MS_PER_DAY;
1928 if (alarmInterval == 0) {
1929 alarmInterval = MS_PER_DAY;
1931 alarmTime = now + alarmInterval;
1934 long token = mInjector.binderClearCallingIdentity();
1936 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1937 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1938 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1939 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1940 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1941 UserHandle.of(affectedUserHandle));
1943 if (alarmTime != 0) {
1944 am.set(AlarmManager.RTC, alarmTime, pi);
1947 mInjector.binderRestoreCallingIdentity(token);
1951 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1952 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1954 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1955 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1961 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
1963 enforceManagedProfile(userHandle, "call APIs on the parent profile");
1965 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1966 if (admin != null && parent) {
1967 admin = admin.getParentActiveAdmin();
1972 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1973 throws SecurityException {
1974 final int callingUid = mInjector.binderGetCallingUid();
1976 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1977 if (result != null) {
1982 final int userId = UserHandle.getUserId(callingUid);
1983 final DevicePolicyData policy = getUserData(userId);
1984 ActiveAdmin admin = policy.mAdminMap.get(who);
1985 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1986 throw new SecurityException("Admin " + admin.info.getComponent()
1987 + " does not own the device");
1989 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1990 throw new SecurityException("Admin " + admin.info.getComponent()
1991 + " does not own the profile");
1993 throw new SecurityException("Admin " + admin.info.getComponent()
1994 + " did not specify uses-policy for: "
1995 + admin.info.getTagForPolicy(reqPolicy));
1997 throw new SecurityException("No active admin owned by uid "
1998 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
2002 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2003 throws SecurityException {
2005 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2006 "call APIs on the parent profile");
2008 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2009 return parent ? admin.getParentActiveAdmin() : admin;
2012 * Find the admin for the component and userId bit of the uid, then check
2013 * the admin's uid matches the uid.
2015 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2016 final int userId = UserHandle.getUserId(uid);
2017 final DevicePolicyData policy = getUserData(userId);
2018 ActiveAdmin admin = policy.mAdminMap.get(who);
2019 if (admin == null) {
2020 throw new SecurityException("No active admin " + who);
2022 if (admin.getUid() != uid) {
2023 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2028 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2030 // Try to find an admin which can use reqPolicy
2031 final int userId = UserHandle.getUserId(uid);
2032 final DevicePolicyData policy = getUserData(userId);
2034 ActiveAdmin admin = policy.mAdminMap.get(who);
2035 if (admin == null) {
2036 throw new SecurityException("No active admin " + who);
2038 if (admin.getUid() != uid) {
2039 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2041 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2045 for (ActiveAdmin admin : policy.mAdminList) {
2046 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2057 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2059 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2060 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2062 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2064 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2065 // DO always has the PO power.
2066 return ownsDevice || ownsProfile;
2068 return admin.info.usesPolicy(reqPolicy);
2072 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2073 sendAdminCommandLocked(admin, action, null);
2076 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2077 sendAdminCommandLocked(admin, action, null, result);
2081 * Send an update to one specific admin, get notified when that admin returns a result.
2083 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2084 BroadcastReceiver result) {
2085 Intent intent = new Intent(action);
2086 intent.setComponent(admin.info.getComponent());
2087 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2088 intent.putExtra("expiration", admin.passwordExpirationDate);
2090 if (adminExtras != null) {
2091 intent.putExtras(adminExtras);
2093 if (result != null) {
2094 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2095 null, result, mHandler, Activity.RESULT_OK, null, null);
2097 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2102 * Send an update to all admins of a user that enforce a specified policy.
2104 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2105 final DevicePolicyData policy = getUserData(userHandle);
2106 final int count = policy.mAdminList.size();
2108 for (int i = 0; i < count; i++) {
2109 final ActiveAdmin admin = policy.mAdminList.get(i);
2110 if (admin.info.usesPolicy(reqPolicy)) {
2111 sendAdminCommandLocked(admin, action);
2118 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2119 * enforce a specified policy.
2121 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2123 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2124 for (int profileId : profileIds) {
2125 sendAdminCommandLocked(action, reqPolicy, profileId);
2130 * Sends a broadcast to each profile that share the password unlock with the given user id.
2132 private void sendAdminCommandForLockscreenPoliciesLocked(
2133 String action, int reqPolicy, int userHandle) {
2134 if (isSeparateProfileChallengeEnabled(userHandle)) {
2135 sendAdminCommandLocked(action, reqPolicy, userHandle);
2137 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2141 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2142 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2143 DevicePolicyData policy = getUserData(userHandle);
2144 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2145 policy.mRemovingAdmins.add(adminReceiver);
2146 sendAdminCommandLocked(admin,
2147 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2148 new BroadcastReceiver() {
2150 public void onReceive(Context context, Intent intent) {
2151 removeAdminArtifacts(adminReceiver, userHandle);
2152 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2159 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2160 boolean throwForMissiongPermission) {
2164 enforceFullCrossUsersPermission(userHandle);
2165 ActivityInfo ai = null;
2167 ai = mIPackageManager.getReceiverInfo(adminName,
2168 PackageManager.GET_META_DATA |
2169 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2170 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2171 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2172 } catch (RemoteException e) {
2173 // shouldn't happen.
2176 throw new IllegalArgumentException("Unknown admin: " + adminName);
2179 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2180 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2181 + permission.BIND_DEVICE_ADMIN;
2182 Slog.w(LOG_TAG, message);
2183 if (throwForMissiongPermission &&
2184 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2185 throw new IllegalArgumentException(message);
2190 return new DeviceAdminInfo(mContext, ai);
2191 } catch (XmlPullParserException | IOException e) {
2192 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2198 private JournaledFile makeJournaledFile(int userHandle) {
2199 final String base = userHandle == UserHandle.USER_SYSTEM
2200 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2201 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2202 DEVICE_POLICIES_XML).getAbsolutePath();
2204 Log.v(LOG_TAG, "Opening " + base);
2206 return new JournaledFile(new File(base), new File(base + ".tmp"));
2209 private void saveSettingsLocked(int userHandle) {
2210 DevicePolicyData policy = getUserData(userHandle);
2211 JournaledFile journal = makeJournaledFile(userHandle);
2212 FileOutputStream stream = null;
2214 stream = new FileOutputStream(journal.chooseForWrite(), false);
2215 XmlSerializer out = new FastXmlSerializer();
2216 out.setOutput(stream, StandardCharsets.UTF_8.name());
2217 out.startDocument(null, true);
2219 out.startTag(null, "policies");
2220 if (policy.mRestrictionsProvider != null) {
2221 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2222 policy.mRestrictionsProvider.flattenToString());
2224 if (policy.mUserSetupComplete) {
2225 out.attribute(null, ATTR_SETUP_COMPLETE,
2226 Boolean.toString(true));
2228 if (policy.mPaired) {
2229 out.attribute(null, ATTR_DEVICE_PAIRED,
2230 Boolean.toString(true));
2232 if (policy.mDeviceProvisioningConfigApplied) {
2233 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2234 Boolean.toString(true));
2236 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2237 out.attribute(null, ATTR_PROVISIONING_STATE,
2238 Integer.toString(policy.mUserProvisioningState));
2240 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2241 out.attribute(null, ATTR_PERMISSION_POLICY,
2242 Integer.toString(policy.mPermissionPolicy));
2244 if (policy.mDelegatedCertInstallerPackage != null) {
2245 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2246 policy.mDelegatedCertInstallerPackage);
2248 if (policy.mApplicationRestrictionsManagingPackage != null) {
2249 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2250 policy.mApplicationRestrictionsManagingPackage);
2253 final int N = policy.mAdminList.size();
2254 for (int i=0; i<N; i++) {
2255 ActiveAdmin ap = policy.mAdminList.get(i);
2257 out.startTag(null, "admin");
2258 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2260 out.endTag(null, "admin");
2264 if (policy.mPasswordOwner >= 0) {
2265 out.startTag(null, "password-owner");
2266 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2267 out.endTag(null, "password-owner");
2270 if (policy.mFailedPasswordAttempts != 0) {
2271 out.startTag(null, "failed-password-attempts");
2272 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2273 out.endTag(null, "failed-password-attempts");
2276 // Don't save metrics for FBE devices
2277 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
2278 && (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2279 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2280 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2281 || policy.mActivePasswordSymbols != 0
2282 || policy.mActivePasswordNonLetter != 0)) {
2283 out.startTag(null, "active-password");
2284 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2285 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2286 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2287 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2288 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2289 out.attribute(null, "numeric", Integer
2290 .toString(policy.mActivePasswordNumeric));
2291 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2292 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2293 out.endTag(null, "active-password");
2296 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2297 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2298 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2299 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2302 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2303 String component = policy.mLockTaskPackages.get(i);
2304 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2305 out.attribute(null, "name", component);
2306 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2309 if (policy.mStatusBarDisabled) {
2310 out.startTag(null, TAG_STATUS_BAR);
2311 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2312 out.endTag(null, TAG_STATUS_BAR);
2315 if (policy.doNotAskCredentialsOnBoot) {
2316 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2317 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2320 for (String id : policy.mAffiliationIds) {
2321 out.startTag(null, TAG_AFFILIATION_ID);
2322 out.attribute(null, "id", id);
2323 out.endTag(null, TAG_AFFILIATION_ID);
2326 if (policy.mAdminBroadcastPending) {
2327 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2328 out.attribute(null, ATTR_VALUE,
2329 Boolean.toString(policy.mAdminBroadcastPending));
2330 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2333 if (policy.mInitBundle != null) {
2334 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2335 policy.mInitBundle.saveToXml(out);
2336 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2339 out.endTag(null, "policies");
2343 FileUtils.sync(stream);
2346 sendChangedNotification(userHandle);
2347 } catch (XmlPullParserException | IOException e) {
2348 Slog.w(LOG_TAG, "failed writing file", e);
2350 if (stream != null) {
2353 } catch (IOException ex) {
2360 private void sendChangedNotification(int userHandle) {
2361 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2362 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2363 long ident = mInjector.binderClearCallingIdentity();
2365 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2367 mInjector.binderRestoreCallingIdentity(ident);
2371 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2372 JournaledFile journal = makeJournaledFile(userHandle);
2373 FileInputStream stream = null;
2374 File file = journal.chooseForRead();
2375 boolean needsRewrite = false;
2377 stream = new FileInputStream(file);
2378 XmlPullParser parser = Xml.newPullParser();
2379 parser.setInput(stream, StandardCharsets.UTF_8.name());
2382 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2383 && type != XmlPullParser.START_TAG) {
2385 String tag = parser.getName();
2386 if (!"policies".equals(tag)) {
2387 throw new XmlPullParserException(
2388 "Settings do not start with policies tag: found " + tag);
2391 // Extract the permission provider component name if available
2392 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2393 if (permissionProvider != null) {
2394 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2396 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2397 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2398 policy.mUserSetupComplete = true;
2400 String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
2401 if (paired != null && Boolean.toString(true).equals(paired)) {
2402 policy.mPaired = true;
2404 String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2405 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2406 if (deviceProvisioningConfigApplied != null
2407 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2408 policy.mDeviceProvisioningConfigApplied = true;
2410 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2411 if (!TextUtils.isEmpty(provisioningState)) {
2412 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2414 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2415 if (!TextUtils.isEmpty(permissionPolicy)) {
2416 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2418 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2419 ATTR_DELEGATED_CERT_INSTALLER);
2420 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2421 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2423 type = parser.next();
2424 int outerDepth = parser.getDepth();
2425 policy.mLockTaskPackages.clear();
2426 policy.mAdminList.clear();
2427 policy.mAdminMap.clear();
2428 policy.mAffiliationIds.clear();
2429 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2430 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2431 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2434 tag = parser.getName();
2435 if ("admin".equals(tag)) {
2436 String name = parser.getAttributeValue(null, "name");
2438 DeviceAdminInfo dai = findAdmin(
2439 ComponentName.unflattenFromString(name), userHandle,
2440 /* throwForMissionPermission= */ false);
2442 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2444 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2445 + dai.getActivityInfo().applicationInfo.uid + " for user "
2449 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2450 ap.readFromXml(parser);
2451 policy.mAdminMap.put(ap.info.getComponent(), ap);
2453 } catch (RuntimeException e) {
2454 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2456 } else if ("failed-password-attempts".equals(tag)) {
2457 policy.mFailedPasswordAttempts = Integer.parseInt(
2458 parser.getAttributeValue(null, "value"));
2459 } else if ("password-owner".equals(tag)) {
2460 policy.mPasswordOwner = Integer.parseInt(
2461 parser.getAttributeValue(null, "value"));
2462 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2463 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2464 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2465 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2466 } else if (TAG_STATUS_BAR.equals(tag)) {
2467 policy.mStatusBarDisabled = Boolean.parseBoolean(
2468 parser.getAttributeValue(null, ATTR_DISABLED));
2469 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2470 policy.doNotAskCredentialsOnBoot = true;
2471 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2472 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2473 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2474 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2475 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2476 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2477 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2478 } else if ("active-password".equals(tag)) {
2479 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2480 // Remove this from FBE devices
2481 needsRewrite = true;
2483 policy.mActivePasswordQuality = Integer.parseInt(
2484 parser.getAttributeValue(null, "quality"));
2485 policy.mActivePasswordLength = Integer.parseInt(
2486 parser.getAttributeValue(null, "length"));
2487 policy.mActivePasswordUpperCase = Integer.parseInt(
2488 parser.getAttributeValue(null, "uppercase"));
2489 policy.mActivePasswordLowerCase = Integer.parseInt(
2490 parser.getAttributeValue(null, "lowercase"));
2491 policy.mActivePasswordLetters = Integer.parseInt(
2492 parser.getAttributeValue(null, "letters"));
2493 policy.mActivePasswordNumeric = Integer.parseInt(
2494 parser.getAttributeValue(null, "numeric"));
2495 policy.mActivePasswordSymbols = Integer.parseInt(
2496 parser.getAttributeValue(null, "symbols"));
2497 policy.mActivePasswordNonLetter = Integer.parseInt(
2498 parser.getAttributeValue(null, "nonletter"));
2501 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2502 XmlUtils.skipCurrentTag(parser);
2505 } catch (FileNotFoundException e) {
2506 // Don't be noisy, this is normal if we haven't defined any policies.
2507 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2508 | IndexOutOfBoundsException e) {
2509 Slog.w(LOG_TAG, "failed parsing " + file, e);
2512 if (stream != null) {
2515 } catch (IOException e) {
2519 // Generate a list of admins from the admin map
2520 policy.mAdminList.addAll(policy.mAdminMap.values());
2522 // Might need to upgrade the file by rewriting it
2524 saveSettingsLocked(userHandle);
2527 validatePasswordOwnerLocked(policy);
2528 updateMaximumTimeToLockLocked(userHandle);
2529 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2530 if (policy.mStatusBarDisabled) {
2531 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2535 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2536 long ident = mInjector.binderClearCallingIdentity();
2538 mInjector.getIActivityManager()
2539 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2540 } catch (RemoteException e) {
2541 // Not gonna happen.
2543 mInjector.binderRestoreCallingIdentity(ident);
2547 private void updateDeviceOwnerLocked() {
2548 long ident = mInjector.binderClearCallingIdentity();
2550 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2551 // user id and also protect all other DAs too.
2552 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2553 if (deviceOwnerComponent != null) {
2554 mInjector.getIActivityManager()
2555 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2557 } catch (RemoteException e) {
2558 // Not gonna happen.
2560 mInjector.binderRestoreCallingIdentity(ident);
2564 static void validateQualityConstant(int quality) {
2566 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2567 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2568 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2569 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2570 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2571 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2572 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2573 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2574 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2577 throw new IllegalArgumentException("Invalid quality constant: 0x"
2578 + Integer.toHexString(quality));
2581 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2582 if (policy.mPasswordOwner >= 0) {
2583 boolean haveOwner = false;
2584 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2585 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2591 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2592 + " no longer active; disabling");
2593 policy.mPasswordOwner = -1;
2599 void systemReady(int phase) {
2604 case SystemService.PHASE_LOCK_SETTINGS_READY:
2605 onLockSettingsReady();
2607 case SystemService.PHASE_BOOT_COMPLETED:
2608 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2613 private void onLockSettingsReady() {
2614 getUserData(UserHandle.USER_SYSTEM);
2618 onStartUser(UserHandle.USER_SYSTEM);
2620 // Register an observer for watching for user setup complete.
2621 new SetupContentObserver(mHandler).register();
2622 // Initialize the user setup state, to handle the upgrade case.
2623 updateUserSetupCompleteAndPaired();
2625 List<String> packageList;
2626 synchronized (this) {
2627 packageList = getKeepUninstalledPackagesLocked();
2629 if (packageList != null) {
2630 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2633 synchronized (this) {
2634 // push the force-ephemeral-users policy to the user manager.
2635 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2636 if (deviceOwner != null) {
2637 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2642 private void ensureDeviceOwnerUserStarted() {
2644 synchronized (this) {
2645 if (!mOwners.hasDeviceOwner()) {
2648 userId = mOwners.getDeviceOwnerUserId();
2651 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2653 if (userId != UserHandle.USER_SYSTEM) {
2655 mInjector.getIActivityManager().startUserInBackground(userId);
2657 // STOPSHIP Prevent the DO user from being killed.
2659 } catch (RemoteException e) {
2660 Slog.w(LOG_TAG, "Exception starting user", e);
2665 private void onStartUser(int userId) {
2666 updateScreenCaptureDisabledInWindowManager(userId,
2667 getScreenCaptureDisabled(null, userId));
2668 pushUserRestrictions(userId);
2671 private void cleanUpOldUsers() {
2672 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2674 Set<Integer> usersWithProfileOwners;
2675 Set<Integer> usersWithData;
2676 synchronized(this) {
2677 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2678 usersWithData = new ArraySet<>();
2679 for (int i = 0; i < mUserData.size(); i++) {
2680 usersWithData.add(mUserData.keyAt(i));
2683 List<UserInfo> allUsers = mUserManager.getUsers();
2685 Set<Integer> deletedUsers = new ArraySet<>();
2686 deletedUsers.addAll(usersWithProfileOwners);
2687 deletedUsers.addAll(usersWithData);
2688 for (UserInfo userInfo : allUsers) {
2689 deletedUsers.remove(userInfo.id);
2691 for (Integer userId : deletedUsers) {
2692 removeUserData(userId);
2696 private void handlePasswordExpirationNotification(int userHandle) {
2697 synchronized (this) {
2698 final long now = System.currentTimeMillis();
2700 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2701 userHandle, /* parent */ false);
2702 final int N = admins.size();
2703 for (int i = 0; i < N; i++) {
2704 ActiveAdmin admin = admins.get(i);
2705 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2706 && admin.passwordExpirationTimeout > 0L
2707 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2708 && admin.passwordExpirationDate > 0L) {
2709 sendAdminCommandLocked(admin,
2710 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2713 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2717 private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2719 protected Void doInBackground(Integer... params) {
2720 int userHandle = params[0];
2722 if (userHandle == UserHandle.USER_ALL) {
2723 for (UserInfo userInfo : mUserManager.getUsers(true)) {
2724 manageNotification(userInfo.getUserHandle());
2727 manageNotification(UserHandle.of(userHandle));
2732 private void manageNotification(UserHandle userHandle) {
2733 if (!mUserManager.isUserUnlocked(userHandle)) {
2737 // Call out to KeyChain to check for CAs which are waiting for approval.
2738 final List<String> pendingCertificates;
2740 pendingCertificates = getInstalledCaCertificates(userHandle);
2741 } catch (RemoteException | RuntimeException e) {
2742 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2746 synchronized (DevicePolicyManagerService.this) {
2747 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2749 // Remove deleted certificates. Flush xml if necessary.
2750 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2751 saveSettingsLocked(userHandle.getIdentifier());
2753 // Trim to approved certificates.
2754 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2757 if (pendingCertificates.isEmpty()) {
2758 mInjector.getNotificationManager().cancelAsUser(
2759 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2763 // Build and show a warning notification
2766 int parentUserId = userHandle.getIdentifier();
2767 if (getProfileOwner(userHandle.getIdentifier()) != null) {
2768 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2769 getProfileOwnerName(userHandle.getIdentifier()));
2770 smallIconId = R.drawable.stat_sys_certificate_info;
2771 parentUserId = getProfileParentId(userHandle.getIdentifier());
2772 } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
2773 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2774 getDeviceOwnerName());
2775 smallIconId = R.drawable.stat_sys_certificate_info;
2777 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2778 smallIconId = android.R.drawable.stat_sys_warning;
2781 final int numberOfCertificates = pendingCertificates.size();
2782 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2783 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2784 dialogIntent.setPackage("com.android.settings");
2785 dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
2786 dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
2787 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2788 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
2789 new UserHandle(parentUserId));
2791 final Context userContext;
2793 final String packageName = mContext.getPackageName();
2794 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
2795 } catch (PackageManager.NameNotFoundException e) {
2796 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2799 final Notification noti = new Notification.Builder(userContext)
2800 .setSmallIcon(smallIconId)
2801 .setContentTitle(mContext.getResources().getQuantityText(
2802 R.plurals.ssl_ca_cert_warning, numberOfCertificates))
2803 .setContentText(contentText)
2804 .setContentIntent(notifyIntent)
2805 .setPriority(Notification.PRIORITY_HIGH)
2807 .setColor(mContext.getColor(
2808 com.android.internal.R.color.system_notification_accent_color))
2811 mInjector.getNotificationManager().notifyAsUser(
2812 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2815 private List<String> getInstalledCaCertificates(UserHandle userHandle)
2816 throws RemoteException, RuntimeException {
2817 KeyChainConnection conn = null;
2819 conn = KeyChain.bindAsUser(mContext, userHandle);
2820 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
2821 List<String> result = new ArrayList<>(aliases.size());
2822 for (int i = 0; i < aliases.size(); i++) {
2823 result.add(aliases.get(i).string);
2826 } catch (InterruptedException e) {
2827 Thread.currentThread().interrupt();
2829 } catch (AssertionError e) {
2830 throw new RuntimeException(e);
2840 * @param adminReceiver The admin to add
2841 * @param refreshing true = update an active admin, no error
2844 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2848 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2851 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2852 Bundle onEnableData) {
2853 mContext.enforceCallingOrSelfPermission(
2854 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2855 enforceFullCrossUsersPermission(userHandle);
2857 DevicePolicyData policy = getUserData(userHandle);
2858 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2859 /* throwForMissionPermission= */ true);
2861 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2863 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2864 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2867 synchronized (this) {
2868 long ident = mInjector.binderClearCallingIdentity();
2870 final ActiveAdmin existingAdmin
2871 = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2872 if (!refreshing && existingAdmin != null) {
2873 throw new IllegalArgumentException("Admin is already added");
2875 if (policy.mRemovingAdmins.contains(adminReceiver)) {
2876 throw new IllegalArgumentException(
2877 "Trying to set an admin which is being removed");
2879 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2880 newAdmin.testOnlyAdmin =
2881 (existingAdmin != null) ? existingAdmin.testOnlyAdmin
2882 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
2883 policy.mAdminMap.put(adminReceiver, newAdmin);
2884 int replaceIndex = -1;
2885 final int N = policy.mAdminList.size();
2886 for (int i=0; i < N; i++) {
2887 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2888 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2893 if (replaceIndex == -1) {
2894 policy.mAdminList.add(newAdmin);
2895 enableIfNecessary(info.getPackageName(), userHandle);
2897 policy.mAdminList.set(replaceIndex, newAdmin);
2899 saveSettingsLocked(userHandle);
2900 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2901 onEnableData, null);
2903 mInjector.binderRestoreCallingIdentity(ident);
2909 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2913 enforceFullCrossUsersPermission(userHandle);
2914 synchronized (this) {
2915 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2920 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2924 enforceFullCrossUsersPermission(userHandle);
2925 synchronized (this) {
2926 DevicePolicyData policyData = getUserData(userHandle);
2927 return policyData.mRemovingAdmins.contains(adminReceiver);
2932 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2936 enforceFullCrossUsersPermission(userHandle);
2937 synchronized (this) {
2938 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2939 if (administrator == null) {
2940 throw new SecurityException("No active admin " + adminReceiver);
2942 return administrator.info.usesPolicy(policyId);
2947 @SuppressWarnings("unchecked")
2948 public List<ComponentName> getActiveAdmins(int userHandle) {
2950 return Collections.EMPTY_LIST;
2953 enforceFullCrossUsersPermission(userHandle);
2954 synchronized (this) {
2955 DevicePolicyData policy = getUserData(userHandle);
2956 final int N = policy.mAdminList.size();
2960 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2961 for (int i=0; i<N; i++) {
2962 res.add(policy.mAdminList.get(i).info.getComponent());
2969 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2973 enforceFullCrossUsersPermission(userHandle);
2974 synchronized (this) {
2975 DevicePolicyData policy = getUserData(userHandle);
2976 final int N = policy.mAdminList.size();
2977 for (int i=0; i<N; i++) {
2978 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2986 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
2990 Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
2991 enforceShell("forceRemoveActiveAdmin");
2992 long ident = mInjector.binderClearCallingIdentity();
2994 synchronized (this) {
2995 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
2996 throw new SecurityException("Attempt to remove non-test admin "
2997 + adminReceiver + " " + userHandle);
3000 // If admin is a device or profile owner tidy that up first.
3001 if (isDeviceOwner(adminReceiver, userHandle)) {
3002 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3004 if (isProfileOwner(adminReceiver, userHandle)) {
3005 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3006 userHandle, /* parent */ false);
3007 clearProfileOwnerLocked(admin, userHandle);
3010 // Remove the admin skipping sending the broadcast.
3011 removeAdminArtifacts(adminReceiver, userHandle);
3012 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3014 mInjector.binderRestoreCallingIdentity(ident);
3019 * Return if a given package has testOnly="true", in which case we'll relax certain rules
3022 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked}
3023 * to check wehter an active admin is test-only or not.
3025 * The system allows this flag to be changed when an app is updated, which is not good
3026 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3027 * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3029 private boolean isPackageTestOnly(String packageName, int userHandle) {
3030 final ApplicationInfo ai;
3032 ai = mIPackageManager.getApplicationInfo(packageName,
3033 (PackageManager.MATCH_DIRECT_BOOT_AWARE
3034 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3035 } catch (RemoteException e) {
3036 throw new IllegalStateException(e);
3039 throw new IllegalStateException("Couldn't find package: "
3040 + packageName + " on user " + userHandle);
3042 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3046 * See {@link #isPackageTestOnly}.
3048 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3049 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3050 return (admin != null) && admin.testOnlyAdmin;
3053 private void enforceShell(String method) {
3054 final int callingUid = Binder.getCallingUid();
3055 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3056 throw new SecurityException("Non-shell user attempted to call " + method);
3061 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3065 enforceFullCrossUsersPermission(userHandle);
3066 enforceUserUnlocked(userHandle);
3067 synchronized (this) {
3068 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3069 if (admin == null) {
3072 // Active device/profile owners must remain active admins.
3073 if (isDeviceOwner(adminReceiver, userHandle)
3074 || isProfileOwner(adminReceiver, userHandle)) {
3075 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3079 if (admin.getUid() != mInjector.binderGetCallingUid()) {
3080 mContext.enforceCallingOrSelfPermission(
3081 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3083 long ident = mInjector.binderClearCallingIdentity();
3085 removeActiveAdminLocked(adminReceiver, userHandle);
3087 mInjector.binderRestoreCallingIdentity(ident);
3093 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3094 ComponentName profileOwner = getProfileOwner(userHandle);
3095 // Profile challenge is supported on N or newer release.
3096 return profileOwner != null &&
3097 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3101 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3105 Preconditions.checkNotNull(who, "ComponentName is null");
3106 validateQualityConstant(quality);
3108 synchronized (this) {
3109 ActiveAdmin ap = getActiveAdminForCallerLocked(
3110 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3111 if (ap.passwordQuality != quality) {
3112 ap.passwordQuality = quality;
3113 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3119 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3121 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3123 enforceFullCrossUsersPermission(userHandle);
3124 synchronized (this) {
3125 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3128 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3129 return admin != null ? admin.passwordQuality : mode;
3132 // Return the strictest policy across all participating admins.
3133 List<ActiveAdmin> admins =
3134 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3135 final int N = admins.size();
3136 for (int i = 0; i < N; i++) {
3137 ActiveAdmin admin = admins.get(i);
3138 if (mode < admin.passwordQuality) {
3139 mode = admin.passwordQuality;
3146 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3147 int userHandle, boolean parent) {
3148 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3149 // If this user has a separate challenge, only return its restrictions.
3150 return getUserDataUnchecked(userHandle).mAdminList;
3152 // Return all admins for this user and the profiles that are visible from this
3153 // user that do not use a separate work challenge.
3154 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3155 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3156 DevicePolicyData policy = getUserData(userInfo.id);
3157 if (!userInfo.isManagedProfile()) {
3158 admins.addAll(policy.mAdminList);
3160 // For managed profiles, we always include the policies set on the parent
3161 // profile. Additionally, we include the ones set on the managed profile
3162 // if no separate challenge is in place.
3163 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3164 final int N = policy.mAdminList.size();
3165 for (int i = 0; i < N; i++) {
3166 ActiveAdmin admin = policy.mAdminList.get(i);
3167 if (admin.hasParentActiveAdmin()) {
3168 admins.add(admin.getParentActiveAdmin());
3170 if (!hasSeparateChallenge) {
3180 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3181 long ident = mInjector.binderClearCallingIdentity();
3183 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3185 mInjector.binderRestoreCallingIdentity(ident);
3190 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3194 Preconditions.checkNotNull(who, "ComponentName is null");
3195 synchronized (this) {
3196 ActiveAdmin ap = getActiveAdminForCallerLocked(
3197 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3198 if (ap.minimumPasswordLength != length) {
3199 ap.minimumPasswordLength = length;
3200 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3206 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3210 enforceFullCrossUsersPermission(userHandle);
3211 synchronized (this) {
3215 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3216 return admin != null ? admin.minimumPasswordLength : length;
3219 // Return the strictest policy across all participating admins.
3220 List<ActiveAdmin> admins =
3221 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3222 final int N = admins.size();
3223 for (int i = 0; i < N; i++) {
3224 ActiveAdmin admin = admins.get(i);
3225 if (length < admin.minimumPasswordLength) {
3226 length = admin.minimumPasswordLength;
3234 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3238 Preconditions.checkNotNull(who, "ComponentName is null");
3239 synchronized (this) {
3240 ActiveAdmin ap = getActiveAdminForCallerLocked(
3241 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3242 if (ap.passwordHistoryLength != length) {
3243 ap.passwordHistoryLength = length;
3244 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3250 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3254 enforceFullCrossUsersPermission(userHandle);
3255 synchronized (this) {
3259 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3260 return admin != null ? admin.passwordHistoryLength : length;
3263 // Return the strictest policy across all participating admins.
3264 List<ActiveAdmin> admins =
3265 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3266 final int N = admins.size();
3267 for (int i = 0; i < N; i++) {
3268 ActiveAdmin admin = admins.get(i);
3269 if (length < admin.passwordHistoryLength) {
3270 length = admin.passwordHistoryLength;
3279 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3283 Preconditions.checkNotNull(who, "ComponentName is null");
3284 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3285 final int userHandle = mInjector.userHandleGetCallingUserId();
3286 synchronized (this) {
3287 ActiveAdmin ap = getActiveAdminForCallerLocked(
3288 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3289 // Calling this API automatically bumps the expiration date
3290 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3291 ap.passwordExpirationDate = expiration;
3292 ap.passwordExpirationTimeout = timeout;
3294 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3295 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3296 .format(new Date(expiration)));
3298 saveSettingsLocked(userHandle);
3300 // in case this is the first one, set the alarm on the appropriate user.
3301 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3306 * Return a single admin's expiration cycle time, or the min of all cycle times.
3307 * Returns 0 if not configured.
3310 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3314 enforceFullCrossUsersPermission(userHandle);
3315 synchronized (this) {
3319 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3320 return admin != null ? admin.passwordExpirationTimeout : timeout;
3323 // Return the strictest policy across all participating admins.
3324 List<ActiveAdmin> admins =
3325 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3326 final int N = admins.size();
3327 for (int i = 0; i < N; i++) {
3328 ActiveAdmin admin = admins.get(i);
3329 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3330 && timeout > admin.passwordExpirationTimeout)) {
3331 timeout = admin.passwordExpirationTimeout;
3339 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3340 final int userId = UserHandle.getCallingUserId();
3341 List<String> changedProviders = null;
3343 synchronized (this) {
3344 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3345 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3346 if (activeAdmin.crossProfileWidgetProviders == null) {
3347 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3349 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3350 if (!providers.contains(packageName)) {
3351 providers.add(packageName);
3352 changedProviders = new ArrayList<>(providers);
3353 saveSettingsLocked(userId);
3357 if (changedProviders != null) {
3358 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3366 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3367 final int userId = UserHandle.getCallingUserId();
3368 List<String> changedProviders = null;
3370 synchronized (this) {
3371 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3372 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3373 if (activeAdmin.crossProfileWidgetProviders == null) {
3376 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3377 if (providers.remove(packageName)) {
3378 changedProviders = new ArrayList<>(providers);
3379 saveSettingsLocked(userId);
3383 if (changedProviders != null) {
3384 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3392 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3393 synchronized (this) {
3394 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3395 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3396 if (activeAdmin.crossProfileWidgetProviders == null
3397 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3400 if (mInjector.binderIsCallingUidMyUid()) {
3401 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3403 return activeAdmin.crossProfileWidgetProviders;
3409 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3410 * Returns 0 if not configured.
3412 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3416 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3417 return admin != null ? admin.passwordExpirationDate : timeout;
3420 // Return the strictest policy across all participating admins.
3421 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3422 final int N = admins.size();
3423 for (int i = 0; i < N; i++) {
3424 ActiveAdmin admin = admins.get(i);
3425 if (timeout == 0L || (admin.passwordExpirationDate != 0
3426 && timeout > admin.passwordExpirationDate)) {
3427 timeout = admin.passwordExpirationDate;
3434 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3438 enforceFullCrossUsersPermission(userHandle);
3439 synchronized (this) {
3440 return getPasswordExpirationLocked(who, userHandle, parent);
3445 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3449 Preconditions.checkNotNull(who, "ComponentName is null");
3450 synchronized (this) {
3451 ActiveAdmin ap = getActiveAdminForCallerLocked(
3452 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3453 if (ap.minimumPasswordUpperCase != length) {
3454 ap.minimumPasswordUpperCase = length;
3455 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3461 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3465 enforceFullCrossUsersPermission(userHandle);
3466 synchronized (this) {
3470 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3471 return admin != null ? admin.minimumPasswordUpperCase : length;
3474 // Return the strictest policy across all participating admins.
3475 List<ActiveAdmin> admins =
3476 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3477 final int N = admins.size();
3478 for (int i = 0; i < N; i++) {
3479 ActiveAdmin admin = admins.get(i);
3480 if (length < admin.minimumPasswordUpperCase) {
3481 length = admin.minimumPasswordUpperCase;
3489 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3490 Preconditions.checkNotNull(who, "ComponentName is null");
3491 synchronized (this) {
3492 ActiveAdmin ap = getActiveAdminForCallerLocked(
3493 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3494 if (ap.minimumPasswordLowerCase != length) {
3495 ap.minimumPasswordLowerCase = length;
3496 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3502 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3506 enforceFullCrossUsersPermission(userHandle);
3507 synchronized (this) {
3511 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3512 return admin != null ? admin.minimumPasswordLowerCase : length;
3515 // Return the strictest policy across all participating admins.
3516 List<ActiveAdmin> admins =
3517 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3518 final int N = admins.size();
3519 for (int i = 0; i < N; i++) {
3520 ActiveAdmin admin = admins.get(i);
3521 if (length < admin.minimumPasswordLowerCase) {
3522 length = admin.minimumPasswordLowerCase;
3530 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3534 Preconditions.checkNotNull(who, "ComponentName is null");
3535 synchronized (this) {
3536 ActiveAdmin ap = getActiveAdminForCallerLocked(
3537 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3538 if (ap.minimumPasswordLetters != length) {
3539 ap.minimumPasswordLetters = length;
3540 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3546 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3550 enforceFullCrossUsersPermission(userHandle);
3551 synchronized (this) {
3555 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3556 return admin != null ? admin.minimumPasswordLetters : length;
3559 // Return the strictest policy across all participating admins.
3560 List<ActiveAdmin> admins =
3561 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3562 final int N = admins.size();
3563 for (int i = 0; i < N; i++) {
3564 ActiveAdmin admin = admins.get(i);
3565 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3568 if (length < admin.minimumPasswordLetters) {
3569 length = admin.minimumPasswordLetters;
3577 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3581 Preconditions.checkNotNull(who, "ComponentName is null");
3582 synchronized (this) {
3583 ActiveAdmin ap = getActiveAdminForCallerLocked(
3584 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3585 if (ap.minimumPasswordNumeric != length) {
3586 ap.minimumPasswordNumeric = length;
3587 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3593 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3597 enforceFullCrossUsersPermission(userHandle);
3598 synchronized (this) {
3602 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3603 return admin != null ? admin.minimumPasswordNumeric : length;
3606 // Return the strictest policy across all participating admins.
3607 List<ActiveAdmin> admins =
3608 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3609 final int N = admins.size();
3610 for (int i = 0; i < N; i++) {
3611 ActiveAdmin admin = admins.get(i);
3612 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3615 if (length < admin.minimumPasswordNumeric) {
3616 length = admin.minimumPasswordNumeric;
3624 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3628 Preconditions.checkNotNull(who, "ComponentName is null");
3629 synchronized (this) {
3630 ActiveAdmin ap = getActiveAdminForCallerLocked(
3631 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3632 if (ap.minimumPasswordSymbols != length) {
3633 ap.minimumPasswordSymbols = length;
3634 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3640 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3644 enforceFullCrossUsersPermission(userHandle);
3645 synchronized (this) {
3649 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3650 return admin != null ? admin.minimumPasswordSymbols : length;
3653 // Return the strictest policy across all participating admins.
3654 List<ActiveAdmin> admins =
3655 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3656 final int N = admins.size();
3657 for (int i = 0; i < N; i++) {
3658 ActiveAdmin admin = admins.get(i);
3659 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3662 if (length < admin.minimumPasswordSymbols) {
3663 length = admin.minimumPasswordSymbols;
3671 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3675 Preconditions.checkNotNull(who, "ComponentName is null");
3676 synchronized (this) {
3677 ActiveAdmin ap = getActiveAdminForCallerLocked(
3678 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3679 if (ap.minimumPasswordNonLetter != length) {
3680 ap.minimumPasswordNonLetter = length;
3681 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3687 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3691 enforceFullCrossUsersPermission(userHandle);
3692 synchronized (this) {
3696 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3697 return admin != null ? admin.minimumPasswordNonLetter : length;
3700 // Return the strictest policy across all participating admins.
3701 List<ActiveAdmin> admins =
3702 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3703 final int N = admins.size();
3704 for (int i = 0; i < N; i++) {
3705 ActiveAdmin admin = admins.get(i);
3706 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3709 if (length < admin.minimumPasswordNonLetter) {
3710 length = admin.minimumPasswordNonLetter;
3718 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3722 enforceFullCrossUsersPermission(userHandle);
3724 synchronized (this) {
3725 // This API can only be called by an active device admin,
3726 // so try to retrieve it to check that the caller is one.
3727 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3728 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3729 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3734 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3738 enforceFullCrossUsersPermission(userHandle);
3739 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3741 synchronized (this) {
3742 int targetUser = getProfileParentId(userHandle);
3743 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3744 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3748 private boolean isActivePasswordSufficientForUserLocked(
3749 DevicePolicyData policy, int userHandle, boolean parent) {
3750 enforceUserUnlocked(userHandle, parent);
3752 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
3753 if (policy.mActivePasswordQuality < requiredPasswordQuality) {
3756 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
3757 && policy.mActivePasswordLength < getPasswordMinimumLength(
3758 null, userHandle, parent)) {
3761 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3764 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3765 null, userHandle, parent)
3766 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3767 null, userHandle, parent)
3768 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3769 null, userHandle, parent)
3770 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3771 null, userHandle, parent)
3772 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3773 null, userHandle, parent)
3774 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3775 null, userHandle, parent);
3779 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3780 enforceFullCrossUsersPermission(userHandle);
3781 synchronized (this) {
3782 if (!isCallerWithSystemUid()) {
3783 // This API can only be called by an active device admin,
3784 // so try to retrieve it to check that the caller is one.
3785 getActiveAdminForCallerLocked(
3786 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3789 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3791 return policy.mFailedPasswordAttempts;
3796 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3800 Preconditions.checkNotNull(who, "ComponentName is null");
3801 synchronized (this) {
3802 // This API can only be called by an active device admin,
3803 // so try to retrieve it to check that the caller is one.
3804 getActiveAdminForCallerLocked(
3805 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3806 ActiveAdmin ap = getActiveAdminForCallerLocked(
3807 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3808 if (ap.maximumFailedPasswordsForWipe != num) {
3809 ap.maximumFailedPasswordsForWipe = num;
3810 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3816 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3820 enforceFullCrossUsersPermission(userHandle);
3821 synchronized (this) {
3822 ActiveAdmin admin = (who != null)
3823 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3824 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3825 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3830 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3832 return UserHandle.USER_NULL;
3834 enforceFullCrossUsersPermission(userHandle);
3835 synchronized (this) {
3836 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3837 userHandle, parent);
3838 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3843 * Returns the admin with the strictest policy on maximum failed passwords for:
3845 * <li>this user if it has a separate profile challenge, or
3846 * <li>this user and all profiles that don't have their own challenge otherwise.
3848 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3849 * the primary profile.
3850 * Returns {@code null} if no participating admin has that policy set.
3852 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3853 int userHandle, boolean parent) {
3855 ActiveAdmin strictestAdmin = null;
3857 // Return the strictest policy across all participating admins.
3858 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3859 final int N = admins.size();
3860 for (int i = 0; i < N; i++) {
3861 ActiveAdmin admin = admins.get(i);
3862 if (admin.maximumFailedPasswordsForWipe ==
3863 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3864 continue; // No max number of failed passwords policy set for this profile.
3867 // We always favor the primary profile if several profiles have the same value set.
3868 int userId = admin.getUserHandle().getIdentifier();
3870 count > admin.maximumFailedPasswordsForWipe ||
3871 (count == admin.maximumFailedPasswordsForWipe &&
3872 getUserInfo(userId).isPrimary())) {
3873 count = admin.maximumFailedPasswordsForWipe;
3874 strictestAdmin = admin;
3877 return strictestAdmin;
3880 private UserInfo getUserInfo(@UserIdInt int userId) {
3881 final long token = mInjector.binderClearCallingIdentity();
3883 return mUserManager.getUserInfo(userId);
3885 mInjector.binderRestoreCallingIdentity(token);
3890 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3894 final int callingUid = mInjector.binderGetCallingUid();
3895 final int userHandle = mInjector.userHandleGetCallingUserId();
3897 String password = passwordOrNull != null ? passwordOrNull : "";
3899 // Password resetting to empty/null is not allowed for managed profiles.
3900 if (TextUtils.isEmpty(password)) {
3901 enforceNotManagedProfile(userHandle, "clear the active password");
3905 synchronized (this) {
3906 // If caller has PO (or DO) it can change the password, so see if that's the case first.
3907 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3908 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3910 if (admin != null) {
3911 preN = getTargetSdk(admin.info.getPackageName(),
3912 userHandle) <= android.os.Build.VERSION_CODES.M;
3914 // Otherwise, make sure the caller has any active admin with the right policy.
3915 admin = getActiveAdminForCallerLocked(null,
3916 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3917 preN = getTargetSdk(admin.info.getPackageName(),
3918 userHandle) <= android.os.Build.VERSION_CODES.M;
3920 // As of N, password resetting to empty/null is not allowed anymore.
3921 // TODO Should we allow DO/PO to set an empty password?
3922 if (TextUtils.isEmpty(password)) {
3924 throw new SecurityException("Cannot call with null password");
3926 Slog.e(LOG_TAG, "Cannot call with null password");
3930 // As of N, password cannot be changed by the admin if it is already set.
3931 if (isLockScreenSecureUnchecked(userHandle)) {
3933 throw new SecurityException("Admin cannot change current password");
3935 Slog.e(LOG_TAG, "Admin cannot change current password");
3940 // Do not allow to reset password when current user has a managed profile
3941 if (!isManagedProfile(userHandle)) {
3942 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3943 if (userInfo.isManagedProfile()) {
3945 throw new IllegalStateException(
3946 "Cannot reset password on user has managed profile");
3948 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
3954 // Do not allow to reset password when user is locked
3955 if (!mUserManager.isUserUnlocked(userHandle)) {
3957 throw new IllegalStateException("Cannot reset password when user is locked");
3959 Slog.e(LOG_TAG, "Cannot reset password when user is locked");
3964 quality = getPasswordQuality(null, userHandle, /* parent */ false);
3965 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
3966 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3968 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
3969 int realQuality = LockPatternUtils.computePasswordQuality(password);
3970 if (realQuality < quality
3971 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3972 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
3973 + Integer.toHexString(realQuality)
3974 + " does not meet required quality 0x"
3975 + Integer.toHexString(quality));
3978 quality = Math.max(realQuality, quality);
3980 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
3981 if (password.length() < length) {
3982 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
3983 + " does not meet required length " + length);
3986 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3993 for (int i = 0; i < password.length(); i++) {
3994 char c = password.charAt(i);
3995 if (c >= 'A' && c <= 'Z') {
3998 } else if (c >= 'a' && c <= 'z') {
4001 } else if (c >= '0' && c <= '9') {
4009 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4010 if(letters < neededLetters) {
4011 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
4012 + " does not meet required number of letters " + neededLetters);
4015 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4016 if (numbers < neededNumbers) {
4017 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
4018 + " does not meet required number of numerical digits "
4022 int neededLowerCase = getPasswordMinimumLowerCase(
4023 null, userHandle, /* parent */ false);
4024 if (lowercase < neededLowerCase) {
4025 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
4026 + " does not meet required number of lowercase letters "
4030 int neededUpperCase = getPasswordMinimumUpperCase(
4031 null, userHandle, /* parent */ false);
4032 if (uppercase < neededUpperCase) {
4033 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
4034 + " does not meet required number of uppercase letters "
4038 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4039 if (symbols < neededSymbols) {
4040 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
4041 + " does not meet required number of special symbols " + neededSymbols);
4044 int neededNonLetter = getPasswordMinimumNonLetter(
4045 null, userHandle, /* parent */ false);
4046 if (nonletter < neededNonLetter) {
4047 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
4048 + " does not meet required number of non-letter characters "
4055 DevicePolicyData policy = getUserData(userHandle);
4056 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4057 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4061 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4062 boolean doNotAskCredentialsOnBoot =
4063 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4064 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4065 setDoNotAskCredentialsOnBoot();
4068 // Don't do this with the lock held, because it is going to call
4069 // back in to the service.
4070 final long ident = mInjector.binderClearCallingIdentity();
4072 if (!TextUtils.isEmpty(password)) {
4073 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4075 mLockPatternUtils.clearLock(userHandle);
4077 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4079 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4080 UserHandle.USER_ALL);
4082 synchronized (this) {
4083 int newOwner = requireEntry ? callingUid : -1;
4084 if (policy.mPasswordOwner != newOwner) {
4085 policy.mPasswordOwner = newOwner;
4086 saveSettingsLocked(userHandle);
4090 mInjector.binderRestoreCallingIdentity(ident);
4096 private boolean isLockScreenSecureUnchecked(int userId) {
4097 long ident = mInjector.binderClearCallingIdentity();
4099 return mLockPatternUtils.isSecure(userId);
4101 mInjector.binderRestoreCallingIdentity(ident);
4105 private void setDoNotAskCredentialsOnBoot() {
4106 synchronized (this) {
4107 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4108 if (!policyData.doNotAskCredentialsOnBoot) {
4109 policyData.doNotAskCredentialsOnBoot = true;
4110 saveSettingsLocked(UserHandle.USER_SYSTEM);
4116 public boolean getDoNotAskCredentialsOnBoot() {
4117 mContext.enforceCallingOrSelfPermission(
4118 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4119 synchronized (this) {
4120 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4121 return policyData.doNotAskCredentialsOnBoot;
4126 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4130 Preconditions.checkNotNull(who, "ComponentName is null");
4131 final int userHandle = mInjector.userHandleGetCallingUserId();
4132 synchronized (this) {
4133 ActiveAdmin ap = getActiveAdminForCallerLocked(
4134 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4135 if (ap.maximumTimeToUnlock != timeMs) {
4136 ap.maximumTimeToUnlock = timeMs;
4137 saveSettingsLocked(userHandle);
4138 updateMaximumTimeToLockLocked(userHandle);
4143 void updateMaximumTimeToLockLocked(int userHandle) {
4144 // Calculate the min timeout for all profiles - including the ones with a separate
4145 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4146 // challenge only and keep the screen on. However there is no easy way of doing that at the
4147 // moment so we set the screen off timeout regardless of whether it affects the parent user
4148 // or the profile challenge only.
4149 long timeMs = Long.MAX_VALUE;
4150 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4151 for (int profileId : profileIds) {
4152 DevicePolicyData policy = getUserDataUnchecked(profileId);
4153 final int N = policy.mAdminList.size();
4154 for (int i = 0; i < N; i++) {
4155 ActiveAdmin admin = policy.mAdminList.get(i);
4156 if (admin.maximumTimeToUnlock > 0
4157 && timeMs > admin.maximumTimeToUnlock) {
4158 timeMs = admin.maximumTimeToUnlock;
4160 // If userInfo.id is a managed profile, we also need to look at
4161 // the policies set on the parent.
4162 if (admin.hasParentActiveAdmin()) {
4163 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4164 if (parentAdmin.maximumTimeToUnlock > 0
4165 && timeMs > parentAdmin.maximumTimeToUnlock) {
4166 timeMs = parentAdmin.maximumTimeToUnlock;
4172 // We only store the last maximum time to lock on the parent profile. So if calling from a
4173 // managed profile, retrieve the policy for the parent.
4174 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4175 if (policy.mLastMaximumTimeToLock == timeMs) {
4178 policy.mLastMaximumTimeToLock = timeMs;
4180 final long ident = mInjector.binderClearCallingIdentity();
4182 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4183 // Make sure KEEP_SCREEN_ON is disabled, since that
4184 // would allow bypassing of the maximum time to lock.
4185 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4188 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4189 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4191 mInjector.binderRestoreCallingIdentity(ident);
4196 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4200 enforceFullCrossUsersPermission(userHandle);
4201 synchronized (this) {
4203 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4204 return admin != null ? admin.maximumTimeToUnlock : 0;
4206 // Return the strictest policy across all participating admins.
4207 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4208 userHandle, parent);
4209 return getMaximumTimeToLockPolicyFromAdmins(admins);
4214 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4218 enforceFullCrossUsersPermission(userHandle);
4219 synchronized (this) {
4220 // All admins for this user.
4221 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4222 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4223 DevicePolicyData policy = getUserData(userInfo.id);
4224 admins.addAll(policy.mAdminList);
4225 // If it is a managed profile, it may have parent active admins
4226 if (userInfo.isManagedProfile()) {
4227 for (ActiveAdmin admin : policy.mAdminList) {
4228 if (admin.hasParentActiveAdmin()) {
4229 admins.add(admin.getParentActiveAdmin());
4234 return getMaximumTimeToLockPolicyFromAdmins(admins);
4238 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4240 final int N = admins.size();
4241 for (int i = 0; i < N; i++) {
4242 ActiveAdmin admin = admins.get(i);
4244 time = admin.maximumTimeToUnlock;
4245 } else if (admin.maximumTimeToUnlock != 0
4246 && time > admin.maximumTimeToUnlock) {
4247 time = admin.maximumTimeToUnlock;
4254 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
4259 Preconditions.checkNotNull(who, "ComponentName is null");
4260 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
4261 // timeoutMs with value 0 means that the admin doesn't participate
4262 // timeoutMs is clamped to the interval in case the internal constants change in the future
4263 if (timeoutMs != 0 && timeoutMs < MINIMUM_STRONG_AUTH_TIMEOUT_MS) {
4264 timeoutMs = MINIMUM_STRONG_AUTH_TIMEOUT_MS;
4266 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
4267 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4270 final int userHandle = mInjector.userHandleGetCallingUserId();
4271 synchronized (this) {
4272 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4273 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4274 if (ap.strongAuthUnlockTimeout != timeoutMs) {
4275 ap.strongAuthUnlockTimeout = timeoutMs;
4276 saveSettingsLocked(userHandle);
4282 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
4283 * admins if who is null.
4284 * Returns 0 if not configured for the provided admin.
4287 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
4289 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4291 enforceFullCrossUsersPermission(userId);
4292 synchronized (this) {
4294 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
4295 return admin != null ? admin.strongAuthUnlockTimeout : 0;
4298 // Return the strictest policy across all participating admins.
4299 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
4301 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4302 for (int i = 0; i < admins.size(); i++) {
4303 final long timeout = admins.get(i).strongAuthUnlockTimeout;
4304 if (timeout != 0) { // take only participating admins into account
4305 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
4308 return Math.max(strongAuthUnlockTimeout, MINIMUM_STRONG_AUTH_TIMEOUT_MS);
4313 public void lockNow(boolean parent) {
4317 synchronized (this) {
4318 // This API can only be called by an active device admin,
4319 // so try to retrieve it to check that the caller is one.
4320 getActiveAdminForCallerLocked(
4321 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4323 int userToLock = mInjector.userHandleGetCallingUserId();
4325 // Unless this is a managed profile with work challenge enabled, lock all users.
4326 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4327 userToLock = UserHandle.USER_ALL;
4329 final long ident = mInjector.binderClearCallingIdentity();
4331 mLockPatternUtils.requireStrongAuth(
4332 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4333 if (userToLock == UserHandle.USER_ALL) {
4334 // Power off the display
4335 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4336 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4337 mInjector.getIWindowManager().lockNow(null);
4339 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4341 } catch (RemoteException e) {
4343 mInjector.binderRestoreCallingIdentity(ident);
4349 public void enforceCanManageCaCerts(ComponentName who) {
4351 if (!isCallerDelegatedCertInstaller()) {
4352 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4355 synchronized (this) {
4356 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4361 private void enforceCanManageInstalledKeys(ComponentName who) {
4363 if (!isCallerDelegatedCertInstaller()) {
4364 throw new SecurityException("who == null, but caller is not cert installer");
4367 synchronized (this) {
4368 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4373 private boolean isCallerDelegatedCertInstaller() {
4374 final int callingUid = mInjector.binderGetCallingUid();
4375 final int userHandle = UserHandle.getUserId(callingUid);
4376 synchronized (this) {
4377 final DevicePolicyData policy = getUserData(userHandle);
4378 if (policy.mDelegatedCertInstallerPackage == null) {
4383 int uid = mContext.getPackageManager().getPackageUidAsUser(
4384 policy.mDelegatedCertInstallerPackage, userHandle);
4385 return uid == callingUid;
4386 } catch (NameNotFoundException e) {
4393 public boolean approveCaCert(String alias, int userId, boolean approval) {
4394 enforceManageUsers();
4395 synchronized (this) {
4396 Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4397 boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4401 saveSettingsLocked(userId);
4403 new MonitoringCertNotificationTask().execute(userId);
4408 public boolean isCaCertApproved(String alias, int userId) {
4409 enforceManageUsers();
4410 synchronized (this) {
4411 return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4415 private void removeCaApprovalsIfNeeded(int userId) {
4416 for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4417 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4418 if (userInfo.isManagedProfile()){
4419 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4422 synchronized (this) {
4423 getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4424 saveSettingsLocked(userInfo.id);
4427 new MonitoringCertNotificationTask().execute(userInfo.id);
4433 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4434 enforceCanManageCaCerts(admin);
4438 X509Certificate cert = parseCert(certBuffer);
4439 pemCert = Credentials.convertToPem(cert);
4440 } catch (CertificateException ce) {
4441 Log.e(LOG_TAG, "Problem converting cert", ce);
4443 } catch (IOException ioe) {
4444 Log.e(LOG_TAG, "Problem reading cert", ioe);
4448 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4449 final long id = mInjector.binderClearCallingIdentity();
4451 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4453 keyChainConnection.getService().installCaCertificate(pemCert);
4455 } catch (RemoteException e) {
4456 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4458 keyChainConnection.close();
4460 } catch (InterruptedException e1) {
4461 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4462 Thread.currentThread().interrupt();
4464 mInjector.binderRestoreCallingIdentity(id);
4469 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4470 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4471 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4476 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4477 enforceCanManageCaCerts(admin);
4479 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4480 final long id = mInjector.binderClearCallingIdentity();
4482 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4484 for (int i = 0 ; i < aliases.length; i++) {
4485 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4487 } catch (RemoteException e) {
4488 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4490 keyChainConnection.close();
4492 } catch (InterruptedException ie) {
4493 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4494 Thread.currentThread().interrupt();
4496 mInjector.binderRestoreCallingIdentity(id);
4501 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4502 String alias, boolean requestAccess) {
4503 enforceCanManageInstalledKeys(who);
4505 final int callingUid = mInjector.binderGetCallingUid();
4506 final long id = mInjector.binderClearCallingIdentity();
4508 final KeyChainConnection keyChainConnection =
4509 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4511 IKeyChainService keyChain = keyChainConnection.getService();
4512 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4515 if (requestAccess) {
4516 keyChain.setGrant(callingUid, alias, true);
4519 } catch (RemoteException e) {
4520 Log.e(LOG_TAG, "Installing certificate", e);
4522 keyChainConnection.close();
4524 } catch (InterruptedException e) {
4525 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4526 Thread.currentThread().interrupt();
4528 mInjector.binderRestoreCallingIdentity(id);
4534 public boolean removeKeyPair(ComponentName who, String alias) {
4535 enforceCanManageInstalledKeys(who);
4537 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4538 final long id = Binder.clearCallingIdentity();
4540 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4542 IKeyChainService keyChain = keyChainConnection.getService();
4543 return keyChain.removeKeyPair(alias);
4544 } catch (RemoteException e) {
4545 Log.e(LOG_TAG, "Removing keypair", e);
4547 keyChainConnection.close();
4549 } catch (InterruptedException e) {
4550 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4551 Thread.currentThread().interrupt();
4553 Binder.restoreCallingIdentity(id);
4559 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4560 final IBinder response) {
4561 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4562 if (!isCallerWithSystemUid()) {
4566 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4567 // If there is a profile owner, redirect to that; otherwise query the device owner.
4568 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4569 if (aliasChooser == null && caller.isSystem()) {
4570 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4571 if (deviceOwnerAdmin != null) {
4572 aliasChooser = deviceOwnerAdmin.info.getComponent();
4575 if (aliasChooser == null) {
4576 sendPrivateKeyAliasResponse(null, response);
4580 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4581 intent.setComponent(aliasChooser);
4582 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4583 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4584 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4585 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4586 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4588 final long id = mInjector.binderClearCallingIdentity();
4590 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4592 public void onReceive(Context context, Intent intent) {
4593 final String chosenAlias = getResultData();
4594 sendPrivateKeyAliasResponse(chosenAlias, response);
4596 }, null, Activity.RESULT_OK, null, null);
4598 mInjector.binderRestoreCallingIdentity(id);
4602 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4603 final IKeyChainAliasCallback keyChainAliasResponse =
4604 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4605 new AsyncTask<Void, Void, Void>() {
4607 protected Void doInBackground(Void... unused) {
4609 keyChainAliasResponse.alias(alias);
4610 } catch (Exception e) {
4611 // Catch everything (not just RemoteException): caller could throw a
4612 // RuntimeException back across processes.
4613 Log.e(LOG_TAG, "error while responding to callback", e);
4621 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4622 throws SecurityException {
4623 int userHandle = UserHandle.getCallingUserId();
4624 synchronized (this) {
4625 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4626 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4627 if (installerPackage != null &&
4628 !isPackageInstalledForUser(installerPackage, userHandle)) {
4629 throw new IllegalArgumentException("Package " + installerPackage
4630 + " is not installed on the current user");
4633 DevicePolicyData policy = getUserData(userHandle);
4634 policy.mDelegatedCertInstallerPackage = installerPackage;
4635 saveSettingsLocked(userHandle);
4640 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4641 int userHandle = UserHandle.getCallingUserId();
4642 synchronized (this) {
4643 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4644 DevicePolicyData policy = getUserData(userHandle);
4645 return policy.mDelegatedCertInstallerPackage;
4650 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4651 * not installed and therefore not available.
4653 * @throws SecurityException if the caller is not a profile or device owner.
4654 * @throws UnsupportedOperationException if the package does not support being set as always-on.
4657 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4658 throws SecurityException {
4659 synchronized (this) {
4660 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4663 final int userId = mInjector.userHandleGetCallingUserId();
4664 final long token = mInjector.binderClearCallingIdentity();
4666 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4669 ConnectivityManager connectivityManager = (ConnectivityManager)
4670 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4671 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4672 throw new UnsupportedOperationException();
4675 mInjector.binderRestoreCallingIdentity(token);
4681 public String getAlwaysOnVpnPackage(ComponentName admin)
4682 throws SecurityException {
4683 synchronized (this) {
4684 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4687 final int userId = mInjector.userHandleGetCallingUserId();
4688 final long token = mInjector.binderClearCallingIdentity();
4690 ConnectivityManager connectivityManager = (ConnectivityManager)
4691 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4692 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4694 mInjector.binderRestoreCallingIdentity(token);
4698 private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
4699 if (wipeExtRequested) {
4700 StorageManager sm = (StorageManager) mContext.getSystemService(
4701 Context.STORAGE_SERVICE);
4702 sm.wipeAdoptableDisks();
4705 RecoverySystem.rebootWipeUserData(mContext, reason);
4706 } catch (IOException | SecurityException e) {
4707 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4712 public void wipeData(int flags) {
4716 final int userHandle = mInjector.userHandleGetCallingUserId();
4717 enforceFullCrossUsersPermission(userHandle);
4719 final String source;
4720 synchronized (this) {
4721 // This API can only be called by an active device admin,
4722 // so try to retrieve it to check that the caller is one.
4723 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4724 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4725 source = admin.info.getComponent().flattenToShortString();
4727 long ident = mInjector.binderClearCallingIdentity();
4729 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4730 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4731 throw new SecurityException(
4732 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4734 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4735 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4736 if (manager != null) {
4741 mInjector.binderRestoreCallingIdentity(ident);
4744 final boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4745 wipeDeviceNoLock(wipeExtRequested, userHandle,
4746 "DevicePolicyManager.wipeData() from " + source);
4749 private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
4750 final long ident = mInjector.binderClearCallingIdentity();
4752 if (userHandle == UserHandle.USER_SYSTEM) {
4753 wipeDataNoLock(wipeExtRequested, reason);
4755 mHandler.post(new Runnable() {
4759 IActivityManager am = mInjector.getIActivityManager();
4760 if (am.getCurrentUser().id == userHandle) {
4761 am.switchUser(UserHandle.USER_SYSTEM);
4764 boolean isManagedProfile = isManagedProfile(userHandle);
4765 if (!mUserManager.removeUser(userHandle)) {
4766 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4767 } else if (isManagedProfile) {
4768 sendWipeProfileNotification();
4770 } catch (RemoteException re) {
4777 mInjector.binderRestoreCallingIdentity(ident);
4781 private void sendWipeProfileNotification() {
4782 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4783 Notification notification = new Notification.Builder(mContext)
4784 .setSmallIcon(android.R.drawable.stat_sys_warning)
4785 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4786 .setContentText(contentText)
4787 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4788 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4790 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4793 private void clearWipeProfileNotification() {
4794 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4798 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4802 enforceFullCrossUsersPermission(userHandle);
4803 mContext.enforceCallingOrSelfPermission(
4804 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4806 synchronized (this) {
4807 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4808 if (admin == null) {
4809 result.sendResult(null);
4812 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4813 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4814 intent.setComponent(admin.info.getComponent());
4815 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4816 null, new BroadcastReceiver() {
4818 public void onReceive(Context context, Intent intent) {
4819 result.sendResult(getResultExtras(false));
4821 }, null, Activity.RESULT_OK, null, null);
4826 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4827 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4831 enforceFullCrossUsersPermission(userHandle);
4832 mContext.enforceCallingOrSelfPermission(
4833 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4835 // If the managed profile doesn't have a separate password, set the metrics to default
4836 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
4837 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4847 validateQualityConstant(quality);
4848 DevicePolicyData policy = getUserData(userHandle);
4849 synchronized (this) {
4850 policy.mActivePasswordQuality = quality;
4851 policy.mActivePasswordLength = length;
4852 policy.mActivePasswordLetters = letters;
4853 policy.mActivePasswordLowerCase = lowercase;
4854 policy.mActivePasswordUpperCase = uppercase;
4855 policy.mActivePasswordNumeric = numbers;
4856 policy.mActivePasswordSymbols = symbols;
4857 policy.mActivePasswordNonLetter = nonletter;
4862 public void reportPasswordChanged(int userId) {
4866 enforceFullCrossUsersPermission(userId);
4868 // Managed Profile password can only be changed when it has a separate challenge.
4869 if (!isSeparateProfileChallengeEnabled(userId)) {
4870 enforceNotManagedProfile(userId, "set the active password");
4873 mContext.enforceCallingOrSelfPermission(
4874 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4876 DevicePolicyData policy = getUserData(userId);
4878 long ident = mInjector.binderClearCallingIdentity();
4880 synchronized (this) {
4881 policy.mFailedPasswordAttempts = 0;
4882 saveSettingsLocked(userId);
4883 updatePasswordExpirationsLocked(userId);
4884 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
4886 // Send a broadcast to each profile using this password as its primary unlock.
4887 sendAdminCommandForLockscreenPoliciesLocked(
4888 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4889 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
4891 removeCaApprovalsIfNeeded(userId);
4893 mInjector.binderRestoreCallingIdentity(ident);
4898 * Called any time the device password is updated. Resets all password expiration clocks.
4900 private void updatePasswordExpirationsLocked(int userHandle) {
4901 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4902 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4903 userHandle, /* parent */ false);
4904 final int N = admins.size();
4905 for (int i = 0; i < N; i++) {
4906 ActiveAdmin admin = admins.get(i);
4907 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4908 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4909 long timeout = admin.passwordExpirationTimeout;
4910 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4911 admin.passwordExpirationDate = expiration;
4914 for (int affectedUserId : affectedUserIds) {
4915 saveSettingsLocked(affectedUserId);
4920 public void reportFailedPasswordAttempt(int userHandle) {
4921 enforceFullCrossUsersPermission(userHandle);
4922 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4923 enforceNotManagedProfile(userHandle,
4924 "report failed password attempt if separate profile challenge is not in place");
4926 mContext.enforceCallingOrSelfPermission(
4927 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4929 final long ident = mInjector.binderClearCallingIdentity();
4931 boolean wipeData = false;
4933 synchronized (this) {
4934 DevicePolicyData policy = getUserData(userHandle);
4935 policy.mFailedPasswordAttempts++;
4936 saveSettingsLocked(userHandle);
4938 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4939 userHandle, /* parent */ false);
4940 int max = strictestAdmin != null
4941 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4942 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4943 // Wipe the user/profile associated with the policy that was violated. This
4944 // is not necessarily calling user: if the policy that fired was from a
4945 // managed profile rather than the main user profile, we wipe former only.
4947 identifier = strictestAdmin.getUserHandle().getIdentifier();
4950 sendAdminCommandForLockscreenPoliciesLocked(
4951 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
4952 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4956 // Call without holding lock.
4957 wipeDeviceNoLock(false, identifier,
4958 "reportFailedPasswordAttempt()");
4961 mInjector.binderRestoreCallingIdentity(ident);
4964 if (mInjector.securityLogIsLoggingEnabled()) {
4965 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4966 /*method strength*/ 1);
4971 public void reportSuccessfulPasswordAttempt(int userHandle) {
4972 enforceFullCrossUsersPermission(userHandle);
4973 mContext.enforceCallingOrSelfPermission(
4974 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4976 synchronized (this) {
4977 DevicePolicyData policy = getUserData(userHandle);
4978 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
4979 long ident = mInjector.binderClearCallingIdentity();
4981 policy.mFailedPasswordAttempts = 0;
4982 policy.mPasswordOwner = -1;
4983 saveSettingsLocked(userHandle);
4985 sendAdminCommandForLockscreenPoliciesLocked(
4986 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
4987 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4990 mInjector.binderRestoreCallingIdentity(ident);
4995 if (mInjector.securityLogIsLoggingEnabled()) {
4996 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4997 /*method strength*/ 1);
5002 public void reportFailedFingerprintAttempt(int userHandle) {
5003 enforceFullCrossUsersPermission(userHandle);
5004 mContext.enforceCallingOrSelfPermission(
5005 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5006 if (mInjector.securityLogIsLoggingEnabled()) {
5007 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5008 /*method strength*/ 0);
5013 public void reportSuccessfulFingerprintAttempt(int userHandle) {
5014 enforceFullCrossUsersPermission(userHandle);
5015 mContext.enforceCallingOrSelfPermission(
5016 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5017 if (mInjector.securityLogIsLoggingEnabled()) {
5018 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5019 /*method strength*/ 0);
5024 public void reportKeyguardDismissed(int userHandle) {
5025 enforceFullCrossUsersPermission(userHandle);
5026 mContext.enforceCallingOrSelfPermission(
5027 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5029 if (mInjector.securityLogIsLoggingEnabled()) {
5030 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
5035 public void reportKeyguardSecured(int userHandle) {
5036 enforceFullCrossUsersPermission(userHandle);
5037 mContext.enforceCallingOrSelfPermission(
5038 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5040 if (mInjector.securityLogIsLoggingEnabled()) {
5041 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
5046 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
5047 String exclusionList) {
5051 synchronized(this) {
5052 Preconditions.checkNotNull(who, "ComponentName is null");
5054 // Only check if system user has set global proxy. We don't allow other users to set it.
5055 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5056 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5057 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
5059 // Scan through active admins and find if anyone has already
5060 // set the global proxy.
5061 Set<ComponentName> compSet = policy.mAdminMap.keySet();
5062 for (ComponentName component : compSet) {
5063 ActiveAdmin ap = policy.mAdminMap.get(component);
5064 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
5065 // Another admin already sets the global proxy
5066 // Return it to the caller.
5071 // If the user is not system, don't set the global proxy. Fail silently.
5072 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
5073 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
5074 + UserHandle.getCallingUserId() + " is not permitted.");
5077 if (proxySpec == null) {
5078 admin.specifiesGlobalProxy = false;
5079 admin.globalProxySpec = null;
5080 admin.globalProxyExclusionList = null;
5083 admin.specifiesGlobalProxy = true;
5084 admin.globalProxySpec = proxySpec;
5085 admin.globalProxyExclusionList = exclusionList;
5088 // Reset the global proxy accordingly
5089 // Do this using system permissions, as apps cannot write to secure settings
5090 long origId = mInjector.binderClearCallingIdentity();
5092 resetGlobalProxyLocked(policy);
5094 mInjector.binderRestoreCallingIdentity(origId);
5101 public ComponentName getGlobalProxyAdmin(int userHandle) {
5105 enforceFullCrossUsersPermission(userHandle);
5106 synchronized(this) {
5107 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5108 // Scan through active admins and find if anyone has already
5109 // set the global proxy.
5110 final int N = policy.mAdminList.size();
5111 for (int i = 0; i < N; i++) {
5112 ActiveAdmin ap = policy.mAdminList.get(i);
5113 if (ap.specifiesGlobalProxy) {
5114 // Device admin sets the global proxy
5115 // Return it to the caller.
5116 return ap.info.getComponent();
5120 // No device admin sets the global proxy.
5125 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5126 synchronized (this) {
5127 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5129 long token = mInjector.binderClearCallingIdentity();
5131 ConnectivityManager connectivityManager = (ConnectivityManager)
5132 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5133 connectivityManager.setGlobalProxy(proxyInfo);
5135 mInjector.binderRestoreCallingIdentity(token);
5139 private void resetGlobalProxyLocked(DevicePolicyData policy) {
5140 final int N = policy.mAdminList.size();
5141 for (int i = 0; i < N; i++) {
5142 ActiveAdmin ap = policy.mAdminList.get(i);
5143 if (ap.specifiesGlobalProxy) {
5144 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5148 // No device admins defining global proxies - reset global proxy settings to none
5149 saveGlobalProxyLocked(null, null);
5152 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5153 if (exclusionList == null) {
5156 if (proxySpec == null) {
5159 // Remove white spaces
5160 proxySpec = proxySpec.trim();
5161 String data[] = proxySpec.split(":");
5162 int proxyPort = 8080;
5163 if (data.length > 1) {
5165 proxyPort = Integer.parseInt(data[1]);
5166 } catch (NumberFormatException e) {}
5168 exclusionList = exclusionList.trim();
5170 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5171 if (!proxyProperties.isValid()) {
5172 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5175 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5176 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5177 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5182 * Set the storage encryption request for a single admin. Returns the new total request
5183 * status (for all admins).
5186 public int setStorageEncryption(ComponentName who, boolean encrypt) {
5188 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5190 Preconditions.checkNotNull(who, "ComponentName is null");
5191 final int userHandle = UserHandle.getCallingUserId();
5192 synchronized (this) {
5193 // Check for permissions
5194 // Only system user can set storage encryption
5195 if (userHandle != UserHandle.USER_SYSTEM) {
5196 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5197 + UserHandle.getCallingUserId() + " is not permitted.");
5201 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5202 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5204 // Quick exit: If the filesystem does not support encryption, we can exit early.
5205 if (!isEncryptionSupported()) {
5206 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5209 // (1) Record the value for the admin so it's sticky
5210 if (ap.encryptionRequested != encrypt) {
5211 ap.encryptionRequested = encrypt;
5212 saveSettingsLocked(userHandle);
5215 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5216 // (2) Compute "max" for all admins
5217 boolean newRequested = false;
5218 final int N = policy.mAdminList.size();
5219 for (int i = 0; i < N; i++) {
5220 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5223 // Notify OS of new request
5224 setEncryptionRequested(newRequested);
5226 // Return the new global request status
5228 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5229 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5234 * Get the current storage encryption request status for a given admin, or aggregate of all
5238 public boolean getStorageEncryption(ComponentName who, int userHandle) {
5242 enforceFullCrossUsersPermission(userHandle);
5243 synchronized (this) {
5244 // Check for permissions if a particular caller is specified
5246 // When checking for a single caller, status is based on caller's request
5247 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5248 return ap != null ? ap.encryptionRequested : false;
5251 // If no particular caller is specified, return the aggregate set of requests.
5252 // This is short circuited by returning true on the first hit.
5253 DevicePolicyData policy = getUserData(userHandle);
5254 final int N = policy.mAdminList.size();
5255 for (int i = 0; i < N; i++) {
5256 if (policy.mAdminList.get(i).encryptionRequested) {
5265 * Get the current encryption status of the device.
5268 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5270 // Ok to return current status.
5272 enforceFullCrossUsersPermission(userHandle);
5274 // It's not critical here, but let's make sure the package name is correct, in case
5275 // we start using it for different purposes.
5276 ensureCallerPackage(callerPackage);
5278 final ApplicationInfo ai;
5280 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5281 } catch (RemoteException e) {
5282 throw new SecurityException(e);
5285 boolean legacyApp = false;
5286 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5290 final int rawStatus = getEncryptionStatus();
5291 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5292 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5298 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
5300 private boolean isEncryptionSupported() {
5301 // Note, this can be implemented as
5302 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5303 // But is provided as a separate internal method if there's a faster way to do a
5304 // simple check for supported-or-not.
5305 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5309 * Hook to low-levels: Reporting the current status of encryption.
5310 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5311 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5312 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5313 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5314 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5316 private int getEncryptionStatus() {
5317 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5318 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5319 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5320 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5321 } else if (mInjector.storageManagerIsEncrypted()) {
5322 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5323 } else if (mInjector.storageManagerIsEncryptable()) {
5324 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5326 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5331 * Hook to low-levels: If needed, record the new admin setting for encryption.
5333 private void setEncryptionRequested(boolean encrypt) {
5337 * Set whether the screen capture is disabled for the user managed by the specified admin.
5340 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5344 Preconditions.checkNotNull(who, "ComponentName is null");
5345 final int userHandle = UserHandle.getCallingUserId();
5346 synchronized (this) {
5347 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5348 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5349 if (ap.disableScreenCapture != disabled) {
5350 ap.disableScreenCapture = disabled;
5351 saveSettingsLocked(userHandle);
5352 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5358 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5359 * active admin (if given admin is null).
5362 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5366 synchronized (this) {
5368 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5369 return (admin != null) ? admin.disableScreenCapture : false;
5372 DevicePolicyData policy = getUserData(userHandle);
5373 final int N = policy.mAdminList.size();
5374 for (int i = 0; i < N; i++) {
5375 ActiveAdmin admin = policy.mAdminList.get(i);
5376 if (admin.disableScreenCapture) {
5384 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5385 final boolean disabled) {
5386 mHandler.post(new Runnable() {
5390 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5391 } catch (RemoteException e) {
5392 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5399 * Set whether auto time is required by the specified admin (must be device owner).
5402 public void setAutoTimeRequired(ComponentName who, boolean required) {
5406 Preconditions.checkNotNull(who, "ComponentName is null");
5407 final int userHandle = UserHandle.getCallingUserId();
5408 synchronized (this) {
5409 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5410 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5411 if (admin.requireAutoTime != required) {
5412 admin.requireAutoTime = required;
5413 saveSettingsLocked(userHandle);
5417 // Turn AUTO_TIME on in settings if it is required
5419 long ident = mInjector.binderClearCallingIdentity();
5421 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5423 mInjector.binderRestoreCallingIdentity(ident);
5429 * Returns whether or not auto time is required by the device owner.
5432 public boolean getAutoTimeRequired() {
5436 synchronized (this) {
5437 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5438 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5443 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5447 Preconditions.checkNotNull(who, "ComponentName is null");
5448 // Allow setting this policy to true only if there is a split system user.
5449 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5450 throw new UnsupportedOperationException(
5451 "Cannot force ephemeral users on systems without split system user.");
5453 boolean removeAllUsers = false;
5454 synchronized (this) {
5455 final ActiveAdmin deviceOwner =
5456 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5457 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5458 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5459 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5460 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5461 removeAllUsers = forceEphemeralUsers;
5464 if (removeAllUsers) {
5465 long identitity = mInjector.binderClearCallingIdentity();
5467 mUserManagerInternal.removeAllUsers();
5469 mInjector.binderRestoreCallingIdentity(identitity);
5475 public boolean getForceEphemeralUsers(ComponentName who) {
5479 Preconditions.checkNotNull(who, "ComponentName is null");
5480 synchronized (this) {
5481 final ActiveAdmin deviceOwner =
5482 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5483 return deviceOwner.forceEphemeralUsers;
5487 private boolean isDeviceOwnerManagedSingleUserDevice() {
5488 synchronized (this) {
5489 if (!mOwners.hasDeviceOwner()) {
5493 final long callingIdentity = mInjector.binderClearCallingIdentity();
5495 if (mInjector.userManagerIsSplitSystemUser()) {
5496 // In split system user mode, only allow the case where the device owner is managing
5497 // the only non-system user of the device
5498 return (mUserManager.getUserCount() == 2
5499 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5501 return mUserManager.getUserCount() == 1;
5504 mInjector.binderRestoreCallingIdentity(callingIdentity);
5508 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5509 synchronized (this) {
5510 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5512 if (!isDeviceOwnerManagedSingleUserDevice()) {
5513 throw new SecurityException(
5514 "There should only be one user, managed by Device Owner");
5519 public boolean requestBugreport(ComponentName who) {
5523 Preconditions.checkNotNull(who, "ComponentName is null");
5524 ensureDeviceOwnerManagingSingleUser(who);
5526 if (mRemoteBugreportServiceIsActive.get()
5527 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5528 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5532 final long callingIdentity = mInjector.binderClearCallingIdentity();
5534 ActivityManagerNative.getDefault().requestBugReport(
5535 ActivityManager.BUGREPORT_OPTION_REMOTE);
5537 mRemoteBugreportServiceIsActive.set(true);
5538 mRemoteBugreportSharingAccepted.set(false);
5539 registerRemoteBugreportReceivers();
5540 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5541 RemoteBugreportUtils.buildNotification(mContext,
5542 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5543 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5544 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5546 } catch (RemoteException re) {
5547 // should never happen
5548 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5551 mInjector.binderRestoreCallingIdentity(callingIdentity);
5555 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5556 Intent intent = new Intent(action);
5557 intent.setComponent(mOwners.getDeviceOwnerComponent());
5558 if (extras != null) {
5559 intent.putExtras(extras);
5561 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5564 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5565 return mOwners.getDeviceOwnerRemoteBugreportUri();
5568 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5569 String bugreportHash) {
5570 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5573 private void registerRemoteBugreportReceivers() {
5575 IntentFilter filterFinished = new IntentFilter(
5576 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5577 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5578 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5579 } catch (IntentFilter.MalformedMimeTypeException e) {
5580 // should never happen, as setting a constant
5581 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5583 IntentFilter filterConsent = new IntentFilter();
5584 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5585 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5586 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5589 private void onBugreportFinished(Intent intent) {
5590 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5591 mRemoteBugreportServiceIsActive.set(false);
5592 Uri bugreportUri = intent.getData();
5593 String bugreportUriString = null;
5594 if (bugreportUri != null) {
5595 bugreportUriString = bugreportUri.toString();
5597 String bugreportHash = intent.getStringExtra(
5598 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5599 if (mRemoteBugreportSharingAccepted.get()) {
5600 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5601 mInjector.getNotificationManager().cancel(LOG_TAG,
5602 RemoteBugreportUtils.NOTIFICATION_ID);
5604 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5605 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5606 RemoteBugreportUtils.buildNotification(mContext,
5607 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5610 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5613 private void onBugreportFailed() {
5614 mRemoteBugreportServiceIsActive.set(false);
5615 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5616 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5617 mRemoteBugreportSharingAccepted.set(false);
5618 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5619 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5620 Bundle extras = new Bundle();
5621 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5622 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5623 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5624 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5625 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5628 private void onBugreportSharingAccepted() {
5629 mRemoteBugreportSharingAccepted.set(true);
5630 String bugreportUriString = null;
5631 String bugreportHash = null;
5632 synchronized (this) {
5633 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5634 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5636 if (bugreportUriString != null) {
5637 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5638 } else if (mRemoteBugreportServiceIsActive.get()) {
5639 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5640 RemoteBugreportUtils.buildNotification(mContext,
5641 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5646 private void onBugreportSharingDeclined() {
5647 if (mRemoteBugreportServiceIsActive.get()) {
5648 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5649 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5650 mRemoteBugreportServiceIsActive.set(false);
5651 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5652 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5654 mRemoteBugreportSharingAccepted.set(false);
5655 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5656 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5659 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5660 String bugreportHash) {
5661 ParcelFileDescriptor pfd = null;
5663 if (bugreportUriString == null) {
5664 throw new FileNotFoundException();
5666 Uri bugreportUri = Uri.parse(bugreportUriString);
5667 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5669 synchronized (this) {
5670 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5671 intent.setComponent(mOwners.getDeviceOwnerComponent());
5672 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5673 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5674 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
5675 bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5676 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5678 } catch (FileNotFoundException e) {
5679 Bundle extras = new Bundle();
5680 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5681 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5682 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5688 } catch (IOException ex) {
5691 mRemoteBugreportSharingAccepted.set(false);
5692 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5697 * Disables all device cameras according to the specified admin.
5700 public void setCameraDisabled(ComponentName who, boolean disabled) {
5704 Preconditions.checkNotNull(who, "ComponentName is null");
5705 final int userHandle = mInjector.userHandleGetCallingUserId();
5706 synchronized (this) {
5707 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5708 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5709 if (ap.disableCamera != disabled) {
5710 ap.disableCamera = disabled;
5711 saveSettingsLocked(userHandle);
5714 // Tell the user manager that the restrictions have changed.
5715 pushUserRestrictions(userHandle);
5719 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5723 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5724 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5727 private boolean getCameraDisabled(ComponentName who, int userHandle,
5728 boolean mergeDeviceOwnerRestriction) {
5732 synchronized (this) {
5734 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5735 return (admin != null) ? admin.disableCamera : false;
5737 // First, see if DO has set it. If so, it's device-wide.
5738 if (mergeDeviceOwnerRestriction) {
5739 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5740 if (deviceOwner != null && deviceOwner.disableCamera) {
5745 // Then check each device admin on the user.
5746 DevicePolicyData policy = getUserData(userHandle);
5747 // Determine whether or not the device camera is disabled for any active admins.
5748 final int N = policy.mAdminList.size();
5749 for (int i = 0; i < N; i++) {
5750 ActiveAdmin admin = policy.mAdminList.get(i);
5751 if (admin.disableCamera) {
5760 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5764 Preconditions.checkNotNull(who, "ComponentName is null");
5765 final int userHandle = mInjector.userHandleGetCallingUserId();
5766 if (isManagedProfile(userHandle)) {
5768 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5770 which = which & PROFILE_KEYGUARD_FEATURES;
5773 synchronized (this) {
5774 ActiveAdmin ap = getActiveAdminForCallerLocked(
5775 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5776 if (ap.disabledKeyguardFeatures != which) {
5777 ap.disabledKeyguardFeatures = which;
5778 saveSettingsLocked(userHandle);
5784 * Gets the disabled state for features in keyguard for the given admin,
5785 * or the aggregate of all active admins if who is null.
5788 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5792 enforceFullCrossUsersPermission(userHandle);
5793 final long ident = mInjector.binderClearCallingIdentity();
5795 synchronized (this) {
5797 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5798 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5801 final List<ActiveAdmin> admins;
5802 if (!parent && isManagedProfile(userHandle)) {
5803 // If we are being asked about a managed profile, just return keyguard features
5804 // disabled by admins in the profile.
5805 admins = getUserDataUnchecked(userHandle).mAdminList;
5807 // Otherwise return those set by admins in the user and its profiles.
5808 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5811 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5812 final int N = admins.size();
5813 for (int i = 0; i < N; i++) {
5814 ActiveAdmin admin = admins.get(i);
5815 int userId = admin.getUserHandle().getIdentifier();
5816 boolean isRequestedUser = !parent && (userId == userHandle);
5817 if (isRequestedUser || !isManagedProfile(userId)) {
5818 // If we are being asked explicitly about this user
5819 // return all disabled features even if its a managed profile.
5820 which |= admin.disabledKeyguardFeatures;
5822 // Otherwise a managed profile is only allowed to disable
5823 // some features on the parent user.
5824 which |= (admin.disabledKeyguardFeatures
5825 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5831 mInjector.binderRestoreCallingIdentity(ident);
5836 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5840 Preconditions.checkNotNull(who, "ComponentName is null");
5841 Preconditions.checkNotNull(packageList, "packageList is null");
5842 final int userHandle = UserHandle.getCallingUserId();
5843 synchronized (this) {
5844 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5845 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5846 admin.keepUninstalledPackages = packageList;
5847 saveSettingsLocked(userHandle);
5848 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5853 public List<String> getKeepUninstalledPackages(ComponentName who) {
5854 Preconditions.checkNotNull(who, "ComponentName is null");
5858 // TODO In split system user mode, allow apps on user 0 to query the list
5859 synchronized (this) {
5860 // Check if this is the device owner who is calling
5861 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5862 return getKeepUninstalledPackagesLocked();
5866 private List<String> getKeepUninstalledPackagesLocked() {
5867 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5868 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5872 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5877 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5878 throw new IllegalArgumentException("Invalid component " + admin
5879 + " for device owner");
5881 synchronized (this) {
5882 enforceCanSetDeviceOwnerLocked(admin, userId);
5883 if (getActiveAdminUncheckedLocked(admin, userId) == null
5884 || getUserData(userId).mRemovingAdmins.contains(admin)) {
5885 throw new IllegalArgumentException("Not active admin: " + admin);
5888 // Shutting down backup manager service permanently.
5889 long ident = mInjector.binderClearCallingIdentity();
5891 if (mInjector.getIBackupManager() != null) {
5892 mInjector.getIBackupManager()
5893 .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5895 } catch (RemoteException e) {
5896 throw new IllegalStateException("Failed deactivating backup service.", e);
5898 mInjector.binderRestoreCallingIdentity(ident);
5901 mOwners.setDeviceOwner(admin, ownerName, userId);
5902 mOwners.writeDeviceOwner();
5903 updateDeviceOwnerLocked();
5904 setDeviceOwnerSystemPropertyLocked();
5905 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5907 ident = mInjector.binderClearCallingIdentity();
5909 // TODO Send to system too?
5910 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5912 mInjector.binderRestoreCallingIdentity(ident);
5914 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
5919 public boolean isDeviceOwner(ComponentName who, int userId) {
5920 synchronized (this) {
5921 return mOwners.hasDeviceOwner()
5922 && mOwners.getDeviceOwnerUserId() == userId
5923 && mOwners.getDeviceOwnerComponent().equals(who);
5927 public boolean isProfileOwner(ComponentName who, int userId) {
5928 final ComponentName profileOwner = getProfileOwner(userId);
5929 return who != null && who.equals(profileOwner);
5933 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5937 if (!callingUserOnly) {
5938 enforceManageUsers();
5940 synchronized (this) {
5941 if (!mOwners.hasDeviceOwner()) {
5944 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
5945 mOwners.getDeviceOwnerUserId()) {
5948 return mOwners.getDeviceOwnerComponent();
5953 public int getDeviceOwnerUserId() {
5955 return UserHandle.USER_NULL;
5957 enforceManageUsers();
5958 synchronized (this) {
5959 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
5964 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
5968 public String getDeviceOwnerName() {
5972 enforceManageUsers();
5973 synchronized (this) {
5974 if (!mOwners.hasDeviceOwner()) {
5977 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
5978 // Should setDeviceOwner/ProfileOwner still take a name?
5979 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
5980 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
5984 // Returns the active device owner or null if there is no device owner.
5986 ActiveAdmin getDeviceOwnerAdminLocked() {
5987 ComponentName component = mOwners.getDeviceOwnerComponent();
5988 if (component == null) {
5992 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
5993 final int n = policy.mAdminList.size();
5994 for (int i = 0; i < n; i++) {
5995 ActiveAdmin admin = policy.mAdminList.get(i);
5996 if (component.equals(admin.info.getComponent())) {
6000 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
6005 public void clearDeviceOwner(String packageName) {
6006 Preconditions.checkNotNull(packageName, "packageName is null");
6007 final int callingUid = mInjector.binderGetCallingUid();
6009 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
6010 UserHandle.getUserId(callingUid));
6011 if (uid != callingUid) {
6012 throw new SecurityException("Invalid packageName");
6014 } catch (NameNotFoundException e) {
6015 throw new SecurityException(e);
6017 synchronized (this) {
6018 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6019 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6020 if (!mOwners.hasDeviceOwner()
6021 || !deviceOwnerComponent.getPackageName().equals(packageName)
6022 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
6023 throw new SecurityException(
6024 "clearDeviceOwner can only be called by the device owner");
6026 enforceUserUnlocked(deviceOwnerUserId);
6028 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
6029 long ident = mInjector.binderClearCallingIdentity();
6031 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
6032 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
6034 mInjector.binderRestoreCallingIdentity(ident);
6036 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
6040 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
6041 if (admin != null) {
6042 admin.disableCamera = false;
6043 admin.userRestrictions = null;
6044 admin.forceEphemeralUsers = false;
6045 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
6047 clearUserPoliciesLocked(userId);
6049 mOwners.clearDeviceOwner();
6050 mOwners.writeDeviceOwner();
6051 updateDeviceOwnerLocked();
6052 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
6054 if (mInjector.getIBackupManager() != null) {
6055 // Reactivate backup service.
6056 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6058 } catch (RemoteException e) {
6059 throw new IllegalStateException("Failed reactivating backup service.", e);
6064 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6069 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6070 throw new IllegalArgumentException("Component " + who
6071 + " not installed for userId:" + userHandle);
6073 synchronized (this) {
6074 enforceCanSetProfileOwnerLocked(who, userHandle);
6076 if (getActiveAdminUncheckedLocked(who, userHandle) == null
6077 || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6078 throw new IllegalArgumentException("Not active admin: " + who);
6081 mOwners.setProfileOwner(who, ownerName, userHandle);
6082 mOwners.writeProfileOwner(userHandle);
6083 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6089 public void clearProfileOwner(ComponentName who) {
6093 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
6094 final int userId = callingUser.getIdentifier();
6095 enforceNotManagedProfile(userId, "clear profile owner");
6096 enforceUserUnlocked(userId);
6097 // Check if this is the profile owner who is calling
6098 final ActiveAdmin admin =
6099 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6100 synchronized (this) {
6101 final long ident = mInjector.binderClearCallingIdentity();
6103 clearProfileOwnerLocked(admin, userId);
6104 removeActiveAdminLocked(who, userId);
6106 mInjector.binderRestoreCallingIdentity(ident);
6108 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6112 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6113 if (admin != null) {
6114 admin.disableCamera = false;
6115 admin.userRestrictions = null;
6117 clearUserPoliciesLocked(userId);
6118 mOwners.removeProfileOwner(userId);
6119 mOwners.writeProfileOwner(userId);
6123 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6124 Preconditions.checkNotNull(who, "ComponentName is null");
6129 synchronized (this) {
6130 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6131 long token = mInjector.binderClearCallingIdentity();
6133 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6135 mInjector.binderRestoreCallingIdentity(token);
6141 public CharSequence getDeviceOwnerLockScreenInfo() {
6142 return mLockPatternUtils.getDeviceOwnerInfo();
6145 private void clearUserPoliciesLocked(int userId) {
6146 // Reset some of the user-specific policies
6147 DevicePolicyData policy = getUserData(userId);
6148 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6149 policy.mDelegatedCertInstallerPackage = null;
6150 policy.mApplicationRestrictionsManagingPackage = null;
6151 policy.mStatusBarDisabled = false;
6152 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6153 saveSettingsLocked(userId);
6156 mIPackageManager.updatePermissionFlagsForAllApps(
6157 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6158 0 /* flagValues */, userId);
6159 pushUserRestrictions(userId);
6160 } catch (RemoteException re) {
6161 // Shouldn't happen.
6166 public boolean hasUserSetupCompleted() {
6167 return hasUserSetupCompleted(UserHandle.getCallingUserId());
6170 // This checks only if the Setup Wizard has run. Since Wear devices pair before
6171 // completing Setup Wizard, and pairing involves transferring user data, calling
6172 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
6173 private boolean hasUserSetupCompleted(int userHandle) {
6177 return getUserData(userHandle).mUserSetupComplete;
6180 private boolean hasPaired(int userHandle) {
6184 return getUserData(userHandle).mPaired;
6188 public int getUserProvisioningState() {
6190 return DevicePolicyManager.STATE_USER_UNMANAGED;
6192 int userHandle = mInjector.userHandleGetCallingUserId();
6193 return getUserProvisioningState(userHandle);
6196 private int getUserProvisioningState(int userHandle) {
6197 return getUserData(userHandle).mUserProvisioningState;
6201 public void setUserProvisioningState(int newState, int userHandle) {
6206 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6207 && getManagedUserId(userHandle) == -1) {
6208 // No managed device, user or profile, so setting provisioning state makes no sense.
6209 throw new IllegalStateException("Not allowed to change provisioning state unless a "
6210 + "device or profile owner is set.");
6213 synchronized (this) {
6214 boolean transitionCheckNeeded = true;
6216 // Calling identity/permission checks.
6217 final int callingUid = mInjector.binderGetCallingUid();
6218 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6219 // ADB shell can only move directly from un-managed to finalized as part of directly
6220 // setting profile-owner or device-owner.
6221 if (getUserProvisioningState(userHandle) !=
6222 DevicePolicyManager.STATE_USER_UNMANAGED
6223 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6224 throw new IllegalStateException("Not allowed to change provisioning state "
6225 + "unless current provisioning state is unmanaged, and new state is "
6228 transitionCheckNeeded = false;
6230 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6231 enforceCanManageProfileAndDeviceOwners();
6234 final DevicePolicyData policyData = getUserData(userHandle);
6235 if (transitionCheckNeeded) {
6236 // Optional state transition check for non-ADB case.
6237 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6239 policyData.mUserProvisioningState = newState;
6240 saveSettingsLocked(userHandle);
6244 private void checkUserProvisioningStateTransition(int currentState, int newState) {
6245 // Valid transitions for normal use-cases.
6246 switch (currentState) {
6247 case DevicePolicyManager.STATE_USER_UNMANAGED:
6248 // Can move to any state from unmanaged (except itself as an edge case)..
6249 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6253 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6254 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6255 // Can only move to finalized from these states.
6256 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6260 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6261 // Current user has a managed-profile, but current user is not managed, so
6262 // rather than moving to finalized state, go back to unmanaged once
6263 // profile provisioning is complete.
6264 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6268 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6269 // Cannot transition out of finalized.
6273 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6274 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6275 + "from state [" + currentState + "]");
6279 public void setProfileEnabled(ComponentName who) {
6283 Preconditions.checkNotNull(who, "ComponentName is null");
6284 synchronized (this) {
6285 // Check if this is the profile owner who is calling
6286 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6287 final int userId = UserHandle.getCallingUserId();
6288 enforceManagedProfile(userId, "enable the profile");
6290 long id = mInjector.binderClearCallingIdentity();
6292 mUserManager.setUserEnabled(userId);
6293 UserInfo parent = mUserManager.getProfileParent(userId);
6294 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6295 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6296 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6297 Intent.FLAG_RECEIVER_FOREGROUND);
6298 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6300 mInjector.binderRestoreCallingIdentity(id);
6306 public void setProfileName(ComponentName who, String profileName) {
6307 Preconditions.checkNotNull(who, "ComponentName is null");
6308 int userId = UserHandle.getCallingUserId();
6309 // Check if this is the profile owner (includes device owner).
6310 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6312 long id = mInjector.binderClearCallingIdentity();
6314 mUserManager.setUserName(userId, profileName);
6316 mInjector.binderRestoreCallingIdentity(id);
6321 public ComponentName getProfileOwner(int userHandle) {
6326 synchronized (this) {
6327 return mOwners.getProfileOwnerComponent(userHandle);
6331 // Returns the active profile owner for this user or null if the current user has no
6334 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6335 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6336 if (profileOwner == null) {
6339 DevicePolicyData policy = getUserData(userHandle);
6340 final int n = policy.mAdminList.size();
6341 for (int i = 0; i < n; i++) {
6342 ActiveAdmin admin = policy.mAdminList.get(i);
6343 if (profileOwner.equals(admin.info.getComponent())) {
6351 public String getProfileOwnerName(int userHandle) {
6355 enforceManageUsers();
6356 ComponentName profileOwner = getProfileOwner(userHandle);
6357 if (profileOwner == null) {
6360 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6364 * Canonical name for a given package.
6366 private String getApplicationLabel(String packageName, int userHandle) {
6367 long token = mInjector.binderClearCallingIdentity();
6369 final Context userContext;
6371 UserHandle handle = new UserHandle(userHandle);
6372 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6373 } catch (PackageManager.NameNotFoundException nnfe) {
6374 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6377 ApplicationInfo appInfo = userContext.getApplicationInfo();
6378 CharSequence result = null;
6379 if (appInfo != null) {
6380 PackageManager pm = userContext.getPackageManager();
6381 result = pm.getApplicationLabel(appInfo);
6383 return result != null ? result.toString() : null;
6385 mInjector.binderRestoreCallingIdentity(token);
6390 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6392 * The profile owner can only be set before the user setup phase has completed,
6395 * - adb if there are no accounts. (But see {@link #hasIncompatibleAccountsLocked})
6397 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle) {
6398 UserInfo info = getUserInfo(userHandle);
6400 // User doesn't exist.
6401 throw new IllegalArgumentException(
6402 "Attempted to set profile owner for invalid userId: " + userHandle);
6404 if (info.isGuest()) {
6405 throw new IllegalStateException("Cannot set a profile owner on a guest");
6407 if (mOwners.hasProfileOwner(userHandle)) {
6408 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6409 + "is already set.");
6411 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6412 throw new IllegalStateException("Trying to set the profile owner, but the user "
6413 + "already has a device owner.");
6415 int callingUid = mInjector.binderGetCallingUid();
6416 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6417 if ((mIsWatch || hasUserSetupCompleted(userHandle))
6418 && hasIncompatibleAccountsLocked(userHandle, owner)) {
6419 throw new IllegalStateException("Not allowed to set the profile owner because "
6420 + "there are already some accounts on the profile");
6424 enforceCanManageProfileAndDeviceOwners();
6425 if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
6426 throw new IllegalStateException("Cannot set the profile owner on a user which is "
6427 + "already set-up");
6432 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6435 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId) {
6436 int callingUid = mInjector.binderGetCallingUid();
6437 boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6439 enforceCanManageProfileAndDeviceOwners();
6442 final int code = checkSetDeviceOwnerPreConditionLocked(owner, userId, isAdb);
6446 case CODE_HAS_DEVICE_OWNER:
6447 throw new IllegalStateException(
6448 "Trying to set the device owner, but device owner is already set.");
6449 case CODE_USER_HAS_PROFILE_OWNER:
6450 throw new IllegalStateException("Trying to set the device owner, but the user "
6451 + "already has a profile owner.");
6452 case CODE_USER_NOT_RUNNING:
6453 throw new IllegalStateException("User not running: " + userId);
6454 case CODE_NOT_SYSTEM_USER:
6455 throw new IllegalStateException("User is not system user");
6456 case CODE_USER_SETUP_COMPLETED:
6457 throw new IllegalStateException(
6458 "Cannot set the device owner if the device is already set-up");
6459 case CODE_NONSYSTEM_USER_EXISTS:
6460 throw new IllegalStateException("Not allowed to set the device owner because there "
6461 + "are already several users on the device");
6462 case CODE_ACCOUNTS_NOT_EMPTY:
6463 throw new IllegalStateException("Not allowed to set the device owner because there "
6464 + "are already some accounts on the device");
6465 case CODE_HAS_PAIRED:
6466 throw new IllegalStateException("Not allowed to set the device owner because this "
6467 + "device has already paired");
6469 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6473 private void enforceUserUnlocked(int userId) {
6474 // Since we're doing this operation on behalf of an app, we only
6475 // want to use the actual "unlocked" state.
6476 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6477 "User must be running and unlocked");
6480 private void enforceUserUnlocked(int userId, boolean parent) {
6482 enforceUserUnlocked(getProfileParentId(userId));
6484 enforceUserUnlocked(userId);
6488 private void enforceManageUsers() {
6489 final int callingUid = mInjector.binderGetCallingUid();
6490 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6491 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6495 private void enforceFullCrossUsersPermission(int userHandle) {
6496 enforceSystemUserOrPermission(userHandle,
6497 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6500 private void enforceCrossUsersPermission(int userHandle) {
6501 enforceSystemUserOrPermission(userHandle,
6502 android.Manifest.permission.INTERACT_ACROSS_USERS);
6505 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6506 if (userHandle < 0) {
6507 throw new IllegalArgumentException("Invalid userId " + userHandle);
6509 final int callingUid = mInjector.binderGetCallingUid();
6510 if (userHandle == UserHandle.getUserId(callingUid)) {
6513 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6514 mContext.enforceCallingOrSelfPermission(permission,
6515 "Must be system or have " + permission + " permission");
6519 private void enforceManagedProfile(int userHandle, String message) {
6520 if(!isManagedProfile(userHandle)) {
6521 throw new SecurityException("You can not " + message + " outside a managed profile.");
6525 private void enforceNotManagedProfile(int userHandle, String message) {
6526 if(isManagedProfile(userHandle)) {
6527 throw new SecurityException("You can not " + message + " for a managed profile.");
6531 private void ensureCallerPackage(@Nullable String packageName) {
6532 if (packageName == null) {
6533 Preconditions.checkState(isCallerWithSystemUid(),
6534 "Only caller can omit package name");
6536 final int callingUid = mInjector.binderGetCallingUid();
6537 final int userId = mInjector.userHandleGetCallingUserId();
6539 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6540 packageName, 0, userId);
6541 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6542 } catch (RemoteException e) {
6548 private boolean isCallerWithSystemUid() {
6549 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6552 private int getProfileParentId(int userHandle) {
6553 final long ident = mInjector.binderClearCallingIdentity();
6555 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6556 return parentUser != null ? parentUser.id : userHandle;
6558 mInjector.binderRestoreCallingIdentity(ident);
6562 private int getCredentialOwner(int userHandle, boolean parent) {
6563 final long ident = mInjector.binderClearCallingIdentity();
6566 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6567 if (parentProfile != null) {
6568 userHandle = parentProfile.id;
6571 return mUserManager.getCredentialOwnerProfile(userHandle);
6573 mInjector.binderRestoreCallingIdentity(ident);
6577 private boolean isManagedProfile(int userHandle) {
6578 return getUserInfo(userHandle).isManagedProfile();
6581 private void enableIfNecessary(String packageName, int userId) {
6583 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6584 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6586 if (ai.enabledSetting
6587 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6588 mIPackageManager.setApplicationEnabledSetting(packageName,
6589 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6590 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6592 } catch (RemoteException e) {
6597 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6598 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6599 != PackageManager.PERMISSION_GRANTED) {
6601 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6602 + mInjector.binderGetCallingPid()
6603 + ", uid=" + mInjector.binderGetCallingUid());
6607 synchronized (this) {
6608 pw.println("Current Device Policy Manager state:");
6609 mOwners.dump(" ", pw);
6610 int userCount = mUserData.size();
6611 for (int u = 0; u < userCount; u++) {
6612 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6614 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6615 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6616 final int N = policy.mAdminList.size();
6617 for (int i=0; i<N; i++) {
6618 ActiveAdmin ap = policy.mAdminList.get(i);
6620 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6625 if (!policy.mRemovingAdmins.isEmpty()) {
6626 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6627 + policy.mRemovingAdmins);
6631 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6634 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6638 private String getEncryptionStatusName(int encryptionStatus) {
6639 switch (encryptionStatus) {
6640 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6642 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6643 return "block default key";
6644 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6646 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6648 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6649 return "unsupported";
6650 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6651 return "activating";
6658 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6659 ComponentName activity) {
6660 Preconditions.checkNotNull(who, "ComponentName is null");
6661 final int userHandle = UserHandle.getCallingUserId();
6662 synchronized (this) {
6663 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6665 long id = mInjector.binderClearCallingIdentity();
6667 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6668 } catch (RemoteException re) {
6671 mInjector.binderRestoreCallingIdentity(id);
6677 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6678 Preconditions.checkNotNull(who, "ComponentName is null");
6679 final int userHandle = UserHandle.getCallingUserId();
6680 synchronized (this) {
6681 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6683 long id = mInjector.binderClearCallingIdentity();
6685 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6686 } catch (RemoteException re) {
6689 mInjector.binderRestoreCallingIdentity(id);
6695 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6696 String packageName) {
6697 Preconditions.checkNotNull(admin, "ComponentName is null");
6699 final int userHandle = mInjector.userHandleGetCallingUserId();
6700 synchronized (this) {
6701 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6702 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6705 DevicePolicyData policy = getUserData(userHandle);
6706 policy.mApplicationRestrictionsManagingPackage = packageName;
6707 saveSettingsLocked(userHandle);
6713 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6714 Preconditions.checkNotNull(admin, "ComponentName is null");
6716 final int userHandle = mInjector.userHandleGetCallingUserId();
6717 synchronized (this) {
6718 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6719 DevicePolicyData policy = getUserData(userHandle);
6720 return policy.mApplicationRestrictionsManagingPackage;
6725 public boolean isCallerApplicationRestrictionsManagingPackage() {
6726 final int callingUid = mInjector.binderGetCallingUid();
6727 final int userHandle = UserHandle.getUserId(callingUid);
6728 synchronized (this) {
6729 final DevicePolicyData policy = getUserData(userHandle);
6730 if (policy.mApplicationRestrictionsManagingPackage == null) {
6735 int uid = mContext.getPackageManager().getPackageUidAsUser(
6736 policy.mApplicationRestrictionsManagingPackage, userHandle);
6737 return uid == callingUid;
6738 } catch (NameNotFoundException e) {
6744 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6746 synchronized (this) {
6747 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6749 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6750 throw new SecurityException(
6751 "No admin component given, and caller cannot manage application restrictions "
6752 + "for other apps.");
6757 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6758 enforceCanManageApplicationRestrictions(who);
6760 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6761 final long id = mInjector.binderClearCallingIdentity();
6763 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6765 mInjector.binderRestoreCallingIdentity(id);
6770 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6771 PersistableBundle args, boolean parent) {
6775 Preconditions.checkNotNull(admin, "admin is null");
6776 Preconditions.checkNotNull(agent, "agent is null");
6777 final int userHandle = UserHandle.getCallingUserId();
6778 synchronized (this) {
6779 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6780 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6781 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6782 saveSettingsLocked(userHandle);
6787 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6788 ComponentName agent, int userHandle, boolean parent) {
6792 Preconditions.checkNotNull(agent, "agent null");
6793 enforceFullCrossUsersPermission(userHandle);
6795 synchronized (this) {
6796 final String componentName = agent.flattenToString();
6797 if (admin != null) {
6798 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6799 if (ap == null) return null;
6800 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6801 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6802 List<PersistableBundle> result = new ArrayList<>();
6803 result.add(trustAgentInfo.options);
6807 // Return strictest policy for this user and profiles that are visible from this user.
6808 List<PersistableBundle> result = null;
6809 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6810 // of the options. If any admin doesn't have options, discard options for the rest
6812 List<ActiveAdmin> admins =
6813 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6814 boolean allAdminsHaveOptions = true;
6815 final int N = admins.size();
6816 for (int i = 0; i < N; i++) {
6817 final ActiveAdmin active = admins.get(i);
6819 final boolean disablesTrust = (active.disabledKeyguardFeatures
6820 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6821 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6822 if (info != null && info.options != null && !info.options.isEmpty()) {
6823 if (disablesTrust) {
6824 if (result == null) {
6825 result = new ArrayList<>();
6827 result.add(info.options);
6829 Log.w(LOG_TAG, "Ignoring admin " + active.info
6830 + " because it has trust options but doesn't declare "
6831 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6833 } else if (disablesTrust) {
6834 allAdminsHaveOptions = false;
6838 return allAdminsHaveOptions ? result : null;
6843 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6844 Preconditions.checkNotNull(who, "ComponentName is null");
6845 synchronized (this) {
6846 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6848 int userHandle = UserHandle.getCallingUserId();
6849 DevicePolicyData userData = getUserData(userHandle);
6850 userData.mRestrictionsProvider = permissionProvider;
6851 saveSettingsLocked(userHandle);
6856 public ComponentName getRestrictionsProvider(int userHandle) {
6857 synchronized (this) {
6858 if (!isCallerWithSystemUid()) {
6859 throw new SecurityException("Only the system can query the permission provider");
6861 DevicePolicyData userData = getUserData(userHandle);
6862 return userData != null ? userData.mRestrictionsProvider : null;
6867 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6868 Preconditions.checkNotNull(who, "ComponentName is null");
6869 int callingUserId = UserHandle.getCallingUserId();
6870 synchronized (this) {
6871 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6873 long id = mInjector.binderClearCallingIdentity();
6875 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6876 if (parent == null) {
6877 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6881 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6882 mIPackageManager.addCrossProfileIntentFilter(
6883 filter, who.getPackageName(), callingUserId, parent.id, 0);
6885 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6886 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6887 parent.id, callingUserId, 0);
6889 } catch (RemoteException re) {
6892 mInjector.binderRestoreCallingIdentity(id);
6898 public void clearCrossProfileIntentFilters(ComponentName who) {
6899 Preconditions.checkNotNull(who, "ComponentName is null");
6900 int callingUserId = UserHandle.getCallingUserId();
6901 synchronized (this) {
6902 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6903 long id = mInjector.binderClearCallingIdentity();
6905 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6906 if (parent == null) {
6907 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6911 // Removing those that go from the managed profile to the parent.
6912 mIPackageManager.clearCrossProfileIntentFilters(
6913 callingUserId, who.getPackageName());
6914 // And those that go from the parent to the managed profile.
6915 // If we want to support multiple managed profiles, we will have to only remove
6916 // those that have callingUserId as their target.
6917 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6918 } catch (RemoteException re) {
6921 mInjector.binderRestoreCallingIdentity(id);
6927 * @return true if all packages in enabledPackages are either in the list
6928 * permittedList or are a system app.
6930 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6931 List<String> permittedList, int userIdToCheck) {
6932 long id = mInjector.binderClearCallingIdentity();
6934 // If we have an enabled packages list for a managed profile the packages
6935 // we should check are installed for the parent user.
6936 UserInfo user = getUserInfo(userIdToCheck);
6937 if (user.isManagedProfile()) {
6938 userIdToCheck = user.profileGroupId;
6941 for (String enabledPackage : enabledPackages) {
6942 boolean systemService = false;
6944 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
6945 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
6946 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6947 } catch (RemoteException e) {
6948 Log.i(LOG_TAG, "Can't talk to package managed", e);
6950 if (!systemService && !permittedList.contains(enabledPackage)) {
6955 mInjector.binderRestoreCallingIdentity(id);
6960 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
6961 // Not using AccessibilityManager.getInstance because that guesses
6962 // at the user you require based on callingUid and caches for a given
6964 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
6965 IAccessibilityManager service = iBinder == null
6966 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
6967 return new AccessibilityManager(mContext, service, userId);
6971 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
6975 Preconditions.checkNotNull(who, "ComponentName is null");
6977 if (packageList != null) {
6978 int userId = UserHandle.getCallingUserId();
6979 List<AccessibilityServiceInfo> enabledServices = null;
6980 long id = mInjector.binderClearCallingIdentity();
6982 UserInfo user = getUserInfo(userId);
6983 if (user.isManagedProfile()) {
6984 userId = user.profileGroupId;
6986 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
6987 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
6988 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
6990 mInjector.binderRestoreCallingIdentity(id);
6993 if (enabledServices != null) {
6994 List<String> enabledPackages = new ArrayList<String>();
6995 for (AccessibilityServiceInfo service : enabledServices) {
6996 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
6998 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7000 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
7001 + "because it contains already enabled accesibility services.");
7007 synchronized (this) {
7008 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7009 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7010 admin.permittedAccessiblityServices = packageList;
7011 saveSettingsLocked(UserHandle.getCallingUserId());
7017 public List getPermittedAccessibilityServices(ComponentName who) {
7021 Preconditions.checkNotNull(who, "ComponentName is null");
7023 synchronized (this) {
7024 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7025 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7026 return admin.permittedAccessiblityServices;
7031 public List getPermittedAccessibilityServicesForUser(int userId) {
7035 synchronized (this) {
7036 List<String> result = null;
7037 // If we have multiple profiles we return the intersection of the
7038 // permitted lists. This can happen in cases where we have a device
7039 // and profile owner.
7040 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7041 for (int profileId : profileIds) {
7042 // Just loop though all admins, only device or profiles
7043 // owners can have permitted lists set.
7044 DevicePolicyData policy = getUserDataUnchecked(profileId);
7045 final int N = policy.mAdminList.size();
7046 for (int j = 0; j < N; j++) {
7047 ActiveAdmin admin = policy.mAdminList.get(j);
7048 List<String> fromAdmin = admin.permittedAccessiblityServices;
7049 if (fromAdmin != null) {
7050 if (result == null) {
7051 result = new ArrayList<>(fromAdmin);
7053 result.retainAll(fromAdmin);
7059 // If we have a permitted list add all system accessibility services.
7060 if (result != null) {
7061 long id = mInjector.binderClearCallingIdentity();
7063 UserInfo user = getUserInfo(userId);
7064 if (user.isManagedProfile()) {
7065 userId = user.profileGroupId;
7067 AccessibilityManager accessibilityManager =
7068 getAccessibilityManagerForUser(userId);
7069 List<AccessibilityServiceInfo> installedServices =
7070 accessibilityManager.getInstalledAccessibilityServiceList();
7072 if (installedServices != null) {
7073 for (AccessibilityServiceInfo service : installedServices) {
7074 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7075 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7076 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7077 result.add(serviceInfo.packageName);
7082 mInjector.binderRestoreCallingIdentity(id);
7091 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7096 Preconditions.checkNotNull(who, "ComponentName is null");
7097 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7098 if (!isCallerWithSystemUid()){
7099 throw new SecurityException(
7100 "Only the system can query if an accessibility service is disabled by admin");
7102 synchronized (this) {
7103 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7104 if (admin == null) {
7107 if (admin.permittedAccessiblityServices == null) {
7110 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7111 admin.permittedAccessiblityServices, userHandle);
7115 private boolean checkCallerIsCurrentUserOrProfile() {
7116 int callingUserId = UserHandle.getCallingUserId();
7117 long token = mInjector.binderClearCallingIdentity();
7119 UserInfo currentUser;
7120 UserInfo callingUser = getUserInfo(callingUserId);
7122 currentUser = mInjector.getIActivityManager().getCurrentUser();
7123 } catch (RemoteException e) {
7124 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7128 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7129 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7130 + "of a user that isn't the foreground user.");
7133 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7134 Slog.e(LOG_TAG, "Cannot set permitted input methods "
7135 + "of a user that isn't the foreground user.");
7139 mInjector.binderRestoreCallingIdentity(token);
7145 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7149 Preconditions.checkNotNull(who, "ComponentName is null");
7151 // TODO When InputMethodManager supports per user calls remove
7152 // this restriction.
7153 if (!checkCallerIsCurrentUserOrProfile()) {
7157 if (packageList != null) {
7158 // InputMethodManager fetches input methods for current user.
7159 // So this can only be set when calling user is the current user
7160 // or parent is current user in case of managed profiles.
7161 InputMethodManager inputMethodManager =
7162 mContext.getSystemService(InputMethodManager.class);
7163 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7165 if (enabledImes != null) {
7166 List<String> enabledPackages = new ArrayList<String>();
7167 for (InputMethodInfo ime : enabledImes) {
7168 enabledPackages.add(ime.getPackageName());
7170 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7171 mInjector.binderGetCallingUserHandle().getIdentifier())) {
7172 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7173 + "because it contains already enabled input method.");
7179 synchronized (this) {
7180 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7181 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7182 admin.permittedInputMethods = packageList;
7183 saveSettingsLocked(UserHandle.getCallingUserId());
7189 public List getPermittedInputMethods(ComponentName who) {
7193 Preconditions.checkNotNull(who, "ComponentName is null");
7195 synchronized (this) {
7196 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7197 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7198 return admin.permittedInputMethods;
7203 public List getPermittedInputMethodsForCurrentUser() {
7204 UserInfo currentUser;
7206 currentUser = mInjector.getIActivityManager().getCurrentUser();
7207 } catch (RemoteException e) {
7208 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7209 // Activity managed is dead, just allow all IMEs
7213 int userId = currentUser.id;
7214 synchronized (this) {
7215 List<String> result = null;
7216 // If we have multiple profiles we return the intersection of the
7217 // permitted lists. This can happen in cases where we have a device
7218 // and profile owner.
7219 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7220 for (int profileId : profileIds) {
7221 // Just loop though all admins, only device or profiles
7222 // owners can have permitted lists set.
7223 DevicePolicyData policy = getUserDataUnchecked(profileId);
7224 final int N = policy.mAdminList.size();
7225 for (int j = 0; j < N; j++) {
7226 ActiveAdmin admin = policy.mAdminList.get(j);
7227 List<String> fromAdmin = admin.permittedInputMethods;
7228 if (fromAdmin != null) {
7229 if (result == null) {
7230 result = new ArrayList<String>(fromAdmin);
7232 result.retainAll(fromAdmin);
7238 // If we have a permitted list add all system input methods.
7239 if (result != null) {
7240 InputMethodManager inputMethodManager =
7241 mContext.getSystemService(InputMethodManager.class);
7242 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7243 long id = mInjector.binderClearCallingIdentity();
7246 for (InputMethodInfo ime : imes) {
7247 ServiceInfo serviceInfo = ime.getServiceInfo();
7248 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7249 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7250 result.add(serviceInfo.packageName);
7255 mInjector.binderRestoreCallingIdentity(id);
7263 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7268 Preconditions.checkNotNull(who, "ComponentName is null");
7269 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7270 if (!isCallerWithSystemUid()) {
7271 throw new SecurityException(
7272 "Only the system can query if an input method is disabled by admin");
7274 synchronized (this) {
7275 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7276 if (admin == null) {
7279 if (admin.permittedInputMethods == null) {
7282 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7283 admin.permittedInputMethods, userHandle);
7287 private void sendAdminEnabledBroadcastLocked(int userHandle) {
7288 DevicePolicyData policyData = getUserData(userHandle);
7289 if (policyData.mAdminBroadcastPending) {
7290 // Send the initialization data to profile owner and delete the data
7291 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7292 if (admin != null) {
7293 PersistableBundle initBundle = policyData.mInitBundle;
7294 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7295 initBundle == null ? null : new Bundle(initBundle), null);
7297 policyData.mInitBundle = null;
7298 policyData.mAdminBroadcastPending = false;
7299 saveSettingsLocked(userHandle);
7304 public UserHandle createAndManageUser(ComponentName admin, String name,
7305 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7306 Preconditions.checkNotNull(admin, "admin is null");
7307 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7308 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7309 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7310 + admin + " are not in the same package");
7312 // Only allow the system user to use this method
7313 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7314 throw new SecurityException("createAndManageUser was called from non-system user");
7316 if (!mInjector.userManagerIsSplitSystemUser()
7317 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7318 throw new IllegalArgumentException(
7319 "Ephemeral users are only supported on systems with a split system user.");
7322 UserHandle user = null;
7323 synchronized (this) {
7324 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7326 final long id = mInjector.binderClearCallingIdentity();
7328 int userInfoFlags = 0;
7329 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7330 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7332 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7334 if (userInfo != null) {
7335 user = userInfo.getUserHandle();
7338 mInjector.binderRestoreCallingIdentity(id);
7345 final long id = mInjector.binderClearCallingIdentity();
7347 final String adminPkg = admin.getPackageName();
7349 final int userHandle = user.getIdentifier();
7351 // Install the profile owner if not present.
7352 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7353 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7355 } catch (RemoteException e) {
7356 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7357 + "removing created user", e);
7358 mUserManager.removeUser(user.getIdentifier());
7362 setActiveAdmin(profileOwner, true, userHandle);
7363 // User is not started yet, the broadcast by setActiveAdmin will not be received.
7364 // So we store adminExtras for broadcasting when the user starts for first time.
7365 synchronized(this) {
7366 DevicePolicyData policyData = getUserData(userHandle);
7367 policyData.mInitBundle = adminExtras;
7368 policyData.mAdminBroadcastPending = true;
7369 saveSettingsLocked(userHandle);
7371 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7372 setProfileOwner(profileOwner, ownerName, userHandle);
7374 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7375 Settings.Secure.putIntForUser(mContext.getContentResolver(),
7376 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7381 mInjector.binderRestoreCallingIdentity(id);
7386 public boolean removeUser(ComponentName who, UserHandle userHandle) {
7387 Preconditions.checkNotNull(who, "ComponentName is null");
7388 synchronized (this) {
7389 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7391 long id = mInjector.binderClearCallingIdentity();
7393 return mUserManager.removeUser(userHandle.getIdentifier());
7395 mInjector.binderRestoreCallingIdentity(id);
7401 public boolean switchUser(ComponentName who, UserHandle userHandle) {
7402 Preconditions.checkNotNull(who, "ComponentName is null");
7403 synchronized (this) {
7404 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7406 long id = mInjector.binderClearCallingIdentity();
7408 int userId = UserHandle.USER_SYSTEM;
7409 if (userHandle != null) {
7410 userId = userHandle.getIdentifier();
7412 return mInjector.getIActivityManager().switchUser(userId);
7413 } catch (RemoteException e) {
7414 Log.e(LOG_TAG, "Couldn't switch user", e);
7417 mInjector.binderRestoreCallingIdentity(id);
7423 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7424 enforceCanManageApplicationRestrictions(who);
7426 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7427 final long id = mInjector.binderClearCallingIdentity();
7429 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7430 // if no restrictions were saved, mUserManager.getApplicationRestrictions
7431 // returns null, but DPM method should return an empty Bundle as per JavaDoc
7432 return bundle != null ? bundle : Bundle.EMPTY;
7434 mInjector.binderRestoreCallingIdentity(id);
7439 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7440 boolean suspended) {
7441 Preconditions.checkNotNull(who, "ComponentName is null");
7442 int callingUserId = UserHandle.getCallingUserId();
7443 synchronized (this) {
7444 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7446 long id = mInjector.binderClearCallingIdentity();
7448 return mIPackageManager.setPackagesSuspendedAsUser(
7449 packageNames, suspended, callingUserId);
7450 } catch (RemoteException re) {
7451 // Shouldn't happen.
7452 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7454 mInjector.binderRestoreCallingIdentity(id);
7456 return packageNames;
7461 public boolean isPackageSuspended(ComponentName who, String packageName) {
7462 Preconditions.checkNotNull(who, "ComponentName is null");
7463 int callingUserId = UserHandle.getCallingUserId();
7464 synchronized (this) {
7465 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7467 long id = mInjector.binderClearCallingIdentity();
7469 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7470 } catch (RemoteException re) {
7471 // Shouldn't happen.
7472 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7474 mInjector.binderRestoreCallingIdentity(id);
7481 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7482 Preconditions.checkNotNull(who, "ComponentName is null");
7483 if (!UserRestrictionsUtils.isValidRestriction(key)) {
7487 final int userHandle = mInjector.userHandleGetCallingUserId();
7488 synchronized (this) {
7489 ActiveAdmin activeAdmin =
7490 getActiveAdminForCallerLocked(who,
7491 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7492 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7493 if (isDeviceOwner) {
7494 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7495 throw new SecurityException("Device owner cannot set user restriction " + key);
7497 } else { // profile owner
7498 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7499 throw new SecurityException("Profile owner cannot set user restriction " + key);
7503 // Save the restriction to ActiveAdmin.
7504 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7505 saveSettingsLocked(userHandle);
7507 pushUserRestrictions(userHandle);
7509 sendChangedNotification(userHandle);
7513 private void pushUserRestrictions(int userId) {
7514 synchronized (this) {
7515 final Bundle global;
7516 final Bundle local = new Bundle();
7517 if (mOwners.isDeviceOwnerUserId(userId)) {
7518 global = new Bundle();
7520 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7521 if (deviceOwner == null) {
7522 return; // Shouldn't happen.
7525 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7527 // DO can disable camera globally.
7528 if (deviceOwner.disableCamera) {
7529 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7534 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7535 if (profileOwner != null) {
7536 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7539 // Also merge in *local* camera restriction.
7540 if (getCameraDisabled(/* who= */ null,
7541 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7542 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7544 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7549 public Bundle getUserRestrictions(ComponentName who) {
7553 Preconditions.checkNotNull(who, "ComponentName is null");
7554 synchronized (this) {
7555 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7556 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7557 return activeAdmin.userRestrictions;
7562 public boolean setApplicationHidden(ComponentName who, String packageName,
7564 Preconditions.checkNotNull(who, "ComponentName is null");
7565 int callingUserId = UserHandle.getCallingUserId();
7566 synchronized (this) {
7567 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7569 long id = mInjector.binderClearCallingIdentity();
7571 return mIPackageManager.setApplicationHiddenSettingAsUser(
7572 packageName, hidden, callingUserId);
7573 } catch (RemoteException re) {
7575 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7577 mInjector.binderRestoreCallingIdentity(id);
7584 public boolean isApplicationHidden(ComponentName who, String packageName) {
7585 Preconditions.checkNotNull(who, "ComponentName is null");
7586 int callingUserId = UserHandle.getCallingUserId();
7587 synchronized (this) {
7588 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7590 long id = mInjector.binderClearCallingIdentity();
7592 return mIPackageManager.getApplicationHiddenSettingAsUser(
7593 packageName, callingUserId);
7594 } catch (RemoteException re) {
7596 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7598 mInjector.binderRestoreCallingIdentity(id);
7605 public void enableSystemApp(ComponentName who, String packageName) {
7606 Preconditions.checkNotNull(who, "ComponentName is null");
7607 synchronized (this) {
7608 // This API can only be called by an active device admin,
7609 // so try to retrieve it to check that the caller is one.
7610 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7612 int userId = UserHandle.getCallingUserId();
7613 long id = mInjector.binderClearCallingIdentity();
7617 Slog.v(LOG_TAG, "installing " + packageName + " for "
7621 int parentUserId = getProfileParentId(userId);
7622 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7623 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7627 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7629 } catch (RemoteException re) {
7631 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7633 mInjector.binderRestoreCallingIdentity(id);
7639 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7640 Preconditions.checkNotNull(who, "ComponentName is null");
7641 synchronized (this) {
7642 // This API can only be called by an active device admin,
7643 // so try to retrieve it to check that the caller is one.
7644 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7646 int userId = UserHandle.getCallingUserId();
7647 long id = mInjector.binderClearCallingIdentity();
7650 int parentUserId = getProfileParentId(userId);
7651 List<ResolveInfo> activitiesToEnable = mIPackageManager
7652 .queryIntentActivities(intent,
7653 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7654 PackageManager.MATCH_DIRECT_BOOT_AWARE
7655 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7660 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7662 int numberOfAppsInstalled = 0;
7663 if (activitiesToEnable != null) {
7664 for (ResolveInfo info : activitiesToEnable) {
7665 if (info.activityInfo != null) {
7666 String packageName = info.activityInfo.packageName;
7667 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7668 numberOfAppsInstalled++;
7669 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7671 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7677 return numberOfAppsInstalled;
7678 } catch (RemoteException e) {
7680 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7683 mInjector.binderRestoreCallingIdentity(id);
7688 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7689 throws RemoteException {
7690 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7692 if (appInfo == null) {
7693 throw new IllegalArgumentException("The application " + packageName +
7694 " is not present on this device");
7696 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7700 public void setAccountManagementDisabled(ComponentName who, String accountType,
7705 Preconditions.checkNotNull(who, "ComponentName is null");
7706 synchronized (this) {
7707 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7708 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7710 ap.accountTypesWithManagementDisabled.add(accountType);
7712 ap.accountTypesWithManagementDisabled.remove(accountType);
7714 saveSettingsLocked(UserHandle.getCallingUserId());
7719 public String[] getAccountTypesWithManagementDisabled() {
7720 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7724 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7725 enforceFullCrossUsersPermission(userId);
7729 synchronized (this) {
7730 DevicePolicyData policy = getUserData(userId);
7731 final int N = policy.mAdminList.size();
7732 ArraySet<String> resultSet = new ArraySet<>();
7733 for (int i = 0; i < N; i++) {
7734 ActiveAdmin admin = policy.mAdminList.get(i);
7735 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7737 return resultSet.toArray(new String[resultSet.size()]);
7742 public void setUninstallBlocked(ComponentName who, String packageName,
7743 boolean uninstallBlocked) {
7744 Preconditions.checkNotNull(who, "ComponentName is null");
7745 final int userId = UserHandle.getCallingUserId();
7746 synchronized (this) {
7747 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7749 long id = mInjector.binderClearCallingIdentity();
7751 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7752 } catch (RemoteException re) {
7753 // Shouldn't happen.
7754 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7756 mInjector.binderRestoreCallingIdentity(id);
7762 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7763 // This function should return true if and only if the package is blocked by
7764 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7765 // when the package is a system app, or when it is an active device admin.
7766 final int userId = UserHandle.getCallingUserId();
7768 synchronized (this) {
7770 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7773 long id = mInjector.binderClearCallingIdentity();
7775 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7776 } catch (RemoteException re) {
7777 // Shouldn't happen.
7778 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7780 mInjector.binderRestoreCallingIdentity(id);
7787 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7791 Preconditions.checkNotNull(who, "ComponentName is null");
7792 synchronized (this) {
7793 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7794 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7795 if (admin.disableCallerId != disabled) {
7796 admin.disableCallerId = disabled;
7797 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7803 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7807 Preconditions.checkNotNull(who, "ComponentName is null");
7808 synchronized (this) {
7809 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7810 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7811 return admin.disableCallerId;
7816 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7817 enforceCrossUsersPermission(userId);
7818 synchronized (this) {
7819 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7820 return (admin != null) ? admin.disableCallerId : false;
7825 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7829 Preconditions.checkNotNull(who, "ComponentName is null");
7830 synchronized (this) {
7831 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7832 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7833 if (admin.disableContactsSearch != disabled) {
7834 admin.disableContactsSearch = disabled;
7835 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7841 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7845 Preconditions.checkNotNull(who, "ComponentName is null");
7846 synchronized (this) {
7847 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7848 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7849 return admin.disableContactsSearch;
7854 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7855 enforceCrossUsersPermission(userId);
7856 synchronized (this) {
7857 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7858 return (admin != null) ? admin.disableContactsSearch : false;
7863 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7864 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7865 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7866 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7867 final int callingUserId = UserHandle.getCallingUserId();
7869 final long ident = mInjector.binderClearCallingIdentity();
7871 synchronized (this) {
7872 final int managedUserId = getManagedUserId(callingUserId);
7873 if (managedUserId < 0) {
7876 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7879 "Cross-profile contacts access disabled for user " + managedUserId);
7883 ContactsInternal.startQuickContactWithErrorToastForUser(
7884 mContext, intent, new UserHandle(managedUserId));
7887 mInjector.binderRestoreCallingIdentity(ident);
7892 * @return true if cross-profile QuickContact is disabled
7894 private boolean isCrossProfileQuickContactDisabled(int userId) {
7895 return getCrossProfileCallerIdDisabledForUser(userId)
7896 && getCrossProfileContactsSearchDisabledForUser(userId);
7900 * @return the user ID of the managed user that is linked to the current user, if any.
7903 public int getManagedUserId(int callingUserId) {
7905 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7908 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7909 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7910 continue; // Caller user self, or not a managed profile. Skip.
7913 Log.v(LOG_TAG, "Managed user=" + ui.id);
7918 Log.v(LOG_TAG, "Managed user not found.");
7924 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7928 Preconditions.checkNotNull(who, "ComponentName is null");
7929 synchronized (this) {
7930 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7931 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7932 if (admin.disableBluetoothContactSharing != disabled) {
7933 admin.disableBluetoothContactSharing = disabled;
7934 saveSettingsLocked(UserHandle.getCallingUserId());
7940 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
7944 Preconditions.checkNotNull(who, "ComponentName is null");
7945 synchronized (this) {
7946 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7947 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7948 return admin.disableBluetoothContactSharing;
7953 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
7954 // TODO: Should there be a check to make sure this relationship is
7955 // within a profile group?
7956 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
7957 synchronized (this) {
7958 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7959 return (admin != null) ? admin.disableBluetoothContactSharing : false;
7964 * Sets which packages may enter lock task mode.
7966 * <p>This function can only be called by the device owner or alternatively by the profile owner
7967 * in case the user is affiliated.
7969 * @param packages The list of packages allowed to enter lock task mode.
7972 public void setLockTaskPackages(ComponentName who, String[] packages)
7973 throws SecurityException {
7974 Preconditions.checkNotNull(who, "ComponentName is null");
7975 synchronized (this) {
7976 ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
7977 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
7978 ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
7979 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
7980 if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
7981 int userHandle = mInjector.userHandleGetCallingUserId();
7982 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
7984 throw new SecurityException("Admin " + who +
7985 " is neither the device owner or affiliated user's profile owner.");
7990 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
7991 DevicePolicyData policy = getUserData(userHandle);
7992 policy.mLockTaskPackages = packages;
7994 // Store the settings persistently.
7995 saveSettingsLocked(userHandle);
7996 updateLockTaskPackagesLocked(packages, userHandle);
8000 * This function returns the list of components allowed to start the task lock mode.
8003 public String[] getLockTaskPackages(ComponentName who) {
8004 Preconditions.checkNotNull(who, "ComponentName is null");
8005 synchronized (this) {
8006 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8007 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
8008 final List<String> packages = getLockTaskPackagesLocked(userHandle);
8009 return packages.toArray(new String[packages.size()]);
8013 private List<String> getLockTaskPackagesLocked(int userHandle) {
8014 final DevicePolicyData policy = getUserData(userHandle);
8015 return policy.mLockTaskPackages;
8019 * This function lets the caller know whether the given package is allowed to start the
8021 * @param pkg The package to check
8024 public boolean isLockTaskPermitted(String pkg) {
8025 // Get current user's devicepolicy
8026 int uid = mInjector.binderGetCallingUid();
8027 int userHandle = UserHandle.getUserId(uid);
8028 DevicePolicyData policy = getUserData(userHandle);
8029 synchronized (this) {
8030 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
8031 String lockTaskPackage = policy.mLockTaskPackages.get(i);
8033 // If the given package equals one of the packages stored our list,
8034 // we allow this package to start lock task mode.
8035 if (lockTaskPackage.equals(pkg)) {
8044 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
8045 if (!isCallerWithSystemUid()) {
8046 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
8048 synchronized (this) {
8049 final DevicePolicyData policy = getUserData(userHandle);
8050 Bundle adminExtras = new Bundle();
8051 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
8052 for (ActiveAdmin admin : policy.mAdminList) {
8053 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
8054 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
8055 if (ownsDevice || ownsProfile) {
8057 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
8060 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
8068 public void setGlobalSetting(ComponentName who, String setting, String value) {
8069 Preconditions.checkNotNull(who, "ComponentName is null");
8071 synchronized (this) {
8072 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8074 // Some settings are no supported any more. However we do not want to throw a
8075 // SecurityException to avoid breaking apps.
8076 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
8077 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
8081 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
8082 throw new SecurityException(String.format(
8083 "Permission denial: device owners cannot update %1$s", setting));
8086 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
8087 // ignore if it contradicts an existing policy
8088 long timeMs = getMaximumTimeToLock(
8089 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
8090 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
8095 long id = mInjector.binderClearCallingIdentity();
8097 mInjector.settingsGlobalPutString(setting, value);
8099 mInjector.binderRestoreCallingIdentity(id);
8105 public void setSecureSetting(ComponentName who, String setting, String value) {
8106 Preconditions.checkNotNull(who, "ComponentName is null");
8107 int callingUserId = mInjector.userHandleGetCallingUserId();
8109 synchronized (this) {
8110 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8112 if (isDeviceOwner(who, callingUserId)) {
8113 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
8114 throw new SecurityException(String.format(
8115 "Permission denial: Device owners cannot update %1$s", setting));
8117 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
8118 throw new SecurityException(String.format(
8119 "Permission denial: Profile owners cannot update %1$s", setting));
8122 long id = mInjector.binderClearCallingIdentity();
8124 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
8126 mInjector.binderRestoreCallingIdentity(id);
8132 public void setMasterVolumeMuted(ComponentName who, boolean on) {
8133 Preconditions.checkNotNull(who, "ComponentName is null");
8134 synchronized (this) {
8135 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8136 setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
8141 public boolean isMasterVolumeMuted(ComponentName who) {
8142 Preconditions.checkNotNull(who, "ComponentName is null");
8143 synchronized (this) {
8144 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8146 AudioManager audioManager =
8147 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
8148 return audioManager.isMasterMute();
8153 public void setUserIcon(ComponentName who, Bitmap icon) {
8154 synchronized (this) {
8155 Preconditions.checkNotNull(who, "ComponentName is null");
8156 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8158 int userId = UserHandle.getCallingUserId();
8159 long id = mInjector.binderClearCallingIdentity();
8161 mUserManagerInternal.setUserIcon(userId, icon);
8163 mInjector.binderRestoreCallingIdentity(id);
8169 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8170 Preconditions.checkNotNull(who, "ComponentName is null");
8171 synchronized (this) {
8172 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8174 final int userId = UserHandle.getCallingUserId();
8176 long ident = mInjector.binderClearCallingIdentity();
8178 // disallow disabling the keyguard if a password is currently set
8179 if (disabled && mLockPatternUtils.isSecure(userId)) {
8182 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8184 mInjector.binderRestoreCallingIdentity(ident);
8190 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8191 int userId = UserHandle.getCallingUserId();
8192 synchronized (this) {
8193 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8194 DevicePolicyData policy = getUserData(userId);
8195 if (policy.mStatusBarDisabled != disabled) {
8196 if (!setStatusBarDisabledInternal(disabled, userId)) {
8199 policy.mStatusBarDisabled = disabled;
8200 saveSettingsLocked(userId);
8206 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8207 long ident = mInjector.binderClearCallingIdentity();
8209 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8210 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8211 if (statusBarService != null) {
8212 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8213 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8214 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8215 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8218 } catch (RemoteException e) {
8219 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8221 mInjector.binderRestoreCallingIdentity(ident);
8227 * We need to update the internal state of whether a user has completed setup or a
8228 * device has paired once. After that, we ignore any changes that reset the
8229 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
8230 * as we don't trust any apps that might try to reset them.
8232 * Unfortunately, we don't know which user's setup state was changed, so we write all of
8235 void updateUserSetupCompleteAndPaired() {
8236 List<UserInfo> users = mUserManager.getUsers(true);
8237 final int N = users.size();
8238 for (int i = 0; i < N; i++) {
8239 int userHandle = users.get(i).id;
8240 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8242 DevicePolicyData policy = getUserData(userHandle);
8243 if (!policy.mUserSetupComplete) {
8244 policy.mUserSetupComplete = true;
8245 synchronized (this) {
8246 saveSettingsLocked(userHandle);
8250 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
8252 DevicePolicyData policy = getUserData(userHandle);
8253 if (!policy.mPaired) {
8254 policy.mPaired = true;
8255 synchronized (this) {
8256 saveSettingsLocked(userHandle);
8263 private class SetupContentObserver extends ContentObserver {
8265 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8266 Settings.Secure.USER_SETUP_COMPLETE);
8267 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8268 Settings.Global.DEVICE_PROVISIONED);
8269 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
8271 public SetupContentObserver(Handler handler) {
8276 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8277 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8279 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
8284 public void onChange(boolean selfChange, Uri uri) {
8285 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
8286 updateUserSetupCompleteAndPaired();
8287 } else if (mDeviceProvisioned.equals(uri)) {
8288 synchronized (DevicePolicyManagerService.this) {
8289 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8290 // is delayed until device is marked as provisioned.
8291 setDeviceOwnerSystemPropertyLocked();
8298 final class LocalService extends DevicePolicyManagerInternal {
8299 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8302 public List<String> getCrossProfileWidgetProviders(int profileId) {
8303 synchronized (DevicePolicyManagerService.this) {
8304 if (mOwners == null) {
8305 return Collections.emptyList();
8307 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8308 if (ownerComponent == null) {
8309 return Collections.emptyList();
8312 DevicePolicyData policy = getUserDataUnchecked(profileId);
8313 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8315 if (admin == null || admin.crossProfileWidgetProviders == null
8316 || admin.crossProfileWidgetProviders.isEmpty()) {
8317 return Collections.emptyList();
8320 return admin.crossProfileWidgetProviders;
8325 public void addOnCrossProfileWidgetProvidersChangeListener(
8326 OnCrossProfileWidgetProvidersChangeListener listener) {
8327 synchronized (DevicePolicyManagerService.this) {
8328 if (mWidgetProviderListeners == null) {
8329 mWidgetProviderListeners = new ArrayList<>();
8331 if (!mWidgetProviderListeners.contains(listener)) {
8332 mWidgetProviderListeners.add(listener);
8338 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8339 synchronized(DevicePolicyManagerService.this) {
8340 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8344 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8345 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8346 synchronized (DevicePolicyManagerService.this) {
8347 listeners = new ArrayList<>(mWidgetProviderListeners);
8349 final int listenerCount = listeners.size();
8350 for (int i = 0; i < listenerCount; i++) {
8351 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8352 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8357 public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
8358 Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8359 intent.putExtra(Intent.EXTRA_USER_ID, userId);
8360 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8362 // This method is called from AM with its lock held, so don't take the DPMS lock.
8365 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8366 if (profileOwner != null) {
8367 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
8371 final Pair<Integer, ComponentName> deviceOwner =
8372 mOwners.getDeviceOwnerUserIdAndComponent();
8373 if (deviceOwner != null && deviceOwner.first == userId) {
8374 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
8378 // We're not specifying the device admin because there isn't one.
8384 * Returns true if specified admin is allowed to limit passwords and has a
8385 * {@code passwordQuality} of at least {@code minPasswordQuality}
8387 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8388 if (admin.passwordQuality < minPasswordQuality) {
8391 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8395 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8396 if (policy != null && !policy.isValid()) {
8397 throw new IllegalArgumentException("Invalid system update policy.");
8399 synchronized (this) {
8400 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8401 if (policy == null) {
8402 mOwners.clearSystemUpdatePolicy();
8404 mOwners.setSystemUpdatePolicy(policy);
8406 mOwners.writeDeviceOwner();
8408 mContext.sendBroadcastAsUser(
8409 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8414 public SystemUpdatePolicy getSystemUpdatePolicy() {
8415 if (UserManager.isDeviceInDemoMode(mContext)) {
8416 // Pretending to have an automatic update policy when the device is in retail demo
8417 // mode. This will allow the device to download and install an ota without
8418 // any user interaction.
8419 return SystemUpdatePolicy.createAutomaticInstallPolicy();
8421 synchronized (this) {
8422 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
8423 if (policy != null && !policy.isValid()) {
8424 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8432 * Checks if the caller of the method is the device owner app.
8434 * @param callerUid UID of the caller.
8435 * @return true if the caller is the device owner app
8438 boolean isCallerDeviceOwner(int callerUid) {
8439 synchronized (this) {
8440 if (!mOwners.hasDeviceOwner()) {
8443 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8446 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8448 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8450 for (String pkg : pkgs) {
8451 if (deviceOwnerPackageName.equals(pkg)) {
8461 public void notifyPendingSystemUpdate(long updateReceivedTime) {
8462 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8463 "Only the system update service can broadcast update information");
8465 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8466 Slog.w(LOG_TAG, "Only the system update service in the system user " +
8467 "can broadcast update information.");
8470 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8471 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8472 updateReceivedTime);
8474 synchronized (this) {
8475 final String deviceOwnerPackage =
8476 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8478 if (deviceOwnerPackage == null) {
8481 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8483 ActivityInfo[] receivers = null;
8485 receivers = mContext.getPackageManager().getPackageInfo(
8486 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8487 } catch (NameNotFoundException e) {
8488 Log.e(LOG_TAG, "Cannot find device owner package", e);
8490 if (receivers != null) {
8491 long ident = mInjector.binderClearCallingIdentity();
8493 for (int i = 0; i < receivers.length; i++) {
8494 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8495 intent.setComponent(new ComponentName(deviceOwnerPackage,
8496 receivers[i].name));
8497 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8501 mInjector.binderRestoreCallingIdentity(ident);
8508 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8509 int userId = UserHandle.getCallingUserId();
8510 synchronized (this) {
8511 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8512 DevicePolicyData userPolicy = getUserData(userId);
8513 if (userPolicy.mPermissionPolicy != policy) {
8514 userPolicy.mPermissionPolicy = policy;
8515 saveSettingsLocked(userId);
8521 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8522 int userId = UserHandle.getCallingUserId();
8523 synchronized (this) {
8524 DevicePolicyData userPolicy = getUserData(userId);
8525 return userPolicy.mPermissionPolicy;
8530 public boolean setPermissionGrantState(ComponentName admin, String packageName,
8531 String permission, int grantState) throws RemoteException {
8532 UserHandle user = mInjector.binderGetCallingUserHandle();
8533 synchronized (this) {
8534 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8535 long ident = mInjector.binderClearCallingIdentity();
8537 if (getTargetSdk(packageName, user.getIdentifier())
8538 < android.os.Build.VERSION_CODES.M) {
8541 final PackageManager packageManager = mContext.getPackageManager();
8542 switch (grantState) {
8543 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8544 packageManager.grantRuntimePermission(packageName, permission, user);
8545 packageManager.updatePermissionFlags(permission, packageName,
8546 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8547 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8550 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8551 packageManager.revokeRuntimePermission(packageName,
8553 packageManager.updatePermissionFlags(permission, packageName,
8554 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8555 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8558 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8559 packageManager.updatePermissionFlags(permission, packageName,
8560 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8564 } catch (SecurityException se) {
8567 mInjector.binderRestoreCallingIdentity(ident);
8573 public int getPermissionGrantState(ComponentName admin, String packageName,
8574 String permission) throws RemoteException {
8575 PackageManager packageManager = mContext.getPackageManager();
8577 UserHandle user = mInjector.binderGetCallingUserHandle();
8578 synchronized (this) {
8579 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8580 long ident = mInjector.binderClearCallingIdentity();
8582 int granted = mIPackageManager.checkPermission(permission,
8583 packageName, user.getIdentifier());
8584 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8585 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8586 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8587 // Not controlled by policy
8588 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8590 // Policy controlled so return result based on permission grant state
8591 return granted == PackageManager.PERMISSION_GRANTED
8592 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8593 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8596 mInjector.binderRestoreCallingIdentity(ident);
8601 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8603 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8605 return (pi != null) && (pi.applicationInfo.flags != 0);
8606 } catch (RemoteException re) {
8607 throw new RuntimeException("Package manager has died", re);
8612 public boolean isProvisioningAllowed(String action) {
8617 final int callingUserId = mInjector.userHandleGetCallingUserId();
8618 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8619 if (!hasFeatureManagedUsers()) {
8622 synchronized (this) {
8623 if (mOwners.hasDeviceOwner()) {
8624 if (!mInjector.userManagerIsSplitSystemUser()) {
8625 // Only split-system-user systems support managed-profiles in combination with
8629 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8630 // Only system device-owner supports managed-profiles. Non-system device-owner
8634 if (callingUserId == UserHandle.USER_SYSTEM) {
8635 // Managed-profiles cannot be setup on the system user, only regular users.
8640 if (getProfileOwner(callingUserId) != null) {
8641 // Managed user cannot have a managed profile.
8644 final long ident = mInjector.binderClearCallingIdentity();
8646 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8650 mInjector.binderRestoreCallingIdentity(ident);
8653 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8654 return isDeviceOwnerProvisioningAllowed(callingUserId);
8655 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8656 if (!hasFeatureManagedUsers()) {
8659 if (!mInjector.userManagerIsSplitSystemUser()) {
8660 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8663 if (callingUserId == UserHandle.USER_SYSTEM) {
8664 // System user cannot be a managed user.
8667 if (hasUserSetupCompleted(callingUserId)) {
8670 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8674 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8675 if (!mInjector.userManagerIsSplitSystemUser()) {
8676 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8679 return isDeviceOwnerProvisioningAllowed(callingUserId);
8681 throw new IllegalArgumentException("Unknown provisioning action " + action);
8685 * The device owner can only be set before the setup phase of the primary user has completed,
8686 * except for adb command if no accounts or additional users are present on the device.
8688 private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreConditionLocked(
8689 @Nullable ComponentName owner, int deviceOwnerUserId, boolean isAdb) {
8690 if (mOwners.hasDeviceOwner()) {
8691 return CODE_HAS_DEVICE_OWNER;
8693 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8694 return CODE_USER_HAS_PROFILE_OWNER;
8696 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8697 return CODE_USER_NOT_RUNNING;
8699 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8700 return CODE_HAS_PAIRED;
8703 // if shell command runs after user setup completed check device status. Otherwise, OK.
8704 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8705 if (!mInjector.userManagerIsSplitSystemUser()) {
8706 if (mUserManager.getUserCount() > 1) {
8707 return CODE_NONSYSTEM_USER_EXISTS;
8709 if (hasIncompatibleAccountsLocked(UserHandle.USER_SYSTEM, owner)) {
8710 return CODE_ACCOUNTS_NOT_EMPTY;
8713 // STOPSHIP Do proper check in split user mode
8718 if (!mInjector.userManagerIsSplitSystemUser()) {
8719 // In non-split user mode, DO has to be user 0
8720 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8721 return CODE_NOT_SYSTEM_USER;
8723 // In non-split user mode, only provision DO before setup wizard completes
8724 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8725 return CODE_USER_SETUP_COMPLETED;
8728 // STOPSHIP Do proper check in split user mode
8734 private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8735 synchronized (this) {
8736 return CODE_OK == checkSetDeviceOwnerPreConditionLocked(
8737 /* owner unknown */ null, deviceOwnerUserId, /* isAdb */ false);
8741 private boolean hasFeatureManagedUsers() {
8743 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8744 } catch (RemoteException e) {
8750 public String getWifiMacAddress(ComponentName admin) {
8751 // Make sure caller has DO.
8752 synchronized (this) {
8753 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8756 final long ident = mInjector.binderClearCallingIdentity();
8758 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8759 if (wifiInfo == null) {
8762 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8764 mInjector.binderRestoreCallingIdentity(ident);
8769 * Returns the target sdk version number that the given packageName was built for
8770 * in the given user.
8772 private int getTargetSdk(String packageName, int userId) {
8773 final ApplicationInfo ai;
8775 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8776 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8777 return targetSdkVersion;
8778 } catch (RemoteException e) {
8785 public boolean isManagedProfile(ComponentName admin) {
8786 synchronized (this) {
8787 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8789 final int callingUserId = mInjector.userHandleGetCallingUserId();
8790 final UserInfo user = getUserInfo(callingUserId);
8791 return user != null && user.isManagedProfile();
8795 public boolean isSystemOnlyUser(ComponentName admin) {
8796 synchronized (this) {
8797 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8799 final int callingUserId = mInjector.userHandleGetCallingUserId();
8800 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8804 public void reboot(ComponentName admin) {
8805 Preconditions.checkNotNull(admin);
8806 // Make sure caller has DO.
8807 synchronized (this) {
8808 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8810 long ident = mInjector.binderClearCallingIdentity();
8812 // Make sure there are no ongoing calls on the device.
8813 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8814 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8816 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8818 mInjector.binderRestoreCallingIdentity(ident);
8823 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8827 Preconditions.checkNotNull(who, "ComponentName is null");
8828 final int userHandle = mInjector.userHandleGetCallingUserId();
8829 synchronized (this) {
8830 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8831 mInjector.binderGetCallingUid());
8832 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8833 admin.shortSupportMessage = message;
8834 saveSettingsLocked(userHandle);
8840 public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8844 Preconditions.checkNotNull(who, "ComponentName is null");
8845 synchronized (this) {
8846 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8847 mInjector.binderGetCallingUid());
8848 return admin.shortSupportMessage;
8853 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8857 Preconditions.checkNotNull(who, "ComponentName is null");
8858 final int userHandle = mInjector.userHandleGetCallingUserId();
8859 synchronized (this) {
8860 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8861 mInjector.binderGetCallingUid());
8862 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8863 admin.longSupportMessage = message;
8864 saveSettingsLocked(userHandle);
8870 public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8874 Preconditions.checkNotNull(who, "ComponentName is null");
8875 synchronized (this) {
8876 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8877 mInjector.binderGetCallingUid());
8878 return admin.longSupportMessage;
8883 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8887 Preconditions.checkNotNull(who, "ComponentName is null");
8888 if (!isCallerWithSystemUid()) {
8889 throw new SecurityException("Only the system can query support message for user");
8891 synchronized (this) {
8892 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8893 if (admin != null) {
8894 return admin.shortSupportMessage;
8901 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8905 Preconditions.checkNotNull(who, "ComponentName is null");
8906 if (!isCallerWithSystemUid()) {
8907 throw new SecurityException("Only the system can query support message for user");
8909 synchronized (this) {
8910 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8911 if (admin != null) {
8912 return admin.longSupportMessage;
8919 public void setOrganizationColor(@NonNull ComponentName who, int color) {
8923 Preconditions.checkNotNull(who, "ComponentName is null");
8924 final int userHandle = mInjector.userHandleGetCallingUserId();
8925 enforceManagedProfile(userHandle, "set organization color");
8926 synchronized (this) {
8927 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8928 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8929 admin.organizationColor = color;
8930 saveSettingsLocked(userHandle);
8935 public void setOrganizationColorForUser(int color, int userId) {
8939 enforceFullCrossUsersPermission(userId);
8940 enforceManageUsers();
8941 enforceManagedProfile(userId, "set organization color");
8942 synchronized (this) {
8943 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8944 admin.organizationColor = color;
8945 saveSettingsLocked(userId);
8950 public int getOrganizationColor(@NonNull ComponentName who) {
8952 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8954 Preconditions.checkNotNull(who, "ComponentName is null");
8955 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
8956 synchronized (this) {
8957 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8958 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8959 return admin.organizationColor;
8964 public int getOrganizationColorForUser(int userHandle) {
8966 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8968 enforceFullCrossUsersPermission(userHandle);
8969 enforceManagedProfile(userHandle, "get organization color");
8970 synchronized (this) {
8971 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8972 return (profileOwner != null)
8973 ? profileOwner.organizationColor
8974 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
8979 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
8983 Preconditions.checkNotNull(who, "ComponentName is null");
8984 final int userHandle = mInjector.userHandleGetCallingUserId();
8985 enforceManagedProfile(userHandle, "set organization name");
8986 synchronized (this) {
8987 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8988 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8989 if (!TextUtils.equals(admin.organizationName, text)) {
8990 admin.organizationName = (text == null || text.length() == 0)
8991 ? null : text.toString();
8992 saveSettingsLocked(userHandle);
8998 public CharSequence getOrganizationName(@NonNull ComponentName who) {
9002 Preconditions.checkNotNull(who, "ComponentName is null");
9003 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
9004 synchronized(this) {
9005 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9006 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9007 return admin.organizationName;
9012 public CharSequence getOrganizationNameForUser(int userHandle) {
9016 enforceFullCrossUsersPermission(userHandle);
9017 enforceManagedProfile(userHandle, "get organization name");
9018 synchronized (this) {
9019 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9020 return (profileOwner != null)
9021 ? profileOwner.organizationName
9027 public void setAffiliationIds(ComponentName admin, List<String> ids) {
9028 final Set<String> affiliationIds = new ArraySet<String>(ids);
9029 final int callingUserId = mInjector.userHandleGetCallingUserId();
9031 synchronized (this) {
9032 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9033 getUserData(callingUserId).mAffiliationIds = affiliationIds;
9034 saveSettingsLocked(callingUserId);
9035 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
9036 // Affiliation ids specified by the device owner are additionally stored in
9037 // UserHandle.USER_SYSTEM's DevicePolicyData.
9038 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
9039 saveSettingsLocked(UserHandle.USER_SYSTEM);
9045 public boolean isAffiliatedUser() {
9046 final int callingUserId = mInjector.userHandleGetCallingUserId();
9048 synchronized (this) {
9049 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
9050 // The user that the DO is installed on is always affiliated.
9053 final ComponentName profileOwner = getProfileOwner(callingUserId);
9054 if (profileOwner == null
9055 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
9058 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
9059 final Set<String> deviceAffiliationIds =
9060 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
9061 for (String id : userAffiliationIds) {
9062 if (deviceAffiliationIds.contains(id)) {
9070 private synchronized void disableDeviceOwnerManagedSingleUserFeaturesIfNeeded() {
9071 if (!isDeviceOwnerManagedSingleUserDevice()) {
9072 mInjector.securityLogSetLoggingEnabledProperty(false);
9073 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user device.");
9074 if (mOwners.hasDeviceOwner()) {
9075 setBackupServiceEnabledInternal(false);
9076 Slog.w(LOG_TAG, "Backup is off as it's a managed device that has more that one user.");
9082 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
9083 Preconditions.checkNotNull(admin);
9084 ensureDeviceOwnerManagingSingleUser(admin);
9086 synchronized (this) {
9087 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
9090 mInjector.securityLogSetLoggingEnabledProperty(enabled);
9092 mSecurityLogMonitor.start();
9094 mSecurityLogMonitor.stop();
9100 public boolean isSecurityLoggingEnabled(ComponentName admin) {
9101 Preconditions.checkNotNull(admin);
9102 synchronized (this) {
9103 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9104 return mInjector.securityLogGetLoggingEnabledProperty();
9109 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
9110 Preconditions.checkNotNull(admin);
9111 ensureDeviceOwnerManagingSingleUser(admin);
9113 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
9117 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
9119 SecurityLog.readPreviousEvents(output);
9120 return new ParceledListSlice<SecurityEvent>(output);
9121 } catch (IOException e) {
9122 Slog.w(LOG_TAG, "Fail to read previous events" , e);
9123 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
9128 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
9129 Preconditions.checkNotNull(admin);
9130 ensureDeviceOwnerManagingSingleUser(admin);
9132 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
9133 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
9136 private void enforceCanManageDeviceAdmin() {
9137 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
9141 private void enforceCanManageProfileAndDeviceOwners() {
9142 mContext.enforceCallingOrSelfPermission(
9143 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
9147 public boolean isUninstallInQueue(final String packageName) {
9148 enforceCanManageDeviceAdmin();
9149 final int userId = mInjector.userHandleGetCallingUserId();
9150 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9151 synchronized (this) {
9152 return mPackagesToRemove.contains(packageUserPair);
9157 public void uninstallPackageWithActiveAdmins(final String packageName) {
9158 enforceCanManageDeviceAdmin();
9159 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
9161 final int userId = mInjector.userHandleGetCallingUserId();
9163 enforceUserUnlocked(userId);
9165 final ComponentName profileOwner = getProfileOwner(userId);
9166 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
9167 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
9170 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
9171 if (getDeviceOwnerUserId() == userId && deviceOwner != null
9172 && packageName.equals(deviceOwner.getPackageName())) {
9173 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
9176 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9177 synchronized (this) {
9178 mPackagesToRemove.add(packageUserPair);
9181 // All active admins on the user.
9182 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
9184 // Active admins in the target package.
9185 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
9186 if (allActiveAdmins != null) {
9187 for (ComponentName activeAdmin : allActiveAdmins) {
9188 if (packageName.equals(activeAdmin.getPackageName())) {
9189 packageActiveAdmins.add(activeAdmin);
9190 removeActiveAdmin(activeAdmin, userId);
9194 if (packageActiveAdmins.size() == 0) {
9195 startUninstallIntent(packageName, userId);
9197 mHandler.postDelayed(new Runnable() {
9200 for (ComponentName activeAdmin : packageActiveAdmins) {
9201 removeAdminArtifacts(activeAdmin, userId);
9203 startUninstallIntent(packageName, userId);
9205 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9210 public boolean isDeviceProvisioned() {
9211 return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9214 private void removePackageIfRequired(final String packageName, final int userId) {
9215 if (!packageHasActiveAdmins(packageName, userId)) {
9216 // Will not do anything if uninstall was not requested or was already started.
9217 startUninstallIntent(packageName, userId);
9221 private void startUninstallIntent(final String packageName, final int userId) {
9222 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9223 synchronized (this) {
9224 if (!mPackagesToRemove.contains(packageUserPair)) {
9225 // Do nothing if uninstall was not requested or was already started.
9228 mPackagesToRemove.remove(packageUserPair);
9231 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9232 // Package does not exist. Nothing to do.
9235 } catch (RemoteException re) {
9236 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9239 try { // force stop the package before uninstalling
9240 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9241 } catch (RemoteException re) {
9242 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9244 final Uri packageURI = Uri.parse("package:" + packageName);
9245 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9246 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9247 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9251 * Removes the admin from the policy. Ideally called after the admin's
9252 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9254 * @param adminReceiver The admin to remove
9255 * @param userHandle The user for which this admin has to be removed.
9257 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9258 synchronized (this) {
9259 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9260 if (admin == null) {
9263 final DevicePolicyData policy = getUserData(userHandle);
9264 final boolean doProxyCleanup = admin.info.usesPolicy(
9265 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9266 policy.mAdminList.remove(admin);
9267 policy.mAdminMap.remove(adminReceiver);
9268 validatePasswordOwnerLocked(policy);
9269 if (doProxyCleanup) {
9270 resetGlobalProxyLocked(policy);
9272 saveSettingsLocked(userHandle);
9273 updateMaximumTimeToLockLocked(userHandle);
9274 policy.mRemovingAdmins.remove(adminReceiver);
9276 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
9278 // The removed admin might have disabled camera, so update user
9280 pushUserRestrictions(userHandle);
9284 public void setDeviceProvisioningConfigApplied() {
9285 enforceManageUsers();
9286 synchronized (this) {
9287 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9288 policy.mDeviceProvisioningConfigApplied = true;
9289 saveSettingsLocked(UserHandle.USER_SYSTEM);
9294 public boolean isDeviceProvisioningConfigApplied() {
9295 enforceManageUsers();
9296 synchronized (this) {
9297 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9298 return policy.mDeviceProvisioningConfigApplied;
9303 * Return true if a given user has any accounts that'll prevent installing a device or profile
9304 * owner {@code owner}.
9305 * - If the user has no accounts, then return false.
9306 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
9307 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
9308 * ..._DISALLOWED, return true.
9309 * - Otherwise return false.
9311 private boolean hasIncompatibleAccountsLocked(int userId, @Nullable ComponentName owner) {
9312 final long token = mInjector.binderClearCallingIdentity();
9314 final AccountManager am = AccountManager.get(mContext);
9315 final Account accounts[] = am.getAccountsAsUser(userId);
9316 if (accounts.length == 0) {
9319 final String[] feature_allow =
9320 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
9321 final String[] feature_disallow =
9322 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
9324 // Even if we find incompatible accounts along the way, we still check all accounts
9326 boolean compatible = true;
9327 for (Account account : accounts) {
9328 if (hasAccountFeatures(am, account, feature_disallow)) {
9329 Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
9332 if (!hasAccountFeatures(am, account, feature_allow)) {
9333 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
9338 Log.w(LOG_TAG, "All accounts are compatible");
9340 Log.e(LOG_TAG, "Found incompatible accounts");
9343 // Then check if the owner is test-only.
9345 if (owner == null) {
9346 // Owner is unknown. Suppose it's not test-only
9348 log = "Only test-only device/profile owner can be installed with accounts";
9349 } else if (isAdminTestOnlyLocked(owner, userId)) {
9351 log = "Installing test-only owner " + owner;
9353 log = "Can't install test-only owner " + owner + " with incompatible accounts";
9357 log = "Can't install non test-only owner " + owner + " with accounts";
9360 Log.w(LOG_TAG, log);
9362 Log.e(LOG_TAG, log);
9366 mInjector.binderRestoreCallingIdentity(token);
9370 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
9372 return am.hasFeatures(account, features, null, null).getResult();
9373 } catch (Exception e) {
9374 Log.w(LOG_TAG, "Failed to get account feature", e);
9380 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
9381 Preconditions.checkNotNull(admin);
9385 ensureDeviceOwnerManagingSingleUser(admin);
9386 setBackupServiceEnabledInternal(enabled);
9389 private synchronized void setBackupServiceEnabledInternal(boolean enabled) {
9390 long ident = mInjector.binderClearCallingIdentity();
9392 IBackupManager ibm = mInjector.getIBackupManager();
9394 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
9396 } catch (RemoteException e) {
9397 throw new IllegalStateException(
9398 "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
9400 mInjector.binderRestoreCallingIdentity(ident);
9405 public boolean isBackupServiceEnabled(ComponentName admin) {
9406 Preconditions.checkNotNull(admin);
9410 synchronized (this) {
9411 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9413 IBackupManager ibm = mInjector.getIBackupManager();
9414 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
9415 } catch (RemoteException e) {
9416 throw new IllegalStateException("Failed requesting backup service state.", e);