2 * Copyright (C) 2010 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.server.devicepolicy;
19 import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
20 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
21 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
22 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
23 import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
25 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
26 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
27 import static org.xmlpull.v1.XmlPullParser.END_TAG;
28 import static org.xmlpull.v1.XmlPullParser.TEXT;
30 import android.Manifest.permission;
31 import android.accessibilityservice.AccessibilityServiceInfo;
32 import android.accounts.AccountManager;
33 import android.annotation.IntDef;
34 import android.annotation.NonNull;
35 import android.annotation.Nullable;
36 import android.annotation.UserIdInt;
37 import android.app.Activity;
38 import android.app.ActivityManager;
39 import android.app.ActivityManagerInternal;
40 import android.app.ActivityManagerNative;
41 import android.app.AlarmManager;
42 import android.app.AppGlobals;
43 import android.app.IActivityManager;
44 import android.app.Notification;
45 import android.app.NotificationManager;
46 import android.app.PendingIntent;
47 import android.app.StatusBarManager;
48 import android.app.admin.DeviceAdminInfo;
49 import android.app.admin.DeviceAdminReceiver;
50 import android.app.admin.DevicePolicyManager;
51 import android.app.admin.DevicePolicyManagerInternal;
52 import android.app.admin.IDevicePolicyManager;
53 import android.app.admin.SecurityLog;
54 import android.app.admin.SecurityLog.SecurityEvent;
55 import android.app.admin.SystemUpdatePolicy;
56 import android.app.backup.IBackupManager;
57 import android.app.trust.TrustManager;
58 import android.content.BroadcastReceiver;
59 import android.content.ComponentName;
60 import android.content.Context;
61 import android.content.Intent;
62 import android.content.IntentFilter;
63 import android.content.pm.ActivityInfo;
64 import android.content.pm.ApplicationInfo;
65 import android.content.pm.IPackageManager;
66 import android.content.pm.PackageInfo;
67 import android.content.pm.PackageManager;
68 import android.content.pm.PackageManager.NameNotFoundException;
69 import android.content.pm.PackageManagerInternal;
70 import android.content.pm.ParceledListSlice;
71 import android.content.pm.PermissionInfo;
72 import android.content.pm.ResolveInfo;
73 import android.content.pm.ServiceInfo;
74 import android.content.pm.UserInfo;
75 import android.database.ContentObserver;
76 import android.graphics.Bitmap;
77 import android.graphics.Color;
78 import android.media.AudioManager;
79 import android.media.IAudioService;
80 import android.net.ConnectivityManager;
81 import android.net.ProxyInfo;
82 import android.net.Uri;
83 import android.net.wifi.WifiInfo;
84 import android.net.wifi.WifiManager;
85 import android.os.AsyncTask;
86 import android.os.Binder;
87 import android.os.Build;
88 import android.os.Bundle;
89 import android.os.Environment;
90 import android.os.FileUtils;
91 import android.os.Handler;
92 import android.os.IBinder;
93 import android.os.Looper;
94 import android.os.ParcelFileDescriptor;
95 import android.os.PersistableBundle;
96 import android.os.PowerManager;
97 import android.os.PowerManagerInternal;
98 import android.os.Process;
99 import android.os.RecoverySystem;
100 import android.os.RemoteCallback;
101 import android.os.RemoteException;
102 import android.os.ServiceManager;
103 import android.os.SystemClock;
104 import android.os.SystemProperties;
105 import android.os.UserHandle;
106 import android.os.UserManager;
107 import android.os.UserManagerInternal;
108 import android.os.storage.StorageManager;
109 import android.provider.ContactsContract.QuickContact;
110 import android.provider.ContactsInternal;
111 import android.provider.Settings;
112 import android.security.Credentials;
113 import android.security.IKeyChainAliasCallback;
114 import android.security.IKeyChainService;
115 import android.security.KeyChain;
116 import android.security.KeyChain.KeyChainConnection;
117 import android.service.persistentdata.PersistentDataBlockManager;
118 import android.telephony.TelephonyManager;
119 import android.text.TextUtils;
120 import android.util.ArrayMap;
121 import android.util.ArraySet;
122 import android.util.EventLog;
123 import android.util.Log;
124 import android.util.Pair;
125 import android.util.Slog;
126 import android.util.SparseArray;
127 import android.util.Xml;
128 import android.view.IWindowManager;
129 import android.view.accessibility.AccessibilityManager;
130 import android.view.accessibility.IAccessibilityManager;
131 import android.view.inputmethod.InputMethodInfo;
132 import android.view.inputmethod.InputMethodManager;
134 import com.android.internal.R;
135 import com.android.internal.annotations.VisibleForTesting;
136 import com.android.internal.statusbar.IStatusBarService;
137 import com.android.internal.util.FastXmlSerializer;
138 import com.android.internal.util.JournaledFile;
139 import com.android.internal.util.ParcelableString;
140 import com.android.internal.util.Preconditions;
141 import com.android.internal.util.XmlUtils;
142 import com.android.internal.widget.LockPatternUtils;
143 import com.android.server.LocalServices;
144 import com.android.server.SystemService;
145 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
146 import com.android.server.pm.UserRestrictionsUtils;
147 import com.google.android.collect.Sets;
149 import org.xmlpull.v1.XmlPullParser;
150 import org.xmlpull.v1.XmlPullParserException;
151 import org.xmlpull.v1.XmlSerializer;
153 import java.io.ByteArrayInputStream;
155 import java.io.FileDescriptor;
156 import java.io.FileInputStream;
157 import java.io.FileNotFoundException;
158 import java.io.FileOutputStream;
159 import java.io.IOException;
160 import java.io.PrintWriter;
161 import java.lang.annotation.Retention;
162 import java.lang.annotation.RetentionPolicy;
163 import java.nio.charset.StandardCharsets;
164 import java.security.cert.CertificateException;
165 import java.security.cert.CertificateFactory;
166 import java.security.cert.X509Certificate;
167 import java.text.DateFormat;
168 import java.util.ArrayList;
169 import java.util.Arrays;
170 import java.util.Collections;
171 import java.util.Date;
172 import java.util.List;
173 import java.util.Map.Entry;
174 import java.util.Set;
175 import java.util.concurrent.atomic.AtomicBoolean;
178 * Implementation of the device policy APIs.
180 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
182 private static final String LOG_TAG = "DevicePolicyManagerService";
184 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
186 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
188 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
190 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
192 private static final String TAG_STATUS_BAR = "statusbar";
194 private static final String ATTR_DISABLED = "disabled";
196 private static final String ATTR_NAME = "name";
198 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
199 "do-not-ask-credentials-on-boot";
201 private static final String TAG_AFFILIATION_ID = "affiliation-id";
203 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
205 private static final String ATTR_VALUE = "value";
207 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
209 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
211 private static final long MS_PER_DAY = 86400 * 1000;
213 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
215 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
216 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
218 private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
219 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
221 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
222 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
223 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
224 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
226 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
227 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
228 = "application-restrictions-manager";
231 * System property whose value is either "true" or "false", indicating whether
233 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
235 private static final int STATUS_BAR_DISABLE_MASK =
236 StatusBarManager.DISABLE_EXPAND |
237 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
238 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
239 StatusBarManager.DISABLE_SEARCH;
241 private static final int STATUS_BAR_DISABLE2_MASK =
242 StatusBarManager.DISABLE2_QUICK_SETTINGS;
244 private static final Set<String> SECURE_SETTINGS_WHITELIST;
245 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
246 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
247 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
249 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
250 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
251 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
252 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
254 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
255 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
256 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
258 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
259 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
260 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
261 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
262 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
263 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
264 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
265 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
266 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
268 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
269 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
270 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
271 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
272 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
273 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
277 * Keyguard features that when set on a managed profile that doesn't have its own challenge will
278 * affect the profile's parent user. These can also be set on the managed profile's parent DPM
281 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
282 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
283 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
286 * Keyguard features that when set on a profile affect the profile content or challenge only.
287 * These cannot be set on the managed profile's parent DPM instance
289 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
290 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
292 /** Keyguard features that are allowed to be set on a managed profile */
293 private static final int PROFILE_KEYGUARD_FEATURES =
294 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
296 private static final int CODE_OK = 0;
297 private static final int CODE_HAS_DEVICE_OWNER = 1;
298 private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
299 private static final int CODE_USER_NOT_RUNNING = 3;
300 private static final int CODE_USER_SETUP_COMPLETED = 4;
301 private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
302 private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
303 private static final int CODE_NOT_SYSTEM_USER = 7;
305 @Retention(RetentionPolicy.SOURCE)
306 @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
307 CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
308 private @interface DeviceOwnerPreConditionCode {}
310 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
312 final Context mContext;
313 final Injector mInjector;
314 final IPackageManager mIPackageManager;
315 final UserManager mUserManager;
316 final UserManagerInternal mUserManagerInternal;
317 final TelephonyManager mTelephonyManager;
318 private final LockPatternUtils mLockPatternUtils;
321 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
322 * is requested for user u.
324 private final Set<Pair<String, Integer>> mPackagesToRemove =
325 new ArraySet<Pair<String, Integer>>();
327 final LocalService mLocalService;
329 // Stores and loads state on device and profile owners.
331 final Owners mOwners;
333 private final Binder mToken = new Binder();
336 * Whether or not device admin feature is supported. If it isn't return defaults for all
341 private final SecurityLogMonitor mSecurityLogMonitor;
343 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
344 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
346 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
349 if(mRemoteBugreportServiceIsActive.get()) {
355 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
358 public void onReceive(Context context, Intent intent) {
359 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
360 && mRemoteBugreportServiceIsActive.get()) {
361 onBugreportFinished(intent);
366 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
369 public void onReceive(Context context, Intent intent) {
370 String action = intent.getAction();
371 mInjector.getNotificationManager().cancel(LOG_TAG,
372 RemoteBugreportUtils.NOTIFICATION_ID);
373 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
374 onBugreportSharingAccepted();
375 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
376 onBugreportSharingDeclined();
378 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
382 public static final class Lifecycle extends SystemService {
383 private DevicePolicyManagerService mService;
385 public Lifecycle(Context context) {
387 mService = new DevicePolicyManagerService(context);
391 public void onStart() {
392 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
396 public void onBootPhase(int phase) {
397 mService.systemReady(phase);
401 public void onStartUser(int userHandle) {
402 mService.onStartUser(userHandle);
406 public static class DevicePolicyData {
407 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
408 int mActivePasswordLength = 0;
409 int mActivePasswordUpperCase = 0;
410 int mActivePasswordLowerCase = 0;
411 int mActivePasswordLetters = 0;
412 int mActivePasswordNumeric = 0;
413 int mActivePasswordSymbols = 0;
414 int mActivePasswordNonLetter = 0;
415 int mFailedPasswordAttempts = 0;
418 int mPasswordOwner = -1;
419 long mLastMaximumTimeToLock = -1;
420 boolean mUserSetupComplete = false;
421 int mUserProvisioningState;
422 int mPermissionPolicy;
424 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
425 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
426 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
428 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
430 // This is the list of component allowed to start lock task mode.
431 List<String> mLockTaskPackages = new ArrayList<>();
433 boolean mStatusBarDisabled = false;
435 ComponentName mRestrictionsProvider;
437 String mDelegatedCertInstallerPackage;
439 boolean doNotAskCredentialsOnBoot = false;
441 String mApplicationRestrictionsManagingPackage;
443 Set<String> mAffiliationIds = new ArraySet<>();
445 // Used for initialization of users created by createAndManageUsers.
446 boolean mAdminBroadcastPending = false;
447 PersistableBundle mInitBundle = null;
449 public DevicePolicyData(int userHandle) {
450 mUserHandle = userHandle;
454 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
456 final Handler mHandler;
458 BroadcastReceiver mReceiver = new BroadcastReceiver() {
460 public void onReceive(Context context, Intent intent) {
461 final String action = intent.getAction();
462 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
465 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
466 && userHandle == mOwners.getDeviceOwnerUserId()
467 && getDeviceOwnerRemoteBugreportUri() != null) {
468 IntentFilter filterConsent = new IntentFilter();
469 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
470 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
471 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
472 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
473 RemoteBugreportUtils.NOTIFICATION_ID,
474 RemoteBugreportUtils.buildNotification(mContext,
475 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
478 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
479 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
481 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
482 + action + " for user " + userHandle);
484 mHandler.post(new Runnable() {
487 handlePasswordExpirationNotification(userHandle);
491 if (Intent.ACTION_USER_UNLOCKED.equals(action)
492 || Intent.ACTION_USER_STARTED.equals(action)
493 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
494 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
495 new MonitoringCertNotificationTask().execute(userId);
497 if (Intent.ACTION_USER_ADDED.equals(action)) {
498 disableSecurityLoggingIfNotCompliant();
499 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
500 disableSecurityLoggingIfNotCompliant();
501 removeUserData(userHandle);
502 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
503 synchronized (DevicePolicyManagerService.this) {
504 // Reset the policy data
505 mUserData.remove(userHandle);
506 sendAdminEnabledBroadcastLocked(userHandle);
508 handlePackagesChanged(null /* check all admins */, userHandle);
509 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
510 handlePackagesChanged(null /* check all admins */, userHandle);
511 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
512 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
513 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
514 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
515 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
516 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
517 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
518 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
519 clearWipeProfileNotification();
524 static class ActiveAdmin {
525 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
526 private static final String TAG_DISABLE_CAMERA = "disable-camera";
527 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
528 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
529 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
530 = "disable-bt-contacts-sharing";
531 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
532 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
533 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
534 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
535 private static final String TAG_ACCOUNT_TYPE = "account-type";
536 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
537 = "permitted-accessiblity-services";
538 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
539 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
540 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
541 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
542 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
543 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
544 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
545 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
546 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
547 private static final String TAG_PERMITTED_IMES = "permitted-imes";
548 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
549 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
550 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
551 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
552 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
553 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
554 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
555 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
556 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
557 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
558 private static final String ATTR_VALUE = "value";
559 private static final String TAG_PASSWORD_QUALITY = "password-quality";
560 private static final String TAG_POLICIES = "policies";
561 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
562 "cross-profile-widget-providers";
563 private static final String TAG_PROVIDER = "provider";
564 private static final String TAG_PACKAGE_LIST_ITEM = "item";
565 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
566 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
567 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
568 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
569 private static final String TAG_PARENT_ADMIN = "parent-admin";
570 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
571 private static final String TAG_ORGANIZATION_NAME = "organization-name";
573 final DeviceAdminInfo info;
575 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
577 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
578 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
580 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
581 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
583 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
584 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
586 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
587 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
589 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
590 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
592 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
593 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
595 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
596 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
598 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
599 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
601 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
602 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
604 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
605 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
607 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
608 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
610 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
611 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
613 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
615 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
617 boolean encryptionRequested = false;
618 boolean disableCamera = false;
619 boolean disableCallerId = false;
620 boolean disableContactsSearch = false;
621 boolean disableBluetoothContactSharing = true;
622 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
623 boolean requireAutoTime = false; // Can only be set by a device owner.
624 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
626 ActiveAdmin parentAdmin;
627 final boolean isParent;
629 static class TrustAgentInfo {
630 public PersistableBundle options;
631 TrustAgentInfo(PersistableBundle bundle) {
636 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
638 // The list of permitted accessibility services package namesas set by a profile
639 // or device owner. Null means all accessibility services are allowed, empty means
640 // none except system services are allowed.
641 List<String> permittedAccessiblityServices;
643 // The list of permitted input methods package names as set by a profile or device owner.
644 // Null means all input methods are allowed, empty means none except system imes are
646 List<String> permittedInputMethods;
648 // List of package names to keep cached.
649 List<String> keepUninstalledPackages;
651 // TODO: review implementation decisions with frameworks team
652 boolean specifiesGlobalProxy = false;
653 String globalProxySpec = null;
654 String globalProxyExclusionList = null;
656 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
658 List<String> crossProfileWidgetProviders;
660 Bundle userRestrictions;
662 // Support text provided by the admin to display to the user.
663 CharSequence shortSupportMessage = null;
664 CharSequence longSupportMessage = null;
666 // Background color of confirm credentials screen. Default: teal.
667 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
668 int organizationColor = DEF_ORGANIZATION_COLOR;
670 // Default title of confirm credentials screen
671 String organizationName = null;
673 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
678 ActiveAdmin getParentActiveAdmin() {
679 Preconditions.checkState(!isParent);
681 if (parentAdmin == null) {
682 parentAdmin = new ActiveAdmin(info, /* parent */ true);
687 boolean hasParentActiveAdmin() {
688 return parentAdmin != null;
691 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
693 public UserHandle getUserHandle() {
694 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
697 void writeToXml(XmlSerializer out)
698 throws IllegalArgumentException, IllegalStateException, IOException {
699 out.startTag(null, TAG_POLICIES);
700 info.writePoliciesToXml(out);
701 out.endTag(null, TAG_POLICIES);
702 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
703 out.startTag(null, TAG_PASSWORD_QUALITY);
704 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
705 out.endTag(null, TAG_PASSWORD_QUALITY);
706 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
707 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
708 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
709 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
711 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
712 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
713 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
714 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
716 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
717 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
718 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
719 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
721 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
722 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
723 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
724 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
726 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
727 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
728 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
729 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
731 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
732 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
733 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
734 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
736 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
737 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
738 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
739 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
741 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
742 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
743 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
744 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
747 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
748 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
749 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
750 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
752 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
753 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
754 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
755 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
757 if (specifiesGlobalProxy) {
758 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
759 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
760 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
761 if (globalProxySpec != null) {
762 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
763 out.attribute(null, ATTR_VALUE, globalProxySpec);
764 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
766 if (globalProxyExclusionList != null) {
767 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
768 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
769 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
772 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
773 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
774 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
775 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
777 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
778 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
779 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
780 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
782 if (encryptionRequested) {
783 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
784 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
785 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
788 out.startTag(null, TAG_DISABLE_CAMERA);
789 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
790 out.endTag(null, TAG_DISABLE_CAMERA);
792 if (disableCallerId) {
793 out.startTag(null, TAG_DISABLE_CALLER_ID);
794 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
795 out.endTag(null, TAG_DISABLE_CALLER_ID);
797 if (disableContactsSearch) {
798 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
799 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
800 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
802 if (!disableBluetoothContactSharing) {
803 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
804 out.attribute(null, ATTR_VALUE,
805 Boolean.toString(disableBluetoothContactSharing));
806 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
808 if (disableScreenCapture) {
809 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
810 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
811 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
813 if (requireAutoTime) {
814 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
815 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
816 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
818 if (forceEphemeralUsers) {
819 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
820 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
821 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
823 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
824 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
825 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
826 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
828 if (!accountTypesWithManagementDisabled.isEmpty()) {
829 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
830 for (String ac : accountTypesWithManagementDisabled) {
831 out.startTag(null, TAG_ACCOUNT_TYPE);
832 out.attribute(null, ATTR_VALUE, ac);
833 out.endTag(null, TAG_ACCOUNT_TYPE);
835 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
837 if (!trustAgentInfos.isEmpty()) {
838 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
839 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
840 for (Entry<String, TrustAgentInfo> entry : set) {
841 TrustAgentInfo trustAgentInfo = entry.getValue();
842 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
843 out.attribute(null, ATTR_VALUE, entry.getKey());
844 if (trustAgentInfo.options != null) {
845 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
847 trustAgentInfo.options.saveToXml(out);
848 } catch (XmlPullParserException e) {
849 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
851 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
853 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
855 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
857 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
858 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
859 final int providerCount = crossProfileWidgetProviders.size();
860 for (int i = 0; i < providerCount; i++) {
861 String provider = crossProfileWidgetProviders.get(i);
862 out.startTag(null, TAG_PROVIDER);
863 out.attribute(null, ATTR_VALUE, provider);
864 out.endTag(null, TAG_PROVIDER);
866 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
868 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
869 permittedAccessiblityServices);
870 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
871 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
872 if (hasUserRestrictions()) {
873 UserRestrictionsUtils.writeRestrictions(
874 out, userRestrictions, TAG_USER_RESTRICTIONS);
876 if (!TextUtils.isEmpty(shortSupportMessage)) {
877 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
878 out.text(shortSupportMessage.toString());
879 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
881 if (!TextUtils.isEmpty(longSupportMessage)) {
882 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
883 out.text(longSupportMessage.toString());
884 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
886 if (parentAdmin != null) {
887 out.startTag(null, TAG_PARENT_ADMIN);
888 parentAdmin.writeToXml(out);
889 out.endTag(null, TAG_PARENT_ADMIN);
891 if (organizationColor != DEF_ORGANIZATION_COLOR) {
892 out.startTag(null, TAG_ORGANIZATION_COLOR);
893 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
894 out.endTag(null, TAG_ORGANIZATION_COLOR);
896 if (organizationName != null) {
897 out.startTag(null, TAG_ORGANIZATION_NAME);
898 out.text(organizationName);
899 out.endTag(null, TAG_ORGANIZATION_NAME);
903 void writePackageListToXml(XmlSerializer out, String outerTag,
904 List<String> packageList)
905 throws IllegalArgumentException, IllegalStateException, IOException {
906 if (packageList == null) {
910 out.startTag(null, outerTag);
911 for (String packageName : packageList) {
912 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
913 out.attribute(null, ATTR_VALUE, packageName);
914 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
916 out.endTag(null, outerTag);
919 void readFromXml(XmlPullParser parser)
920 throws XmlPullParserException, IOException {
921 int outerDepth = parser.getDepth();
923 while ((type=parser.next()) != END_DOCUMENT
924 && (type != END_TAG || parser.getDepth() > outerDepth)) {
925 if (type == END_TAG || type == TEXT) {
928 String tag = parser.getName();
929 if (TAG_POLICIES.equals(tag)) {
930 info.readPoliciesFromXml(parser);
931 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
932 passwordQuality = Integer.parseInt(
933 parser.getAttributeValue(null, ATTR_VALUE));
934 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
935 minimumPasswordLength = Integer.parseInt(
936 parser.getAttributeValue(null, ATTR_VALUE));
937 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
938 passwordHistoryLength = Integer.parseInt(
939 parser.getAttributeValue(null, ATTR_VALUE));
940 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
941 minimumPasswordUpperCase = Integer.parseInt(
942 parser.getAttributeValue(null, ATTR_VALUE));
943 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
944 minimumPasswordLowerCase = Integer.parseInt(
945 parser.getAttributeValue(null, ATTR_VALUE));
946 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
947 minimumPasswordLetters = Integer.parseInt(
948 parser.getAttributeValue(null, ATTR_VALUE));
949 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
950 minimumPasswordNumeric = Integer.parseInt(
951 parser.getAttributeValue(null, ATTR_VALUE));
952 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
953 minimumPasswordSymbols = Integer.parseInt(
954 parser.getAttributeValue(null, ATTR_VALUE));
955 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
956 minimumPasswordNonLetter = Integer.parseInt(
957 parser.getAttributeValue(null, ATTR_VALUE));
958 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
959 maximumTimeToUnlock = Long.parseLong(
960 parser.getAttributeValue(null, ATTR_VALUE));
961 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
962 maximumFailedPasswordsForWipe = Integer.parseInt(
963 parser.getAttributeValue(null, ATTR_VALUE));
964 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
965 specifiesGlobalProxy = Boolean.parseBoolean(
966 parser.getAttributeValue(null, ATTR_VALUE));
967 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
969 parser.getAttributeValue(null, ATTR_VALUE);
970 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
971 globalProxyExclusionList =
972 parser.getAttributeValue(null, ATTR_VALUE);
973 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
974 passwordExpirationTimeout = Long.parseLong(
975 parser.getAttributeValue(null, ATTR_VALUE));
976 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
977 passwordExpirationDate = Long.parseLong(
978 parser.getAttributeValue(null, ATTR_VALUE));
979 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
980 encryptionRequested = Boolean.parseBoolean(
981 parser.getAttributeValue(null, ATTR_VALUE));
982 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
983 disableCamera = Boolean.parseBoolean(
984 parser.getAttributeValue(null, ATTR_VALUE));
985 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
986 disableCallerId = Boolean.parseBoolean(
987 parser.getAttributeValue(null, ATTR_VALUE));
988 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
989 disableContactsSearch = Boolean.parseBoolean(
990 parser.getAttributeValue(null, ATTR_VALUE));
991 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
992 disableBluetoothContactSharing = Boolean.parseBoolean(parser
993 .getAttributeValue(null, ATTR_VALUE));
994 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
995 disableScreenCapture = Boolean.parseBoolean(
996 parser.getAttributeValue(null, ATTR_VALUE));
997 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
998 requireAutoTime = Boolean.parseBoolean(
999 parser.getAttributeValue(null, ATTR_VALUE));
1000 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1001 forceEphemeralUsers = Boolean.parseBoolean(
1002 parser.getAttributeValue(null, ATTR_VALUE));
1003 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1004 disabledKeyguardFeatures = Integer.parseInt(
1005 parser.getAttributeValue(null, ATTR_VALUE));
1006 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1007 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
1008 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1009 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1010 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1011 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
1012 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1013 permittedAccessiblityServices = readPackageList(parser, tag);
1014 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1015 permittedInputMethods = readPackageList(parser, tag);
1016 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1017 keepUninstalledPackages = readPackageList(parser, tag);
1018 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1019 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
1020 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1021 type = parser.next();
1022 if (type == XmlPullParser.TEXT) {
1023 shortSupportMessage = parser.getText();
1025 Log.w(LOG_TAG, "Missing text when loading short support message");
1027 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1028 type = parser.next();
1029 if (type == XmlPullParser.TEXT) {
1030 longSupportMessage = parser.getText();
1032 Log.w(LOG_TAG, "Missing text when loading long support message");
1034 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1035 Preconditions.checkState(!isParent);
1037 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1038 parentAdmin.readFromXml(parser);
1039 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1040 organizationColor = Integer.parseInt(
1041 parser.getAttributeValue(null, ATTR_VALUE));
1042 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1043 type = parser.next();
1044 if (type == XmlPullParser.TEXT) {
1045 organizationName = parser.getText();
1047 Log.w(LOG_TAG, "Missing text when loading organization name");
1050 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1051 XmlUtils.skipCurrentTag(parser);
1056 private List<String> readPackageList(XmlPullParser parser,
1057 String tag) throws XmlPullParserException, IOException {
1058 List<String> result = new ArrayList<String>();
1059 int outerDepth = parser.getDepth();
1061 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1062 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1063 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1066 String outerTag = parser.getName();
1067 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1068 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1069 if (packageName != null) {
1070 result.add(packageName);
1072 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1075 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1081 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1082 throws XmlPullParserException, IOException {
1083 int outerDepthDAM = parser.getDepth();
1085 Set<String> result = new ArraySet<>();
1086 while ((typeDAM=parser.next()) != END_DOCUMENT
1087 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1088 if (typeDAM == END_TAG || typeDAM == TEXT) {
1091 String tagDAM = parser.getName();
1092 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1093 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1095 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1101 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1102 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1103 int outerDepthDAM = parser.getDepth();
1105 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1106 while ((typeDAM=parser.next()) != END_DOCUMENT
1107 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1108 if (typeDAM == END_TAG || typeDAM == TEXT) {
1111 String tagDAM = parser.getName();
1112 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1113 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1114 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1115 result.put(component, trustAgentInfo);
1117 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1123 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1124 throws XmlPullParserException, IOException {
1125 int outerDepthDAM = parser.getDepth();
1127 TrustAgentInfo result = new TrustAgentInfo(null);
1128 while ((typeDAM=parser.next()) != END_DOCUMENT
1129 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1130 if (typeDAM == END_TAG || typeDAM == TEXT) {
1133 String tagDAM = parser.getName();
1134 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1135 result.options = PersistableBundle.restoreFromXml(parser);
1137 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1143 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1144 throws XmlPullParserException, IOException {
1145 int outerDepthDAM = parser.getDepth();
1147 ArrayList<String> result = null;
1148 while ((typeDAM=parser.next()) != END_DOCUMENT
1149 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1150 if (typeDAM == END_TAG || typeDAM == TEXT) {
1153 String tagDAM = parser.getName();
1154 if (TAG_PROVIDER.equals(tagDAM)) {
1155 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1156 if (result == null) {
1157 result = new ArrayList<>();
1159 result.add(provider);
1161 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1167 boolean hasUserRestrictions() {
1168 return userRestrictions != null && userRestrictions.size() > 0;
1171 Bundle ensureUserRestrictions() {
1172 if (userRestrictions == null) {
1173 userRestrictions = new Bundle();
1175 return userRestrictions;
1178 void dump(String prefix, PrintWriter pw) {
1179 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1180 pw.print(prefix); pw.println("policies:");
1181 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1183 for (int i=0; i<pols.size(); i++) {
1184 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1187 pw.print(prefix); pw.print("passwordQuality=0x");
1188 pw.println(Integer.toHexString(passwordQuality));
1189 pw.print(prefix); pw.print("minimumPasswordLength=");
1190 pw.println(minimumPasswordLength);
1191 pw.print(prefix); pw.print("passwordHistoryLength=");
1192 pw.println(passwordHistoryLength);
1193 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1194 pw.println(minimumPasswordUpperCase);
1195 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1196 pw.println(minimumPasswordLowerCase);
1197 pw.print(prefix); pw.print("minimumPasswordLetters=");
1198 pw.println(minimumPasswordLetters);
1199 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1200 pw.println(minimumPasswordNumeric);
1201 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1202 pw.println(minimumPasswordSymbols);
1203 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1204 pw.println(minimumPasswordNonLetter);
1205 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1206 pw.println(maximumTimeToUnlock);
1207 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1208 pw.println(maximumFailedPasswordsForWipe);
1209 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1210 pw.println(specifiesGlobalProxy);
1211 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1212 pw.println(passwordExpirationTimeout);
1213 pw.print(prefix); pw.print("passwordExpirationDate=");
1214 pw.println(passwordExpirationDate);
1215 if (globalProxySpec != null) {
1216 pw.print(prefix); pw.print("globalProxySpec=");
1217 pw.println(globalProxySpec);
1219 if (globalProxyExclusionList != null) {
1220 pw.print(prefix); pw.print("globalProxyEclusionList=");
1221 pw.println(globalProxyExclusionList);
1223 pw.print(prefix); pw.print("encryptionRequested=");
1224 pw.println(encryptionRequested);
1225 pw.print(prefix); pw.print("disableCamera=");
1226 pw.println(disableCamera);
1227 pw.print(prefix); pw.print("disableCallerId=");
1228 pw.println(disableCallerId);
1229 pw.print(prefix); pw.print("disableContactsSearch=");
1230 pw.println(disableContactsSearch);
1231 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1232 pw.println(disableBluetoothContactSharing);
1233 pw.print(prefix); pw.print("disableScreenCapture=");
1234 pw.println(disableScreenCapture);
1235 pw.print(prefix); pw.print("requireAutoTime=");
1236 pw.println(requireAutoTime);
1237 pw.print(prefix); pw.print("forceEphemeralUsers=");
1238 pw.println(forceEphemeralUsers);
1239 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1240 pw.println(disabledKeyguardFeatures);
1241 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1242 pw.println(crossProfileWidgetProviders);
1243 if (permittedAccessiblityServices != null) {
1244 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1245 pw.println(permittedAccessiblityServices);
1247 if (permittedInputMethods != null) {
1248 pw.print(prefix); pw.print("permittedInputMethods=");
1249 pw.println(permittedInputMethods);
1251 if (keepUninstalledPackages != null) {
1252 pw.print(prefix); pw.print("keepUninstalledPackages=");
1253 pw.println(keepUninstalledPackages);
1255 pw.print(prefix); pw.print("organizationColor=");
1256 pw.println(organizationColor);
1257 if (organizationName != null) {
1258 pw.print(prefix); pw.print("organizationName=");
1259 pw.println(organizationName);
1261 pw.print(prefix); pw.println("userRestrictions:");
1262 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1263 pw.print(prefix); pw.print("isParent=");
1264 pw.println(isParent);
1265 if (parentAdmin != null) {
1266 pw.print(prefix); pw.println("parentAdmin:");
1267 parentAdmin.dump(prefix + " ", pw);
1272 private void handlePackagesChanged(String packageName, int userHandle) {
1273 boolean removed = false;
1274 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1275 DevicePolicyData policy = getUserData(userHandle);
1276 synchronized (this) {
1277 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1278 ActiveAdmin aa = policy.mAdminList.get(i);
1280 // If we're checking all packages or if the specific one we're checking matches,
1281 // then check if the package and receiver still exist.
1282 final String adminPackage = aa.info.getPackageName();
1283 if (packageName == null || packageName.equals(adminPackage)) {
1284 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1285 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1286 PackageManager.MATCH_DIRECT_BOOT_AWARE
1287 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1288 userHandle) == null) {
1290 policy.mAdminList.remove(i);
1291 policy.mAdminMap.remove(aa.info.getComponent());
1294 } catch (RemoteException re) {
1299 validatePasswordOwnerLocked(policy);
1300 saveSettingsLocked(policy.mUserHandle);
1303 // Check if delegated cert installer or app restrictions managing packages are removed.
1304 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1305 policy.mDelegatedCertInstallerPackage = null;
1306 saveSettingsLocked(policy.mUserHandle);
1308 if (isRemovedPackage(
1309 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1310 policy.mApplicationRestrictionsManagingPackage = null;
1311 saveSettingsLocked(policy.mUserHandle);
1315 // The removed admin might have disabled camera, so update user restrictions.
1316 pushUserRestrictions(userHandle);
1320 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1322 return targetPackage != null
1323 && (changedPackage == null || changedPackage.equals(targetPackage))
1324 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1325 } catch (RemoteException e) {
1333 * Unit test will subclass it to inject mocks.
1336 static class Injector {
1338 private final Context mContext;
1340 Injector(Context context) {
1344 Owners newOwners() {
1345 return new Owners(getUserManager(), getUserManagerInternal(),
1346 getPackageManagerInternal());
1349 UserManager getUserManager() {
1350 return UserManager.get(mContext);
1353 UserManagerInternal getUserManagerInternal() {
1354 return LocalServices.getService(UserManagerInternal.class);
1357 PackageManagerInternal getPackageManagerInternal() {
1358 return LocalServices.getService(PackageManagerInternal.class);
1361 NotificationManager getNotificationManager() {
1362 return mContext.getSystemService(NotificationManager.class);
1365 PowerManagerInternal getPowerManagerInternal() {
1366 return LocalServices.getService(PowerManagerInternal.class);
1369 TelephonyManager getTelephonyManager() {
1370 return TelephonyManager.from(mContext);
1373 TrustManager getTrustManager() {
1374 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1377 IWindowManager getIWindowManager() {
1378 return IWindowManager.Stub
1379 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1382 IActivityManager getIActivityManager() {
1383 return ActivityManagerNative.getDefault();
1386 IPackageManager getIPackageManager() {
1387 return AppGlobals.getPackageManager();
1390 IBackupManager getIBackupManager() {
1391 return IBackupManager.Stub.asInterface(
1392 ServiceManager.getService(Context.BACKUP_SERVICE));
1395 IAudioService getIAudioService() {
1396 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1399 LockPatternUtils newLockPatternUtils() {
1400 return new LockPatternUtils(mContext);
1403 boolean storageManagerIsFileBasedEncryptionEnabled() {
1404 return StorageManager.isFileEncryptedNativeOnly();
1407 boolean storageManagerIsNonDefaultBlockEncrypted() {
1408 long identity = Binder.clearCallingIdentity();
1410 return StorageManager.isNonDefaultBlockEncrypted();
1412 Binder.restoreCallingIdentity(identity);
1416 boolean storageManagerIsEncrypted() {
1417 return StorageManager.isEncrypted();
1420 boolean storageManagerIsEncryptable() {
1421 return StorageManager.isEncryptable();
1424 Looper getMyLooper() {
1425 return Looper.myLooper();
1428 WifiManager getWifiManager() {
1429 return mContext.getSystemService(WifiManager.class);
1432 long binderClearCallingIdentity() {
1433 return Binder.clearCallingIdentity();
1436 void binderRestoreCallingIdentity(long token) {
1437 Binder.restoreCallingIdentity(token);
1440 int binderGetCallingUid() {
1441 return Binder.getCallingUid();
1444 int binderGetCallingPid() {
1445 return Binder.getCallingPid();
1448 UserHandle binderGetCallingUserHandle() {
1449 return Binder.getCallingUserHandle();
1452 boolean binderIsCallingUidMyUid() {
1453 return getCallingUid() == Process.myUid();
1456 final int userHandleGetCallingUserId() {
1457 return UserHandle.getUserId(binderGetCallingUid());
1460 File environmentGetUserSystemDirectory(int userId) {
1461 return Environment.getUserSystemDirectory(userId);
1464 void powerManagerGoToSleep(long time, int reason, int flags) {
1465 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1468 void powerManagerReboot(String reason) {
1469 mContext.getSystemService(PowerManager.class).reboot(reason);
1472 boolean systemPropertiesGetBoolean(String key, boolean def) {
1473 return SystemProperties.getBoolean(key, def);
1476 long systemPropertiesGetLong(String key, long def) {
1477 return SystemProperties.getLong(key, def);
1480 String systemPropertiesGet(String key, String def) {
1481 return SystemProperties.get(key, def);
1484 String systemPropertiesGet(String key) {
1485 return SystemProperties.get(key);
1488 void systemPropertiesSet(String key, String value) {
1489 SystemProperties.set(key, value);
1492 boolean userManagerIsSplitSystemUser() {
1493 return UserManager.isSplitSystemUser();
1496 String getDevicePolicyFilePathForSystemUser() {
1497 return "/data/system/";
1500 void registerContentObserver(Uri uri, boolean notifyForDescendents,
1501 ContentObserver observer, int userHandle) {
1502 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1503 observer, userHandle);
1506 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1507 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1508 name, def, userHandle);
1511 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1512 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1513 name, value, userHandle);
1516 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1517 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1518 name, value, userHandle);
1521 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1522 Settings.Global.putStringForUser(mContext.getContentResolver(),
1523 name, value, userHandle);
1526 void settingsSecurePutInt(String name, int value) {
1527 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1530 int settingsGlobalGetInt(String name, int def) {
1531 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1534 void settingsGlobalPutInt(String name, int value) {
1535 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1538 void settingsSecurePutString(String name, String value) {
1539 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1542 void settingsGlobalPutString(String name, String value) {
1543 Settings.Global.putString(mContext.getContentResolver(), name, value);
1546 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1547 SecurityLog.setLoggingEnabledProperty(enabled);
1550 boolean securityLogGetLoggingEnabledProperty() {
1551 return SecurityLog.getLoggingEnabledProperty();
1554 boolean securityLogIsLoggingEnabled() {
1555 return SecurityLog.isLoggingEnabled();
1560 * Instantiates the service.
1562 public DevicePolicyManagerService(Context context) {
1563 this(new Injector(context));
1567 DevicePolicyManagerService(Injector injector) {
1568 mInjector = injector;
1569 mContext = Preconditions.checkNotNull(injector.mContext);
1570 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1571 mOwners = Preconditions.checkNotNull(injector.newOwners());
1573 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1574 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1575 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1576 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1578 mLocalService = new LocalService();
1579 mLockPatternUtils = injector.newLockPatternUtils();
1581 mSecurityLogMonitor = new SecurityLogMonitor(this);
1583 mHasFeature = mContext.getPackageManager()
1584 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1586 // Skip the rest of the initialization
1589 IntentFilter filter = new IntentFilter();
1590 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1591 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1592 filter.addAction(Intent.ACTION_USER_ADDED);
1593 filter.addAction(Intent.ACTION_USER_REMOVED);
1594 filter.addAction(Intent.ACTION_USER_STARTED);
1595 filter.addAction(Intent.ACTION_USER_UNLOCKED);
1596 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1597 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1598 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1599 filter = new IntentFilter();
1600 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1601 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1602 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1603 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1604 filter.addDataScheme("package");
1605 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1606 filter = new IntentFilter();
1607 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1608 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1610 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1614 * Creates and loads the policy data from xml.
1615 * @param userHandle the user for whom to load the policy data
1619 DevicePolicyData getUserData(int userHandle) {
1620 synchronized (this) {
1621 DevicePolicyData policy = mUserData.get(userHandle);
1622 if (policy == null) {
1623 policy = new DevicePolicyData(userHandle);
1624 mUserData.append(userHandle, policy);
1625 loadSettingsLocked(policy, userHandle);
1632 * Creates and loads the policy data from xml for data that is shared between
1633 * various profiles of a user. In contrast to {@link #getUserData(int)}
1634 * it allows access to data of users other than the calling user.
1636 * This function should only be used for shared data, e.g. everything regarding
1637 * passwords and should be removed once multiple screen locks are present.
1638 * @param userHandle the user for whom to load the policy data
1641 DevicePolicyData getUserDataUnchecked(int userHandle) {
1642 long ident = mInjector.binderClearCallingIdentity();
1644 return getUserData(userHandle);
1646 mInjector.binderRestoreCallingIdentity(ident);
1650 void removeUserData(int userHandle) {
1651 synchronized (this) {
1652 if (userHandle == UserHandle.USER_SYSTEM) {
1653 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1656 mOwners.removeProfileOwner(userHandle);
1657 mOwners.writeProfileOwner(userHandle);
1659 DevicePolicyData policy = mUserData.get(userHandle);
1660 if (policy != null) {
1661 mUserData.remove(userHandle);
1663 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1664 DEVICE_POLICIES_XML);
1665 policyFile.delete();
1666 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1668 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1672 synchronized (this) {
1674 setDeviceOwnerSystemPropertyLocked();
1675 findOwnerComponentIfNecessaryLocked();
1676 migrateUserRestrictionsIfNecessaryLocked();
1678 // TODO PO may not have a class name either due to b/17652534. Address that too.
1680 updateDeviceOwnerLocked();
1684 private void setDeviceOwnerSystemPropertyLocked() {
1685 // Device owner may still be provisioned, do not set the read-only system property yet.
1686 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1689 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1690 // always false at this point.
1691 if (StorageManager.inCryptKeeperBounce()) {
1695 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1696 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1698 if (mOwners.hasDeviceOwner()) {
1699 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1700 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1701 disableSecurityLoggingIfNotCompliant();
1702 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1703 mSecurityLogMonitor.start();
1706 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1707 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1712 private void findOwnerComponentIfNecessaryLocked() {
1713 if (!mOwners.hasDeviceOwner()) {
1716 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1718 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1719 return; // Already a full component name.
1722 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1723 doComponentName.getPackageName(),
1724 mOwners.getDeviceOwnerUserId());
1725 if (doComponent == null) {
1726 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1728 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1730 mOwners.getDeviceOwnerName(),
1731 mOwners.getDeviceOwnerUserId(),
1732 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1733 mOwners.writeDeviceOwner();
1735 Log.v(LOG_TAG, "Device owner component filled in");
1741 * We didn't use to persist user restrictions for each owners but only persisted in user
1744 private void migrateUserRestrictionsIfNecessaryLocked() {
1745 boolean migrated = false;
1746 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1747 // except for the "system controlled" ones.
1748 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1750 Log.v(LOG_TAG, "Migrating DO user restrictions");
1754 // Migrate user 0 restrictions to DO.
1755 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1757 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1758 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1760 // Push DO user restrictions to user manager.
1761 pushUserRestrictions(UserHandle.USER_SYSTEM);
1763 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1768 // The following restrictions can be set on secondary users by the device owner, so we
1769 // assume they're not from the PO.
1770 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1771 UserManager.DISALLOW_OUTGOING_CALLS,
1772 UserManager.DISALLOW_SMS);
1774 for (UserInfo ui : mUserManager.getUsers()) {
1775 final int userId = ui.id;
1776 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1778 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1782 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1784 final Set<String> exceptionList =
1785 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1787 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1788 exceptionList, /* isDeviceOwner =*/ false);
1790 // Note if a secondary user has no PO but has a DA that disables camera, we
1791 // don't get here and won't push the camera user restriction to UserManager
1792 // here. That's okay because we'll push user restrictions anyway when a user
1793 // starts. But we still do it because we want to let user manager persist
1795 pushUserRestrictions(userId);
1797 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1800 if (VERBOSE_LOG && migrated) {
1801 Log.v(LOG_TAG, "User restrictions migrated.");
1805 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1806 Set<String> exceptionList, boolean isDeviceOwner) {
1807 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1808 user.getIdentifier());
1810 final Bundle newBaseRestrictions = new Bundle();
1811 final Bundle newOwnerRestrictions = new Bundle();
1813 for (String key : origRestrictions.keySet()) {
1814 if (!origRestrictions.getBoolean(key)) {
1817 final boolean canOwnerChange = isDeviceOwner
1818 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1819 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1821 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1822 newBaseRestrictions.putBoolean(key, true);
1824 newOwnerRestrictions.putBoolean(key, true);
1829 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1830 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1831 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1833 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1834 newBaseRestrictions);
1836 if (admin != null) {
1837 admin.ensureUserRestrictions().clear();
1838 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1840 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1842 saveSettingsLocked(user.getIdentifier());
1845 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1846 final DevicePolicyData policy = getUserData(userId);
1847 final int n = policy.mAdminList.size();
1848 ComponentName found = null;
1850 for (int i = 0; i < n; i++) {
1851 final ActiveAdmin admin = policy.mAdminList.get(i);
1852 if (packageName.equals(admin.info.getPackageName())) {
1855 found = admin.info.getComponent();
1861 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1867 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1868 * reminders. Clears alarm if no expirations are configured.
1870 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1871 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1872 final long now = System.currentTimeMillis();
1873 final long timeToExpire = expiration - now;
1874 final long alarmTime;
1875 if (expiration == 0) {
1876 // No expirations are currently configured: Cancel alarm.
1878 } else if (timeToExpire <= 0) {
1879 // The password has already expired: Repeat every 24 hours.
1880 alarmTime = now + MS_PER_DAY;
1882 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1883 // the expiration time.
1884 long alarmInterval = timeToExpire % MS_PER_DAY;
1885 if (alarmInterval == 0) {
1886 alarmInterval = MS_PER_DAY;
1888 alarmTime = now + alarmInterval;
1891 long token = mInjector.binderClearCallingIdentity();
1893 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1894 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1895 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1896 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1897 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1898 UserHandle.of(affectedUserHandle));
1900 if (alarmTime != 0) {
1901 am.set(AlarmManager.RTC, alarmTime, pi);
1904 mInjector.binderRestoreCallingIdentity(token);
1908 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1909 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1911 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1912 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1918 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
1920 enforceManagedProfile(userHandle, "call APIs on the parent profile");
1922 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1923 if (admin != null && parent) {
1924 admin = admin.getParentActiveAdmin();
1929 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1930 throws SecurityException {
1931 final int callingUid = mInjector.binderGetCallingUid();
1933 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1934 if (result != null) {
1939 final int userId = UserHandle.getUserId(callingUid);
1940 final DevicePolicyData policy = getUserData(userId);
1941 ActiveAdmin admin = policy.mAdminMap.get(who);
1942 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1943 throw new SecurityException("Admin " + admin.info.getComponent()
1944 + " does not own the device");
1946 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1947 throw new SecurityException("Admin " + admin.info.getComponent()
1948 + " does not own the profile");
1950 throw new SecurityException("Admin " + admin.info.getComponent()
1951 + " did not specify uses-policy for: "
1952 + admin.info.getTagForPolicy(reqPolicy));
1954 throw new SecurityException("No active admin owned by uid "
1955 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
1959 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
1960 throws SecurityException {
1962 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
1963 "call APIs on the parent profile");
1965 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
1966 return parent ? admin.getParentActiveAdmin() : admin;
1969 * Find the admin for the component and userId bit of the uid, then check
1970 * the admin's uid matches the uid.
1972 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
1973 final int userId = UserHandle.getUserId(uid);
1974 final DevicePolicyData policy = getUserData(userId);
1975 ActiveAdmin admin = policy.mAdminMap.get(who);
1976 if (admin == null) {
1977 throw new SecurityException("No active admin " + who);
1979 if (admin.getUid() != uid) {
1980 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1985 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
1987 // Try to find an admin which can use reqPolicy
1988 final int userId = UserHandle.getUserId(uid);
1989 final DevicePolicyData policy = getUserData(userId);
1991 ActiveAdmin admin = policy.mAdminMap.get(who);
1992 if (admin == null) {
1993 throw new SecurityException("No active admin " + who);
1995 if (admin.getUid() != uid) {
1996 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1998 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2002 for (ActiveAdmin admin : policy.mAdminList) {
2003 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2014 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2016 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2017 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2019 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2021 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2022 // DO always has the PO power.
2023 return ownsDevice || ownsProfile;
2025 return admin.info.usesPolicy(reqPolicy);
2029 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2030 sendAdminCommandLocked(admin, action, null);
2033 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2034 sendAdminCommandLocked(admin, action, null, result);
2038 * Send an update to one specific admin, get notified when that admin returns a result.
2040 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2041 BroadcastReceiver result) {
2042 Intent intent = new Intent(action);
2043 intent.setComponent(admin.info.getComponent());
2044 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2045 intent.putExtra("expiration", admin.passwordExpirationDate);
2047 if (adminExtras != null) {
2048 intent.putExtras(adminExtras);
2050 if (result != null) {
2051 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2052 null, result, mHandler, Activity.RESULT_OK, null, null);
2054 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2059 * Send an update to all admins of a user that enforce a specified policy.
2061 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2062 final DevicePolicyData policy = getUserData(userHandle);
2063 final int count = policy.mAdminList.size();
2065 for (int i = 0; i < count; i++) {
2066 final ActiveAdmin admin = policy.mAdminList.get(i);
2067 if (admin.info.usesPolicy(reqPolicy)) {
2068 sendAdminCommandLocked(admin, action);
2075 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2076 * enforce a specified policy.
2078 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2080 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2081 for (int profileId : profileIds) {
2082 sendAdminCommandLocked(action, reqPolicy, profileId);
2087 * Sends a broadcast to each profile that share the password unlock with the given user id.
2089 private void sendAdminCommandForLockscreenPoliciesLocked(
2090 String action, int reqPolicy, int userHandle) {
2091 if (isSeparateProfileChallengeEnabled(userHandle)) {
2092 sendAdminCommandLocked(action, reqPolicy, userHandle);
2094 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2098 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2099 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2100 if (admin != null) {
2101 getUserData(userHandle).mRemovingAdmins.add(adminReceiver);
2102 sendAdminCommandLocked(admin,
2103 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2104 new BroadcastReceiver() {
2106 public void onReceive(Context context, Intent intent) {
2107 removeAdminArtifacts(adminReceiver, userHandle);
2108 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2115 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2116 boolean throwForMissiongPermission) {
2120 enforceFullCrossUsersPermission(userHandle);
2121 ActivityInfo ai = null;
2123 ai = mIPackageManager.getReceiverInfo(adminName,
2124 PackageManager.GET_META_DATA |
2125 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2126 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2127 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2128 } catch (RemoteException e) {
2129 // shouldn't happen.
2132 throw new IllegalArgumentException("Unknown admin: " + adminName);
2135 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2136 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2137 + permission.BIND_DEVICE_ADMIN;
2138 Slog.w(LOG_TAG, message);
2139 if (throwForMissiongPermission &&
2140 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2141 throw new IllegalArgumentException(message);
2146 return new DeviceAdminInfo(mContext, ai);
2147 } catch (XmlPullParserException | IOException e) {
2148 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2154 private JournaledFile makeJournaledFile(int userHandle) {
2155 final String base = userHandle == UserHandle.USER_SYSTEM
2156 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2157 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2158 DEVICE_POLICIES_XML).getAbsolutePath();
2160 Log.v(LOG_TAG, "Opening " + base);
2162 return new JournaledFile(new File(base), new File(base + ".tmp"));
2165 private void saveSettingsLocked(int userHandle) {
2166 DevicePolicyData policy = getUserData(userHandle);
2167 JournaledFile journal = makeJournaledFile(userHandle);
2168 FileOutputStream stream = null;
2170 stream = new FileOutputStream(journal.chooseForWrite(), false);
2171 XmlSerializer out = new FastXmlSerializer();
2172 out.setOutput(stream, StandardCharsets.UTF_8.name());
2173 out.startDocument(null, true);
2175 out.startTag(null, "policies");
2176 if (policy.mRestrictionsProvider != null) {
2177 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2178 policy.mRestrictionsProvider.flattenToString());
2180 if (policy.mUserSetupComplete) {
2181 out.attribute(null, ATTR_SETUP_COMPLETE,
2182 Boolean.toString(true));
2184 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2185 out.attribute(null, ATTR_PROVISIONING_STATE,
2186 Integer.toString(policy.mUserProvisioningState));
2188 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2189 out.attribute(null, ATTR_PERMISSION_POLICY,
2190 Integer.toString(policy.mPermissionPolicy));
2192 if (policy.mDelegatedCertInstallerPackage != null) {
2193 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2194 policy.mDelegatedCertInstallerPackage);
2196 if (policy.mApplicationRestrictionsManagingPackage != null) {
2197 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2198 policy.mApplicationRestrictionsManagingPackage);
2201 final int N = policy.mAdminList.size();
2202 for (int i=0; i<N; i++) {
2203 ActiveAdmin ap = policy.mAdminList.get(i);
2205 out.startTag(null, "admin");
2206 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2208 out.endTag(null, "admin");
2212 if (policy.mPasswordOwner >= 0) {
2213 out.startTag(null, "password-owner");
2214 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2215 out.endTag(null, "password-owner");
2218 if (policy.mFailedPasswordAttempts != 0) {
2219 out.startTag(null, "failed-password-attempts");
2220 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2221 out.endTag(null, "failed-password-attempts");
2224 // Don't save metrics for FBE devices
2225 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
2226 && (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2227 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2228 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2229 || policy.mActivePasswordSymbols != 0
2230 || policy.mActivePasswordNonLetter != 0)) {
2231 out.startTag(null, "active-password");
2232 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2233 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2234 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2235 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2236 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2237 out.attribute(null, "numeric", Integer
2238 .toString(policy.mActivePasswordNumeric));
2239 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2240 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2241 out.endTag(null, "active-password");
2244 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2245 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2246 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2247 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2250 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2251 String component = policy.mLockTaskPackages.get(i);
2252 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2253 out.attribute(null, "name", component);
2254 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2257 if (policy.mStatusBarDisabled) {
2258 out.startTag(null, TAG_STATUS_BAR);
2259 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2260 out.endTag(null, TAG_STATUS_BAR);
2263 if (policy.doNotAskCredentialsOnBoot) {
2264 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2265 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2268 for (String id : policy.mAffiliationIds) {
2269 out.startTag(null, TAG_AFFILIATION_ID);
2270 out.attribute(null, "id", id);
2271 out.endTag(null, TAG_AFFILIATION_ID);
2274 if (policy.mAdminBroadcastPending) {
2275 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2276 out.attribute(null, ATTR_VALUE,
2277 Boolean.toString(policy.mAdminBroadcastPending));
2278 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2281 if (policy.mInitBundle != null) {
2282 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2283 policy.mInitBundle.saveToXml(out);
2284 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2287 out.endTag(null, "policies");
2291 FileUtils.sync(stream);
2294 sendChangedNotification(userHandle);
2295 } catch (XmlPullParserException | IOException e) {
2296 Slog.w(LOG_TAG, "failed writing file", e);
2298 if (stream != null) {
2301 } catch (IOException ex) {
2308 private void sendChangedNotification(int userHandle) {
2309 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2310 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2311 long ident = mInjector.binderClearCallingIdentity();
2313 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2315 mInjector.binderRestoreCallingIdentity(ident);
2319 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2320 JournaledFile journal = makeJournaledFile(userHandle);
2321 FileInputStream stream = null;
2322 File file = journal.chooseForRead();
2323 boolean needsRewrite = false;
2325 stream = new FileInputStream(file);
2326 XmlPullParser parser = Xml.newPullParser();
2327 parser.setInput(stream, StandardCharsets.UTF_8.name());
2330 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2331 && type != XmlPullParser.START_TAG) {
2333 String tag = parser.getName();
2334 if (!"policies".equals(tag)) {
2335 throw new XmlPullParserException(
2336 "Settings do not start with policies tag: found " + tag);
2339 // Extract the permission provider component name if available
2340 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2341 if (permissionProvider != null) {
2342 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2344 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2345 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2346 policy.mUserSetupComplete = true;
2348 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2349 if (!TextUtils.isEmpty(provisioningState)) {
2350 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2352 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2353 if (!TextUtils.isEmpty(permissionPolicy)) {
2354 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2356 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2357 ATTR_DELEGATED_CERT_INSTALLER);
2358 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2359 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2361 type = parser.next();
2362 int outerDepth = parser.getDepth();
2363 policy.mLockTaskPackages.clear();
2364 policy.mAdminList.clear();
2365 policy.mAdminMap.clear();
2366 policy.mAffiliationIds.clear();
2367 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2368 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2369 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2372 tag = parser.getName();
2373 if ("admin".equals(tag)) {
2374 String name = parser.getAttributeValue(null, "name");
2376 DeviceAdminInfo dai = findAdmin(
2377 ComponentName.unflattenFromString(name), userHandle,
2378 /* throwForMissionPermission= */ false);
2380 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2382 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2383 + dai.getActivityInfo().applicationInfo.uid + " for user "
2387 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2388 ap.readFromXml(parser);
2389 policy.mAdminMap.put(ap.info.getComponent(), ap);
2391 } catch (RuntimeException e) {
2392 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2394 } else if ("failed-password-attempts".equals(tag)) {
2395 policy.mFailedPasswordAttempts = Integer.parseInt(
2396 parser.getAttributeValue(null, "value"));
2397 } else if ("password-owner".equals(tag)) {
2398 policy.mPasswordOwner = Integer.parseInt(
2399 parser.getAttributeValue(null, "value"));
2400 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2401 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2402 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2403 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2404 } else if (TAG_STATUS_BAR.equals(tag)) {
2405 policy.mStatusBarDisabled = Boolean.parseBoolean(
2406 parser.getAttributeValue(null, ATTR_DISABLED));
2407 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2408 policy.doNotAskCredentialsOnBoot = true;
2409 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2410 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2411 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2412 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2413 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2414 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2415 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2416 } else if ("active-password".equals(tag)) {
2417 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2418 // Remove this from FBE devices
2419 needsRewrite = true;
2421 policy.mActivePasswordQuality = Integer.parseInt(
2422 parser.getAttributeValue(null, "quality"));
2423 policy.mActivePasswordLength = Integer.parseInt(
2424 parser.getAttributeValue(null, "length"));
2425 policy.mActivePasswordUpperCase = Integer.parseInt(
2426 parser.getAttributeValue(null, "uppercase"));
2427 policy.mActivePasswordLowerCase = Integer.parseInt(
2428 parser.getAttributeValue(null, "lowercase"));
2429 policy.mActivePasswordLetters = Integer.parseInt(
2430 parser.getAttributeValue(null, "letters"));
2431 policy.mActivePasswordNumeric = Integer.parseInt(
2432 parser.getAttributeValue(null, "numeric"));
2433 policy.mActivePasswordSymbols = Integer.parseInt(
2434 parser.getAttributeValue(null, "symbols"));
2435 policy.mActivePasswordNonLetter = Integer.parseInt(
2436 parser.getAttributeValue(null, "nonletter"));
2439 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2440 XmlUtils.skipCurrentTag(parser);
2443 } catch (FileNotFoundException e) {
2444 // Don't be noisy, this is normal if we haven't defined any policies.
2445 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2446 | IndexOutOfBoundsException e) {
2447 Slog.w(LOG_TAG, "failed parsing " + file, e);
2450 if (stream != null) {
2453 } catch (IOException e) {
2457 // Generate a list of admins from the admin map
2458 policy.mAdminList.addAll(policy.mAdminMap.values());
2460 // Might need to upgrade the file by rewriting it
2462 saveSettingsLocked(userHandle);
2465 validatePasswordOwnerLocked(policy);
2466 updateMaximumTimeToLockLocked(userHandle);
2467 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2468 if (policy.mStatusBarDisabled) {
2469 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2473 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2474 long ident = mInjector.binderClearCallingIdentity();
2476 mInjector.getIActivityManager()
2477 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2478 } catch (RemoteException e) {
2479 // Not gonna happen.
2481 mInjector.binderRestoreCallingIdentity(ident);
2485 private void updateDeviceOwnerLocked() {
2486 long ident = mInjector.binderClearCallingIdentity();
2488 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2489 // user id and also protect all other DAs too.
2490 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2491 if (deviceOwnerComponent != null) {
2492 mInjector.getIActivityManager()
2493 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2495 } catch (RemoteException e) {
2496 // Not gonna happen.
2498 mInjector.binderRestoreCallingIdentity(ident);
2502 static void validateQualityConstant(int quality) {
2504 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2505 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2506 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2507 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2508 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2509 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2510 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2511 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2512 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2515 throw new IllegalArgumentException("Invalid quality constant: 0x"
2516 + Integer.toHexString(quality));
2519 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2520 if (policy.mPasswordOwner >= 0) {
2521 boolean haveOwner = false;
2522 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2523 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2529 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2530 + " no longer active; disabling");
2531 policy.mPasswordOwner = -1;
2537 void systemReady(int phase) {
2542 case SystemService.PHASE_LOCK_SETTINGS_READY:
2543 onLockSettingsReady();
2545 case SystemService.PHASE_BOOT_COMPLETED:
2546 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2551 private void onLockSettingsReady() {
2552 getUserData(UserHandle.USER_SYSTEM);
2556 onStartUser(UserHandle.USER_SYSTEM);
2558 // Register an observer for watching for user setup complete.
2559 new SetupContentObserver(mHandler).register();
2560 // Initialize the user setup state, to handle the upgrade case.
2561 updateUserSetupComplete();
2563 List<String> packageList;
2564 synchronized (this) {
2565 packageList = getKeepUninstalledPackagesLocked();
2567 if (packageList != null) {
2568 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2571 synchronized (this) {
2572 // push the force-ephemeral-users policy to the user manager.
2573 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2574 if (deviceOwner != null) {
2575 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2580 private void ensureDeviceOwnerUserStarted() {
2582 synchronized (this) {
2583 if (!mOwners.hasDeviceOwner()) {
2586 userId = mOwners.getDeviceOwnerUserId();
2589 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2591 if (userId != UserHandle.USER_SYSTEM) {
2593 mInjector.getIActivityManager().startUserInBackground(userId);
2595 // STOPSHIP Prevent the DO user from being killed.
2597 } catch (RemoteException e) {
2598 Slog.w(LOG_TAG, "Exception starting user", e);
2603 private void onStartUser(int userId) {
2604 updateScreenCaptureDisabledInWindowManager(userId,
2605 getScreenCaptureDisabled(null, userId));
2606 pushUserRestrictions(userId);
2609 private void cleanUpOldUsers() {
2610 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2612 Set<Integer> usersWithProfileOwners;
2613 Set<Integer> usersWithData;
2614 synchronized(this) {
2615 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2616 usersWithData = new ArraySet<>();
2617 for (int i = 0; i < mUserData.size(); i++) {
2618 usersWithData.add(mUserData.keyAt(i));
2621 List<UserInfo> allUsers = mUserManager.getUsers();
2623 Set<Integer> deletedUsers = new ArraySet<>();
2624 deletedUsers.addAll(usersWithProfileOwners);
2625 deletedUsers.addAll(usersWithData);
2626 for (UserInfo userInfo : allUsers) {
2627 deletedUsers.remove(userInfo.id);
2629 for (Integer userId : deletedUsers) {
2630 removeUserData(userId);
2634 private void handlePasswordExpirationNotification(int userHandle) {
2635 synchronized (this) {
2636 final long now = System.currentTimeMillis();
2638 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2639 userHandle, /* parent */ false);
2640 final int N = admins.size();
2641 for (int i = 0; i < N; i++) {
2642 ActiveAdmin admin = admins.get(i);
2643 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2644 && admin.passwordExpirationTimeout > 0L
2645 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2646 && admin.passwordExpirationDate > 0L) {
2647 sendAdminCommandLocked(admin,
2648 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2651 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2655 private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2657 protected Void doInBackground(Integer... params) {
2658 int userHandle = params[0];
2660 if (userHandle == UserHandle.USER_ALL) {
2661 for (UserInfo userInfo : mUserManager.getUsers(true)) {
2662 manageNotification(userInfo.getUserHandle());
2665 manageNotification(UserHandle.of(userHandle));
2670 private void manageNotification(UserHandle userHandle) {
2671 if (!mUserManager.isUserUnlocked(userHandle)) {
2675 // Call out to KeyChain to check for CAs which are waiting for approval.
2676 final List<String> pendingCertificates;
2678 pendingCertificates = getInstalledCaCertificates(userHandle);
2679 } catch (RemoteException | RuntimeException e) {
2680 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2684 synchronized (DevicePolicyManagerService.this) {
2685 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2687 // Remove deleted certificates. Flush xml if necessary.
2688 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2689 saveSettingsLocked(userHandle.getIdentifier());
2691 // Trim to approved certificates.
2692 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2695 if (pendingCertificates.isEmpty()) {
2696 mInjector.getNotificationManager().cancelAsUser(
2697 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2701 // Build and show a warning notification
2704 int parentUserId = userHandle.getIdentifier();
2705 if (getProfileOwner(userHandle.getIdentifier()) != null) {
2706 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2707 getProfileOwnerName(userHandle.getIdentifier()));
2708 smallIconId = R.drawable.stat_sys_certificate_info;
2709 parentUserId = getProfileParentId(userHandle.getIdentifier());
2710 } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
2711 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2712 getDeviceOwnerName());
2713 smallIconId = R.drawable.stat_sys_certificate_info;
2715 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2716 smallIconId = android.R.drawable.stat_sys_warning;
2719 final int numberOfCertificates = pendingCertificates.size();
2720 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2721 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2722 dialogIntent.setPackage("com.android.settings");
2723 dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
2724 dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
2725 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2726 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
2727 new UserHandle(parentUserId));
2729 final Context userContext;
2731 final String packageName = mContext.getPackageName();
2732 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
2733 } catch (PackageManager.NameNotFoundException e) {
2734 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2737 final Notification noti = new Notification.Builder(userContext)
2738 .setSmallIcon(smallIconId)
2739 .setContentTitle(mContext.getResources().getQuantityText(
2740 R.plurals.ssl_ca_cert_warning, numberOfCertificates))
2741 .setContentText(contentText)
2742 .setContentIntent(notifyIntent)
2743 .setPriority(Notification.PRIORITY_HIGH)
2745 .setColor(mContext.getColor(
2746 com.android.internal.R.color.system_notification_accent_color))
2749 mInjector.getNotificationManager().notifyAsUser(
2750 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2753 private List<String> getInstalledCaCertificates(UserHandle userHandle)
2754 throws RemoteException, RuntimeException {
2755 KeyChainConnection conn = null;
2757 conn = KeyChain.bindAsUser(mContext, userHandle);
2758 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
2759 List<String> result = new ArrayList<>(aliases.size());
2760 for (int i = 0; i < aliases.size(); i++) {
2761 result.add(aliases.get(i).string);
2764 } catch (InterruptedException e) {
2765 Thread.currentThread().interrupt();
2767 } catch (AssertionError e) {
2768 throw new RuntimeException(e);
2778 * @param adminReceiver The admin to add
2779 * @param refreshing true = update an active admin, no error
2782 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2786 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2789 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2790 Bundle onEnableData) {
2791 mContext.enforceCallingOrSelfPermission(
2792 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2793 enforceFullCrossUsersPermission(userHandle);
2795 DevicePolicyData policy = getUserData(userHandle);
2796 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2797 /* throwForMissionPermission= */ true);
2799 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2801 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2802 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2805 synchronized (this) {
2806 long ident = mInjector.binderClearCallingIdentity();
2809 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
2810 throw new IllegalArgumentException("Admin is already added");
2812 if (policy.mRemovingAdmins.contains(adminReceiver)) {
2813 throw new IllegalArgumentException(
2814 "Trying to set an admin which is being removed");
2816 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2817 policy.mAdminMap.put(adminReceiver, newAdmin);
2818 int replaceIndex = -1;
2819 final int N = policy.mAdminList.size();
2820 for (int i=0; i < N; i++) {
2821 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2822 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2827 if (replaceIndex == -1) {
2828 policy.mAdminList.add(newAdmin);
2829 enableIfNecessary(info.getPackageName(), userHandle);
2831 policy.mAdminList.set(replaceIndex, newAdmin);
2833 saveSettingsLocked(userHandle);
2834 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2835 onEnableData, null);
2837 mInjector.binderRestoreCallingIdentity(ident);
2843 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2847 enforceFullCrossUsersPermission(userHandle);
2848 synchronized (this) {
2849 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2854 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2858 enforceFullCrossUsersPermission(userHandle);
2859 synchronized (this) {
2860 DevicePolicyData policyData = getUserData(userHandle);
2861 return policyData.mRemovingAdmins.contains(adminReceiver);
2866 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2870 enforceFullCrossUsersPermission(userHandle);
2871 synchronized (this) {
2872 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2873 if (administrator == null) {
2874 throw new SecurityException("No active admin " + adminReceiver);
2876 return administrator.info.usesPolicy(policyId);
2881 @SuppressWarnings("unchecked")
2882 public List<ComponentName> getActiveAdmins(int userHandle) {
2884 return Collections.EMPTY_LIST;
2887 enforceFullCrossUsersPermission(userHandle);
2888 synchronized (this) {
2889 DevicePolicyData policy = getUserData(userHandle);
2890 final int N = policy.mAdminList.size();
2894 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2895 for (int i=0; i<N; i++) {
2896 res.add(policy.mAdminList.get(i).info.getComponent());
2903 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2907 enforceFullCrossUsersPermission(userHandle);
2908 synchronized (this) {
2909 DevicePolicyData policy = getUserData(userHandle);
2910 final int N = policy.mAdminList.size();
2911 for (int i=0; i<N; i++) {
2912 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2920 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
2924 Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
2925 enforceShell("forceRemoveActiveAdmin");
2926 long ident = mInjector.binderClearCallingIdentity();
2928 final ApplicationInfo ai;
2930 ai = mIPackageManager.getApplicationInfo(adminReceiver.getPackageName(),
2932 } catch (RemoteException e) {
2933 throw new IllegalStateException(e);
2936 throw new IllegalStateException("Couldn't find package to remove admin "
2937 + adminReceiver.getPackageName() + " " + userHandle);
2939 if ((ai.flags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
2940 throw new SecurityException("Attempt to remove non-test admin " + adminReceiver
2941 + adminReceiver + " " + userHandle);
2943 // If admin is a device or profile owner tidy that up first.
2944 synchronized (this) {
2945 if (isDeviceOwner(adminReceiver, userHandle)) {
2946 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
2948 if (isProfileOwner(adminReceiver, userHandle)) {
2949 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
2950 userHandle, /* parent */ false);
2951 clearProfileOwnerLocked(admin, userHandle);
2954 // Remove the admin skipping sending the broadcast.
2955 removeAdminArtifacts(adminReceiver, userHandle);
2957 mInjector.binderRestoreCallingIdentity(ident);
2961 private void enforceShell(String method) {
2962 final int callingUid = Binder.getCallingUid();
2963 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
2964 throw new SecurityException("Non-shell user attempted to call " + method);
2969 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
2973 enforceFullCrossUsersPermission(userHandle);
2974 enforceUserUnlocked(userHandle);
2975 synchronized (this) {
2976 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2977 if (admin == null) {
2980 // Active device/profile owners must remain active admins.
2981 if (isDeviceOwner(adminReceiver, userHandle)
2982 || isProfileOwner(adminReceiver, userHandle)) {
2983 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
2987 if (admin.getUid() != mInjector.binderGetCallingUid()) {
2988 mContext.enforceCallingOrSelfPermission(
2989 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2991 long ident = mInjector.binderClearCallingIdentity();
2993 removeActiveAdminLocked(adminReceiver, userHandle);
2995 mInjector.binderRestoreCallingIdentity(ident);
3001 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3002 ComponentName profileOwner = getProfileOwner(userHandle);
3003 // Profile challenge is supported on N or newer release.
3004 return profileOwner != null &&
3005 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3009 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3013 Preconditions.checkNotNull(who, "ComponentName is null");
3014 validateQualityConstant(quality);
3016 synchronized (this) {
3017 ActiveAdmin ap = getActiveAdminForCallerLocked(
3018 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3019 if (ap.passwordQuality != quality) {
3020 ap.passwordQuality = quality;
3021 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3027 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3029 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3031 enforceFullCrossUsersPermission(userHandle);
3032 synchronized (this) {
3033 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3036 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3037 return admin != null ? admin.passwordQuality : mode;
3040 // Return the strictest policy across all participating admins.
3041 List<ActiveAdmin> admins =
3042 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3043 final int N = admins.size();
3044 for (int i = 0; i < N; i++) {
3045 ActiveAdmin admin = admins.get(i);
3046 if (mode < admin.passwordQuality) {
3047 mode = admin.passwordQuality;
3054 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3055 int userHandle, boolean parent) {
3056 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3057 // If this user has a separate challenge, only return its restrictions.
3058 return getUserDataUnchecked(userHandle).mAdminList;
3060 // Return all admins for this user and the profiles that are visible from this
3061 // user that do not use a separate work challenge.
3062 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3063 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3064 DevicePolicyData policy = getUserData(userInfo.id);
3065 if (!userInfo.isManagedProfile()) {
3066 admins.addAll(policy.mAdminList);
3068 // For managed profiles, we always include the policies set on the parent
3069 // profile. Additionally, we include the ones set on the managed profile
3070 // if no separate challenge is in place.
3071 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3072 final int N = policy.mAdminList.size();
3073 for (int i = 0; i < N; i++) {
3074 ActiveAdmin admin = policy.mAdminList.get(i);
3075 if (admin.hasParentActiveAdmin()) {
3076 admins.add(admin.getParentActiveAdmin());
3078 if (!hasSeparateChallenge) {
3088 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3089 long ident = mInjector.binderClearCallingIdentity();
3091 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3093 mInjector.binderRestoreCallingIdentity(ident);
3098 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3102 Preconditions.checkNotNull(who, "ComponentName is null");
3103 synchronized (this) {
3104 ActiveAdmin ap = getActiveAdminForCallerLocked(
3105 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3106 if (ap.minimumPasswordLength != length) {
3107 ap.minimumPasswordLength = length;
3108 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3114 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3118 enforceFullCrossUsersPermission(userHandle);
3119 synchronized (this) {
3123 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3124 return admin != null ? admin.minimumPasswordLength : length;
3127 // Return the strictest policy across all participating admins.
3128 List<ActiveAdmin> admins =
3129 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3130 final int N = admins.size();
3131 for (int i = 0; i < N; i++) {
3132 ActiveAdmin admin = admins.get(i);
3133 if (length < admin.minimumPasswordLength) {
3134 length = admin.minimumPasswordLength;
3142 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3146 Preconditions.checkNotNull(who, "ComponentName is null");
3147 synchronized (this) {
3148 ActiveAdmin ap = getActiveAdminForCallerLocked(
3149 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3150 if (ap.passwordHistoryLength != length) {
3151 ap.passwordHistoryLength = length;
3152 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3158 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3162 enforceFullCrossUsersPermission(userHandle);
3163 synchronized (this) {
3167 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3168 return admin != null ? admin.passwordHistoryLength : length;
3171 // Return the strictest policy across all participating admins.
3172 List<ActiveAdmin> admins =
3173 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3174 final int N = admins.size();
3175 for (int i = 0; i < N; i++) {
3176 ActiveAdmin admin = admins.get(i);
3177 if (length < admin.passwordHistoryLength) {
3178 length = admin.passwordHistoryLength;
3187 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3191 Preconditions.checkNotNull(who, "ComponentName is null");
3192 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3193 final int userHandle = mInjector.userHandleGetCallingUserId();
3194 synchronized (this) {
3195 ActiveAdmin ap = getActiveAdminForCallerLocked(
3196 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3197 // Calling this API automatically bumps the expiration date
3198 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3199 ap.passwordExpirationDate = expiration;
3200 ap.passwordExpirationTimeout = timeout;
3202 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3203 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3204 .format(new Date(expiration)));
3206 saveSettingsLocked(userHandle);
3208 // in case this is the first one, set the alarm on the appropriate user.
3209 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3214 * Return a single admin's expiration cycle time, or the min of all cycle times.
3215 * Returns 0 if not configured.
3218 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3222 enforceFullCrossUsersPermission(userHandle);
3223 synchronized (this) {
3227 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3228 return admin != null ? admin.passwordExpirationTimeout : timeout;
3231 // Return the strictest policy across all participating admins.
3232 List<ActiveAdmin> admins =
3233 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3234 final int N = admins.size();
3235 for (int i = 0; i < N; i++) {
3236 ActiveAdmin admin = admins.get(i);
3237 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3238 && timeout > admin.passwordExpirationTimeout)) {
3239 timeout = admin.passwordExpirationTimeout;
3247 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3248 final int userId = UserHandle.getCallingUserId();
3249 List<String> changedProviders = null;
3251 synchronized (this) {
3252 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3253 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3254 if (activeAdmin.crossProfileWidgetProviders == null) {
3255 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3257 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3258 if (!providers.contains(packageName)) {
3259 providers.add(packageName);
3260 changedProviders = new ArrayList<>(providers);
3261 saveSettingsLocked(userId);
3265 if (changedProviders != null) {
3266 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3274 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3275 final int userId = UserHandle.getCallingUserId();
3276 List<String> changedProviders = null;
3278 synchronized (this) {
3279 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3280 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3281 if (activeAdmin.crossProfileWidgetProviders == null) {
3284 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3285 if (providers.remove(packageName)) {
3286 changedProviders = new ArrayList<>(providers);
3287 saveSettingsLocked(userId);
3291 if (changedProviders != null) {
3292 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3300 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3301 synchronized (this) {
3302 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3303 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3304 if (activeAdmin.crossProfileWidgetProviders == null
3305 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3308 if (mInjector.binderIsCallingUidMyUid()) {
3309 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3311 return activeAdmin.crossProfileWidgetProviders;
3317 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3318 * Returns 0 if not configured.
3320 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3324 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3325 return admin != null ? admin.passwordExpirationDate : timeout;
3328 // Return the strictest policy across all participating admins.
3329 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3330 final int N = admins.size();
3331 for (int i = 0; i < N; i++) {
3332 ActiveAdmin admin = admins.get(i);
3333 if (timeout == 0L || (admin.passwordExpirationDate != 0
3334 && timeout > admin.passwordExpirationDate)) {
3335 timeout = admin.passwordExpirationDate;
3342 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3346 enforceFullCrossUsersPermission(userHandle);
3347 synchronized (this) {
3348 return getPasswordExpirationLocked(who, userHandle, parent);
3353 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3357 Preconditions.checkNotNull(who, "ComponentName is null");
3358 synchronized (this) {
3359 ActiveAdmin ap = getActiveAdminForCallerLocked(
3360 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3361 if (ap.minimumPasswordUpperCase != length) {
3362 ap.minimumPasswordUpperCase = length;
3363 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3369 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3373 enforceFullCrossUsersPermission(userHandle);
3374 synchronized (this) {
3378 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3379 return admin != null ? admin.minimumPasswordUpperCase : length;
3382 // Return the strictest policy across all participating admins.
3383 List<ActiveAdmin> admins =
3384 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3385 final int N = admins.size();
3386 for (int i = 0; i < N; i++) {
3387 ActiveAdmin admin = admins.get(i);
3388 if (length < admin.minimumPasswordUpperCase) {
3389 length = admin.minimumPasswordUpperCase;
3397 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3398 Preconditions.checkNotNull(who, "ComponentName is null");
3399 synchronized (this) {
3400 ActiveAdmin ap = getActiveAdminForCallerLocked(
3401 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3402 if (ap.minimumPasswordLowerCase != length) {
3403 ap.minimumPasswordLowerCase = length;
3404 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3410 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3414 enforceFullCrossUsersPermission(userHandle);
3415 synchronized (this) {
3419 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3420 return admin != null ? admin.minimumPasswordLowerCase : length;
3423 // Return the strictest policy across all participating admins.
3424 List<ActiveAdmin> admins =
3425 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3426 final int N = admins.size();
3427 for (int i = 0; i < N; i++) {
3428 ActiveAdmin admin = admins.get(i);
3429 if (length < admin.minimumPasswordLowerCase) {
3430 length = admin.minimumPasswordLowerCase;
3438 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3442 Preconditions.checkNotNull(who, "ComponentName is null");
3443 synchronized (this) {
3444 ActiveAdmin ap = getActiveAdminForCallerLocked(
3445 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3446 if (ap.minimumPasswordLetters != length) {
3447 ap.minimumPasswordLetters = length;
3448 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3454 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3458 enforceFullCrossUsersPermission(userHandle);
3459 synchronized (this) {
3463 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3464 return admin != null ? admin.minimumPasswordLetters : length;
3467 // Return the strictest policy across all participating admins.
3468 List<ActiveAdmin> admins =
3469 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3470 final int N = admins.size();
3471 for (int i = 0; i < N; i++) {
3472 ActiveAdmin admin = admins.get(i);
3473 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3476 if (length < admin.minimumPasswordLetters) {
3477 length = admin.minimumPasswordLetters;
3485 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3489 Preconditions.checkNotNull(who, "ComponentName is null");
3490 synchronized (this) {
3491 ActiveAdmin ap = getActiveAdminForCallerLocked(
3492 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3493 if (ap.minimumPasswordNumeric != length) {
3494 ap.minimumPasswordNumeric = length;
3495 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3501 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3505 enforceFullCrossUsersPermission(userHandle);
3506 synchronized (this) {
3510 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3511 return admin != null ? admin.minimumPasswordNumeric : length;
3514 // Return the strictest policy across all participating admins.
3515 List<ActiveAdmin> admins =
3516 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3517 final int N = admins.size();
3518 for (int i = 0; i < N; i++) {
3519 ActiveAdmin admin = admins.get(i);
3520 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3523 if (length < admin.minimumPasswordNumeric) {
3524 length = admin.minimumPasswordNumeric;
3532 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3536 Preconditions.checkNotNull(who, "ComponentName is null");
3537 synchronized (this) {
3538 ActiveAdmin ap = getActiveAdminForCallerLocked(
3539 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3540 if (ap.minimumPasswordSymbols != length) {
3541 ap.minimumPasswordSymbols = length;
3542 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3548 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3552 enforceFullCrossUsersPermission(userHandle);
3553 synchronized (this) {
3557 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3558 return admin != null ? admin.minimumPasswordSymbols : length;
3561 // Return the strictest policy across all participating admins.
3562 List<ActiveAdmin> admins =
3563 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3564 final int N = admins.size();
3565 for (int i = 0; i < N; i++) {
3566 ActiveAdmin admin = admins.get(i);
3567 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3570 if (length < admin.minimumPasswordSymbols) {
3571 length = admin.minimumPasswordSymbols;
3579 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3583 Preconditions.checkNotNull(who, "ComponentName is null");
3584 synchronized (this) {
3585 ActiveAdmin ap = getActiveAdminForCallerLocked(
3586 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3587 if (ap.minimumPasswordNonLetter != length) {
3588 ap.minimumPasswordNonLetter = length;
3589 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3595 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3599 enforceFullCrossUsersPermission(userHandle);
3600 synchronized (this) {
3604 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3605 return admin != null ? admin.minimumPasswordNonLetter : length;
3608 // Return the strictest policy across all participating admins.
3609 List<ActiveAdmin> admins =
3610 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3611 final int N = admins.size();
3612 for (int i = 0; i < N; i++) {
3613 ActiveAdmin admin = admins.get(i);
3614 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3617 if (length < admin.minimumPasswordNonLetter) {
3618 length = admin.minimumPasswordNonLetter;
3626 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3630 enforceFullCrossUsersPermission(userHandle);
3632 synchronized (this) {
3633 // This API can only be called by an active device admin,
3634 // so try to retrieve it to check that the caller is one.
3635 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3636 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3637 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3642 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3646 enforceFullCrossUsersPermission(userHandle);
3647 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3649 synchronized (this) {
3650 int targetUser = getProfileParentId(userHandle);
3651 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3652 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3656 private boolean isActivePasswordSufficientForUserLocked(
3657 DevicePolicyData policy, int userHandle, boolean parent) {
3658 final long id = Binder.clearCallingIdentity();
3660 enforceUserUnlocked(userHandle, parent);
3662 Binder.restoreCallingIdentity(id);
3665 if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle, parent)
3666 || policy.mActivePasswordLength < getPasswordMinimumLength(
3667 null, userHandle, parent)) {
3670 if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3673 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3674 null, userHandle, parent)
3675 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3676 null, userHandle, parent)
3677 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3678 null, userHandle, parent)
3679 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3680 null, userHandle, parent)
3681 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3682 null, userHandle, parent)
3683 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3684 null, userHandle, parent);
3688 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3689 enforceFullCrossUsersPermission(userHandle);
3690 synchronized (this) {
3691 if (!isCallerWithSystemUid()) {
3692 // This API can only be called by an active device admin,
3693 // so try to retrieve it to check that the caller is one.
3694 getActiveAdminForCallerLocked(
3695 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3698 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3700 return policy.mFailedPasswordAttempts;
3705 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3709 Preconditions.checkNotNull(who, "ComponentName is null");
3710 synchronized (this) {
3711 // This API can only be called by an active device admin,
3712 // so try to retrieve it to check that the caller is one.
3713 getActiveAdminForCallerLocked(
3714 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3715 ActiveAdmin ap = getActiveAdminForCallerLocked(
3716 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3717 if (ap.maximumFailedPasswordsForWipe != num) {
3718 ap.maximumFailedPasswordsForWipe = num;
3719 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3725 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3729 enforceFullCrossUsersPermission(userHandle);
3730 synchronized (this) {
3731 ActiveAdmin admin = (who != null)
3732 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3733 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3734 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3739 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3741 return UserHandle.USER_NULL;
3743 enforceFullCrossUsersPermission(userHandle);
3744 synchronized (this) {
3745 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3746 userHandle, parent);
3747 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3752 * Returns the admin with the strictest policy on maximum failed passwords for:
3754 * <li>this user if it has a separate profile challenge, or
3755 * <li>this user and all profiles that don't have their own challenge otherwise.
3757 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3758 * the primary profile.
3759 * Returns {@code null} if no participating admin has that policy set.
3761 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3762 int userHandle, boolean parent) {
3764 ActiveAdmin strictestAdmin = null;
3766 // Return the strictest policy across all participating admins.
3767 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3768 final int N = admins.size();
3769 for (int i = 0; i < N; i++) {
3770 ActiveAdmin admin = admins.get(i);
3771 if (admin.maximumFailedPasswordsForWipe ==
3772 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3773 continue; // No max number of failed passwords policy set for this profile.
3776 // We always favor the primary profile if several profiles have the same value set.
3777 int userId = admin.getUserHandle().getIdentifier();
3779 count > admin.maximumFailedPasswordsForWipe ||
3780 (count == admin.maximumFailedPasswordsForWipe &&
3781 getUserInfo(userId).isPrimary())) {
3782 count = admin.maximumFailedPasswordsForWipe;
3783 strictestAdmin = admin;
3786 return strictestAdmin;
3789 private UserInfo getUserInfo(@UserIdInt int userId) {
3790 final long token = mInjector.binderClearCallingIdentity();
3792 return mUserManager.getUserInfo(userId);
3794 mInjector.binderRestoreCallingIdentity(token);
3799 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3803 final int callingUid = mInjector.binderGetCallingUid();
3804 final int userHandle = mInjector.userHandleGetCallingUserId();
3806 String password = passwordOrNull != null ? passwordOrNull : "";
3808 // Password resetting to empty/null is not allowed for managed profiles.
3809 if (TextUtils.isEmpty(password)) {
3810 enforceNotManagedProfile(userHandle, "clear the active password");
3814 synchronized (this) {
3815 // If caller has PO (or DO) it can change the password, so see if that's the case first.
3816 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3817 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3819 if (admin != null) {
3820 preN = getTargetSdk(admin.info.getPackageName(),
3821 userHandle) <= android.os.Build.VERSION_CODES.M;
3823 // Otherwise, make sure the caller has any active admin with the right policy.
3824 admin = getActiveAdminForCallerLocked(null,
3825 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3826 preN = getTargetSdk(admin.info.getPackageName(),
3827 userHandle) <= android.os.Build.VERSION_CODES.M;
3829 // As of N, password resetting to empty/null is not allowed anymore.
3830 // TODO Should we allow DO/PO to set an empty password?
3831 if (TextUtils.isEmpty(password)) {
3833 throw new SecurityException("Cannot call with null password");
3835 Slog.e(LOG_TAG, "Cannot call with null password");
3839 // As of N, password cannot be changed by the admin if it is already set.
3840 if (isLockScreenSecureUnchecked(userHandle)) {
3842 throw new SecurityException("Admin cannot change current password");
3844 Slog.e(LOG_TAG, "Admin cannot change current password");
3849 // Do not allow to reset password when current user has a managed profile
3850 if (!isManagedProfile(userHandle)) {
3851 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3852 if (userInfo.isManagedProfile()) {
3854 throw new IllegalStateException(
3855 "Cannot reset password on user has managed profile");
3857 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
3863 // Do not allow to reset password when user is locked
3864 if (!mUserManager.isUserUnlocked(userHandle)) {
3866 throw new IllegalStateException("Cannot reset password when user is locked");
3868 Slog.e(LOG_TAG, "Cannot reset password when user is locked");
3873 quality = getPasswordQuality(null, userHandle, /* parent */ false);
3874 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
3875 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3877 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
3878 int realQuality = LockPatternUtils.computePasswordQuality(password);
3879 if (realQuality < quality
3880 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3881 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
3882 + Integer.toHexString(realQuality)
3883 + " does not meet required quality 0x"
3884 + Integer.toHexString(quality));
3887 quality = Math.max(realQuality, quality);
3889 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
3890 if (password.length() < length) {
3891 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
3892 + " does not meet required length " + length);
3895 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3902 for (int i = 0; i < password.length(); i++) {
3903 char c = password.charAt(i);
3904 if (c >= 'A' && c <= 'Z') {
3907 } else if (c >= 'a' && c <= 'z') {
3910 } else if (c >= '0' && c <= '9') {
3918 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
3919 if(letters < neededLetters) {
3920 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
3921 + " does not meet required number of letters " + neededLetters);
3924 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
3925 if (numbers < neededNumbers) {
3926 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
3927 + " does not meet required number of numerical digits "
3931 int neededLowerCase = getPasswordMinimumLowerCase(
3932 null, userHandle, /* parent */ false);
3933 if (lowercase < neededLowerCase) {
3934 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
3935 + " does not meet required number of lowercase letters "
3939 int neededUpperCase = getPasswordMinimumUpperCase(
3940 null, userHandle, /* parent */ false);
3941 if (uppercase < neededUpperCase) {
3942 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
3943 + " does not meet required number of uppercase letters "
3947 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
3948 if (symbols < neededSymbols) {
3949 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
3950 + " does not meet required number of special symbols " + neededSymbols);
3953 int neededNonLetter = getPasswordMinimumNonLetter(
3954 null, userHandle, /* parent */ false);
3955 if (nonletter < neededNonLetter) {
3956 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
3957 + " does not meet required number of non-letter characters "
3964 DevicePolicyData policy = getUserData(userHandle);
3965 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
3966 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
3970 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
3971 boolean doNotAskCredentialsOnBoot =
3972 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
3973 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
3974 setDoNotAskCredentialsOnBoot();
3977 // Don't do this with the lock held, because it is going to call
3978 // back in to the service.
3979 final long ident = mInjector.binderClearCallingIdentity();
3981 if (!TextUtils.isEmpty(password)) {
3982 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
3984 mLockPatternUtils.clearLock(userHandle);
3986 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
3988 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
3989 UserHandle.USER_ALL);
3991 synchronized (this) {
3992 int newOwner = requireEntry ? callingUid : -1;
3993 if (policy.mPasswordOwner != newOwner) {
3994 policy.mPasswordOwner = newOwner;
3995 saveSettingsLocked(userHandle);
3999 mInjector.binderRestoreCallingIdentity(ident);
4005 private boolean isLockScreenSecureUnchecked(int userId) {
4006 long ident = mInjector.binderClearCallingIdentity();
4008 return mLockPatternUtils.isSecure(userId);
4010 mInjector.binderRestoreCallingIdentity(ident);
4014 private void setDoNotAskCredentialsOnBoot() {
4015 synchronized (this) {
4016 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4017 if (!policyData.doNotAskCredentialsOnBoot) {
4018 policyData.doNotAskCredentialsOnBoot = true;
4019 saveSettingsLocked(UserHandle.USER_SYSTEM);
4025 public boolean getDoNotAskCredentialsOnBoot() {
4026 mContext.enforceCallingOrSelfPermission(
4027 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4028 synchronized (this) {
4029 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4030 return policyData.doNotAskCredentialsOnBoot;
4035 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4039 Preconditions.checkNotNull(who, "ComponentName is null");
4040 final int userHandle = mInjector.userHandleGetCallingUserId();
4041 synchronized (this) {
4042 ActiveAdmin ap = getActiveAdminForCallerLocked(
4043 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4044 if (ap.maximumTimeToUnlock != timeMs) {
4045 ap.maximumTimeToUnlock = timeMs;
4046 saveSettingsLocked(userHandle);
4047 updateMaximumTimeToLockLocked(userHandle);
4052 void updateMaximumTimeToLockLocked(int userHandle) {
4053 // Calculate the min timeout for all profiles - including the ones with a separate
4054 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4055 // challenge only and keep the screen on. However there is no easy way of doing that at the
4056 // moment so we set the screen off timeout regardless of whether it affects the parent user
4057 // or the profile challenge only.
4058 long timeMs = Long.MAX_VALUE;
4059 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4060 for (int profileId : profileIds) {
4061 DevicePolicyData policy = getUserDataUnchecked(profileId);
4062 final int N = policy.mAdminList.size();
4063 for (int i = 0; i < N; i++) {
4064 ActiveAdmin admin = policy.mAdminList.get(i);
4065 if (admin.maximumTimeToUnlock > 0
4066 && timeMs > admin.maximumTimeToUnlock) {
4067 timeMs = admin.maximumTimeToUnlock;
4069 // If userInfo.id is a managed profile, we also need to look at
4070 // the policies set on the parent.
4071 if (admin.hasParentActiveAdmin()) {
4072 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4073 if (parentAdmin.maximumTimeToUnlock > 0
4074 && timeMs > parentAdmin.maximumTimeToUnlock) {
4075 timeMs = parentAdmin.maximumTimeToUnlock;
4081 // We only store the last maximum time to lock on the parent profile. So if calling from a
4082 // managed profile, retrieve the policy for the parent.
4083 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4084 if (policy.mLastMaximumTimeToLock == timeMs) {
4087 policy.mLastMaximumTimeToLock = timeMs;
4089 final long ident = mInjector.binderClearCallingIdentity();
4091 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4092 // Make sure KEEP_SCREEN_ON is disabled, since that
4093 // would allow bypassing of the maximum time to lock.
4094 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4097 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4098 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4100 mInjector.binderRestoreCallingIdentity(ident);
4105 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4109 enforceFullCrossUsersPermission(userHandle);
4110 synchronized (this) {
4112 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4113 return admin != null ? admin.maximumTimeToUnlock : 0;
4115 // Return the strictest policy across all participating admins.
4116 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4117 userHandle, parent);
4118 return getMaximumTimeToLockPolicyFromAdmins(admins);
4123 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4127 enforceFullCrossUsersPermission(userHandle);
4128 synchronized (this) {
4129 // All admins for this user.
4130 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4131 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4132 DevicePolicyData policy = getUserData(userInfo.id);
4133 admins.addAll(policy.mAdminList);
4134 // If it is a managed profile, it may have parent active admins
4135 if (userInfo.isManagedProfile()) {
4136 for (ActiveAdmin admin : policy.mAdminList) {
4137 if (admin.hasParentActiveAdmin()) {
4138 admins.add(admin.getParentActiveAdmin());
4143 return getMaximumTimeToLockPolicyFromAdmins(admins);
4147 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4149 final int N = admins.size();
4150 for (int i = 0; i < N; i++) {
4151 ActiveAdmin admin = admins.get(i);
4153 time = admin.maximumTimeToUnlock;
4154 } else if (admin.maximumTimeToUnlock != 0
4155 && time > admin.maximumTimeToUnlock) {
4156 time = admin.maximumTimeToUnlock;
4163 public void lockNow(boolean parent) {
4167 synchronized (this) {
4168 // This API can only be called by an active device admin,
4169 // so try to retrieve it to check that the caller is one.
4170 getActiveAdminForCallerLocked(
4171 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4173 int userToLock = mInjector.userHandleGetCallingUserId();
4175 // Unless this is a managed profile with work challenge enabled, lock all users.
4176 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4177 userToLock = UserHandle.USER_ALL;
4179 final long ident = mInjector.binderClearCallingIdentity();
4181 mLockPatternUtils.requireStrongAuth(
4182 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4183 if (userToLock == UserHandle.USER_ALL) {
4184 // Power off the display
4185 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4186 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4187 mInjector.getIWindowManager().lockNow(null);
4189 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4191 } catch (RemoteException e) {
4193 mInjector.binderRestoreCallingIdentity(ident);
4199 public void enforceCanManageCaCerts(ComponentName who) {
4201 if (!isCallerDelegatedCertInstaller()) {
4202 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4205 synchronized (this) {
4206 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4211 private void enforceCanManageInstalledKeys(ComponentName who) {
4213 if (!isCallerDelegatedCertInstaller()) {
4214 throw new SecurityException("who == null, but caller is not cert installer");
4217 synchronized (this) {
4218 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4223 private boolean isCallerDelegatedCertInstaller() {
4224 final int callingUid = mInjector.binderGetCallingUid();
4225 final int userHandle = UserHandle.getUserId(callingUid);
4226 synchronized (this) {
4227 final DevicePolicyData policy = getUserData(userHandle);
4228 if (policy.mDelegatedCertInstallerPackage == null) {
4233 int uid = mContext.getPackageManager().getPackageUidAsUser(
4234 policy.mDelegatedCertInstallerPackage, userHandle);
4235 return uid == callingUid;
4236 } catch (NameNotFoundException e) {
4243 public boolean approveCaCert(String alias, int userId, boolean approval) {
4244 enforceManageUsers();
4245 synchronized (this) {
4246 Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4247 boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4251 saveSettingsLocked(userId);
4253 new MonitoringCertNotificationTask().execute(userId);
4258 public boolean isCaCertApproved(String alias, int userId) {
4259 enforceManageUsers();
4260 synchronized (this) {
4261 return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4265 private void removeCaApprovalsIfNeeded(int userId) {
4266 for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4267 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4268 if (userInfo.isManagedProfile()){
4269 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4272 synchronized (this) {
4273 getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4274 saveSettingsLocked(userInfo.id);
4277 new MonitoringCertNotificationTask().execute(userInfo.id);
4283 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4284 enforceCanManageCaCerts(admin);
4288 X509Certificate cert = parseCert(certBuffer);
4289 pemCert = Credentials.convertToPem(cert);
4290 } catch (CertificateException ce) {
4291 Log.e(LOG_TAG, "Problem converting cert", ce);
4293 } catch (IOException ioe) {
4294 Log.e(LOG_TAG, "Problem reading cert", ioe);
4298 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4299 final long id = mInjector.binderClearCallingIdentity();
4301 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4303 keyChainConnection.getService().installCaCertificate(pemCert);
4305 } catch (RemoteException e) {
4306 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4308 keyChainConnection.close();
4310 } catch (InterruptedException e1) {
4311 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4312 Thread.currentThread().interrupt();
4314 mInjector.binderRestoreCallingIdentity(id);
4319 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4320 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4321 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4326 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4327 enforceCanManageCaCerts(admin);
4329 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4330 final long id = mInjector.binderClearCallingIdentity();
4332 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4334 for (int i = 0 ; i < aliases.length; i++) {
4335 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4337 } catch (RemoteException e) {
4338 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4340 keyChainConnection.close();
4342 } catch (InterruptedException ie) {
4343 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4344 Thread.currentThread().interrupt();
4346 mInjector.binderRestoreCallingIdentity(id);
4351 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4352 String alias, boolean requestAccess) {
4353 enforceCanManageInstalledKeys(who);
4355 final int callingUid = mInjector.binderGetCallingUid();
4356 final long id = mInjector.binderClearCallingIdentity();
4358 final KeyChainConnection keyChainConnection =
4359 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4361 IKeyChainService keyChain = keyChainConnection.getService();
4362 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4365 if (requestAccess) {
4366 keyChain.setGrant(callingUid, alias, true);
4369 } catch (RemoteException e) {
4370 Log.e(LOG_TAG, "Installing certificate", e);
4372 keyChainConnection.close();
4374 } catch (InterruptedException e) {
4375 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4376 Thread.currentThread().interrupt();
4378 mInjector.binderRestoreCallingIdentity(id);
4384 public boolean removeKeyPair(ComponentName who, String alias) {
4385 enforceCanManageInstalledKeys(who);
4387 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4388 final long id = Binder.clearCallingIdentity();
4390 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4392 IKeyChainService keyChain = keyChainConnection.getService();
4393 return keyChain.removeKeyPair(alias);
4394 } catch (RemoteException e) {
4395 Log.e(LOG_TAG, "Removing keypair", e);
4397 keyChainConnection.close();
4399 } catch (InterruptedException e) {
4400 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4401 Thread.currentThread().interrupt();
4403 Binder.restoreCallingIdentity(id);
4409 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4410 final IBinder response) {
4411 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4412 if (!isCallerWithSystemUid()) {
4416 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4417 // If there is a profile owner, redirect to that; otherwise query the device owner.
4418 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4419 if (aliasChooser == null && caller.isSystem()) {
4420 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4421 if (deviceOwnerAdmin != null) {
4422 aliasChooser = deviceOwnerAdmin.info.getComponent();
4425 if (aliasChooser == null) {
4426 sendPrivateKeyAliasResponse(null, response);
4430 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4431 intent.setComponent(aliasChooser);
4432 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4433 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4434 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4435 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4437 final long id = mInjector.binderClearCallingIdentity();
4439 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4441 public void onReceive(Context context, Intent intent) {
4442 final String chosenAlias = getResultData();
4443 sendPrivateKeyAliasResponse(chosenAlias, response);
4445 }, null, Activity.RESULT_OK, null, null);
4447 mInjector.binderRestoreCallingIdentity(id);
4451 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4452 final IKeyChainAliasCallback keyChainAliasResponse =
4453 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4454 new AsyncTask<Void, Void, Void>() {
4456 protected Void doInBackground(Void... unused) {
4458 keyChainAliasResponse.alias(alias);
4459 } catch (Exception e) {
4460 // Catch everything (not just RemoteException): caller could throw a
4461 // RuntimeException back across processes.
4462 Log.e(LOG_TAG, "error while responding to callback", e);
4470 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4471 throws SecurityException {
4472 int userHandle = UserHandle.getCallingUserId();
4473 synchronized (this) {
4474 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4475 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4476 if (installerPackage != null &&
4477 !isPackageInstalledForUser(installerPackage, userHandle)) {
4478 throw new IllegalArgumentException("Package " + installerPackage
4479 + " is not installed on the current user");
4482 DevicePolicyData policy = getUserData(userHandle);
4483 policy.mDelegatedCertInstallerPackage = installerPackage;
4484 saveSettingsLocked(userHandle);
4489 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4490 int userHandle = UserHandle.getCallingUserId();
4491 synchronized (this) {
4492 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4493 DevicePolicyData policy = getUserData(userHandle);
4494 return policy.mDelegatedCertInstallerPackage;
4499 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4500 * not installed and therefore not available.
4502 * @throws SecurityException if the caller is not a profile or device owner.
4503 * @throws UnsupportedException if the package does not support being set as always-on.
4506 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4507 throws SecurityException {
4508 synchronized (this) {
4509 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4512 final int userId = mInjector.userHandleGetCallingUserId();
4513 final long token = mInjector.binderClearCallingIdentity();
4515 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4518 ConnectivityManager connectivityManager = (ConnectivityManager)
4519 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4520 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4521 throw new UnsupportedOperationException();
4524 mInjector.binderRestoreCallingIdentity(token);
4530 public String getAlwaysOnVpnPackage(ComponentName admin)
4531 throws SecurityException {
4532 synchronized (this) {
4533 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4536 final int userId = mInjector.userHandleGetCallingUserId();
4537 final long token = mInjector.binderClearCallingIdentity();
4539 ConnectivityManager connectivityManager = (ConnectivityManager)
4540 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4541 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4543 mInjector.binderRestoreCallingIdentity(token);
4547 private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
4548 if (wipeExtRequested) {
4549 StorageManager sm = (StorageManager) mContext.getSystemService(
4550 Context.STORAGE_SERVICE);
4551 sm.wipeAdoptableDisks();
4554 RecoverySystem.rebootWipeUserData(mContext, reason);
4555 } catch (IOException | SecurityException e) {
4556 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4561 public void wipeData(int flags) {
4565 final int userHandle = mInjector.userHandleGetCallingUserId();
4566 enforceFullCrossUsersPermission(userHandle);
4568 final String source;
4569 synchronized (this) {
4570 // This API can only be called by an active device admin,
4571 // so try to retrieve it to check that the caller is one.
4572 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4573 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4574 source = admin.info.getComponent().flattenToShortString();
4576 long ident = mInjector.binderClearCallingIdentity();
4578 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4579 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4580 throw new SecurityException(
4581 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4583 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4584 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4585 if (manager != null) {
4590 mInjector.binderRestoreCallingIdentity(ident);
4593 final boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4594 wipeDeviceNoLock(wipeExtRequested, userHandle,
4595 "DevicePolicyManager.wipeData() from " + source);
4598 private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
4599 final long ident = mInjector.binderClearCallingIdentity();
4601 if (userHandle == UserHandle.USER_SYSTEM) {
4602 wipeDataNoLock(wipeExtRequested, reason);
4604 mHandler.post(new Runnable() {
4608 IActivityManager am = mInjector.getIActivityManager();
4609 if (am.getCurrentUser().id == userHandle) {
4610 am.switchUser(UserHandle.USER_SYSTEM);
4613 boolean isManagedProfile = isManagedProfile(userHandle);
4614 if (!mUserManager.removeUser(userHandle)) {
4615 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4616 } else if (isManagedProfile) {
4617 sendWipeProfileNotification();
4619 } catch (RemoteException re) {
4626 mInjector.binderRestoreCallingIdentity(ident);
4630 private void sendWipeProfileNotification() {
4631 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4632 Notification notification = new Notification.Builder(mContext)
4633 .setSmallIcon(android.R.drawable.stat_sys_warning)
4634 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4635 .setContentText(contentText)
4636 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4637 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4639 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4642 private void clearWipeProfileNotification() {
4643 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4647 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4651 enforceFullCrossUsersPermission(userHandle);
4652 mContext.enforceCallingOrSelfPermission(
4653 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4655 synchronized (this) {
4656 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4657 if (admin == null) {
4658 result.sendResult(null);
4661 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4662 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4663 intent.setComponent(admin.info.getComponent());
4664 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4665 null, new BroadcastReceiver() {
4667 public void onReceive(Context context, Intent intent) {
4668 result.sendResult(getResultExtras(false));
4670 }, null, Activity.RESULT_OK, null, null);
4675 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4676 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4680 enforceFullCrossUsersPermission(userHandle);
4681 mContext.enforceCallingOrSelfPermission(
4682 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4684 // If the managed profile doesn't have a separate password, set the metrics to default
4685 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
4686 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4696 validateQualityConstant(quality);
4697 DevicePolicyData policy = getUserData(userHandle);
4698 synchronized (this) {
4699 policy.mActivePasswordQuality = quality;
4700 policy.mActivePasswordLength = length;
4701 policy.mActivePasswordLetters = letters;
4702 policy.mActivePasswordLowerCase = lowercase;
4703 policy.mActivePasswordUpperCase = uppercase;
4704 policy.mActivePasswordNumeric = numbers;
4705 policy.mActivePasswordSymbols = symbols;
4706 policy.mActivePasswordNonLetter = nonletter;
4711 public void reportPasswordChanged(int userId) {
4715 enforceFullCrossUsersPermission(userId);
4717 // Managed Profile password can only be changed when it has a separate challenge.
4718 if (!isSeparateProfileChallengeEnabled(userId)) {
4719 enforceNotManagedProfile(userId, "set the active password");
4722 mContext.enforceCallingOrSelfPermission(
4723 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4725 DevicePolicyData policy = getUserData(userId);
4727 long ident = mInjector.binderClearCallingIdentity();
4729 synchronized (this) {
4730 policy.mFailedPasswordAttempts = 0;
4731 saveSettingsLocked(userId);
4732 updatePasswordExpirationsLocked(userId);
4733 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
4735 // Send a broadcast to each profile using this password as its primary unlock.
4736 sendAdminCommandForLockscreenPoliciesLocked(
4737 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4738 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
4740 removeCaApprovalsIfNeeded(userId);
4742 mInjector.binderRestoreCallingIdentity(ident);
4747 * Called any time the device password is updated. Resets all password expiration clocks.
4749 private void updatePasswordExpirationsLocked(int userHandle) {
4750 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4751 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4752 userHandle, /* parent */ false);
4753 final int N = admins.size();
4754 for (int i = 0; i < N; i++) {
4755 ActiveAdmin admin = admins.get(i);
4756 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4757 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4758 long timeout = admin.passwordExpirationTimeout;
4759 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4760 admin.passwordExpirationDate = expiration;
4763 for (int affectedUserId : affectedUserIds) {
4764 saveSettingsLocked(affectedUserId);
4769 public void reportFailedPasswordAttempt(int userHandle) {
4770 enforceFullCrossUsersPermission(userHandle);
4771 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4772 enforceNotManagedProfile(userHandle,
4773 "report failed password attempt if separate profile challenge is not in place");
4775 mContext.enforceCallingOrSelfPermission(
4776 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4778 final long ident = mInjector.binderClearCallingIdentity();
4780 boolean wipeData = false;
4782 synchronized (this) {
4783 DevicePolicyData policy = getUserData(userHandle);
4784 policy.mFailedPasswordAttempts++;
4785 saveSettingsLocked(userHandle);
4787 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4788 userHandle, /* parent */ false);
4789 int max = strictestAdmin != null
4790 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4791 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4792 // Wipe the user/profile associated with the policy that was violated. This
4793 // is not necessarily calling user: if the policy that fired was from a
4794 // managed profile rather than the main user profile, we wipe former only.
4796 identifier = strictestAdmin.getUserHandle().getIdentifier();
4799 sendAdminCommandForLockscreenPoliciesLocked(
4800 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
4801 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4805 // Call without holding lock.
4806 wipeDeviceNoLock(false, identifier,
4807 "reportFailedPasswordAttempt()");
4810 mInjector.binderRestoreCallingIdentity(ident);
4813 if (mInjector.securityLogIsLoggingEnabled()) {
4814 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4815 /*method strength*/ 1);
4820 public void reportSuccessfulPasswordAttempt(int userHandle) {
4821 enforceFullCrossUsersPermission(userHandle);
4822 mContext.enforceCallingOrSelfPermission(
4823 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4825 synchronized (this) {
4826 DevicePolicyData policy = getUserData(userHandle);
4827 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
4828 long ident = mInjector.binderClearCallingIdentity();
4830 policy.mFailedPasswordAttempts = 0;
4831 policy.mPasswordOwner = -1;
4832 saveSettingsLocked(userHandle);
4834 sendAdminCommandForLockscreenPoliciesLocked(
4835 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
4836 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4839 mInjector.binderRestoreCallingIdentity(ident);
4844 if (mInjector.securityLogIsLoggingEnabled()) {
4845 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4846 /*method strength*/ 1);
4851 public void reportFailedFingerprintAttempt(int userHandle) {
4852 enforceFullCrossUsersPermission(userHandle);
4853 mContext.enforceCallingOrSelfPermission(
4854 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4855 if (mInjector.securityLogIsLoggingEnabled()) {
4856 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4857 /*method strength*/ 0);
4862 public void reportSuccessfulFingerprintAttempt(int userHandle) {
4863 enforceFullCrossUsersPermission(userHandle);
4864 mContext.enforceCallingOrSelfPermission(
4865 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4866 if (mInjector.securityLogIsLoggingEnabled()) {
4867 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4868 /*method strength*/ 0);
4873 public void reportKeyguardDismissed(int userHandle) {
4874 enforceFullCrossUsersPermission(userHandle);
4875 mContext.enforceCallingOrSelfPermission(
4876 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4878 if (mInjector.securityLogIsLoggingEnabled()) {
4879 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
4884 public void reportKeyguardSecured(int userHandle) {
4885 enforceFullCrossUsersPermission(userHandle);
4886 mContext.enforceCallingOrSelfPermission(
4887 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4889 if (mInjector.securityLogIsLoggingEnabled()) {
4890 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
4895 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
4896 String exclusionList) {
4900 synchronized(this) {
4901 Preconditions.checkNotNull(who, "ComponentName is null");
4903 // Only check if system user has set global proxy. We don't allow other users to set it.
4904 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4905 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4906 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
4908 // Scan through active admins and find if anyone has already
4909 // set the global proxy.
4910 Set<ComponentName> compSet = policy.mAdminMap.keySet();
4911 for (ComponentName component : compSet) {
4912 ActiveAdmin ap = policy.mAdminMap.get(component);
4913 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
4914 // Another admin already sets the global proxy
4915 // Return it to the caller.
4920 // If the user is not system, don't set the global proxy. Fail silently.
4921 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
4922 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
4923 + UserHandle.getCallingUserId() + " is not permitted.");
4926 if (proxySpec == null) {
4927 admin.specifiesGlobalProxy = false;
4928 admin.globalProxySpec = null;
4929 admin.globalProxyExclusionList = null;
4932 admin.specifiesGlobalProxy = true;
4933 admin.globalProxySpec = proxySpec;
4934 admin.globalProxyExclusionList = exclusionList;
4937 // Reset the global proxy accordingly
4938 // Do this using system permissions, as apps cannot write to secure settings
4939 long origId = mInjector.binderClearCallingIdentity();
4941 resetGlobalProxyLocked(policy);
4943 mInjector.binderRestoreCallingIdentity(origId);
4950 public ComponentName getGlobalProxyAdmin(int userHandle) {
4954 enforceFullCrossUsersPermission(userHandle);
4955 synchronized(this) {
4956 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4957 // Scan through active admins and find if anyone has already
4958 // set the global proxy.
4959 final int N = policy.mAdminList.size();
4960 for (int i = 0; i < N; i++) {
4961 ActiveAdmin ap = policy.mAdminList.get(i);
4962 if (ap.specifiesGlobalProxy) {
4963 // Device admin sets the global proxy
4964 // Return it to the caller.
4965 return ap.info.getComponent();
4969 // No device admin sets the global proxy.
4974 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
4975 synchronized (this) {
4976 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4978 long token = mInjector.binderClearCallingIdentity();
4980 ConnectivityManager connectivityManager = (ConnectivityManager)
4981 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4982 connectivityManager.setGlobalProxy(proxyInfo);
4984 mInjector.binderRestoreCallingIdentity(token);
4988 private void resetGlobalProxyLocked(DevicePolicyData policy) {
4989 final int N = policy.mAdminList.size();
4990 for (int i = 0; i < N; i++) {
4991 ActiveAdmin ap = policy.mAdminList.get(i);
4992 if (ap.specifiesGlobalProxy) {
4993 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
4997 // No device admins defining global proxies - reset global proxy settings to none
4998 saveGlobalProxyLocked(null, null);
5001 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5002 if (exclusionList == null) {
5005 if (proxySpec == null) {
5008 // Remove white spaces
5009 proxySpec = proxySpec.trim();
5010 String data[] = proxySpec.split(":");
5011 int proxyPort = 8080;
5012 if (data.length > 1) {
5014 proxyPort = Integer.parseInt(data[1]);
5015 } catch (NumberFormatException e) {}
5017 exclusionList = exclusionList.trim();
5019 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5020 if (!proxyProperties.isValid()) {
5021 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5024 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5025 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5026 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5031 * Set the storage encryption request for a single admin. Returns the new total request
5032 * status (for all admins).
5035 public int setStorageEncryption(ComponentName who, boolean encrypt) {
5037 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5039 Preconditions.checkNotNull(who, "ComponentName is null");
5040 final int userHandle = UserHandle.getCallingUserId();
5041 synchronized (this) {
5042 // Check for permissions
5043 // Only system user can set storage encryption
5044 if (userHandle != UserHandle.USER_SYSTEM) {
5045 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5046 + UserHandle.getCallingUserId() + " is not permitted.");
5050 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5051 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5053 // Quick exit: If the filesystem does not support encryption, we can exit early.
5054 if (!isEncryptionSupported()) {
5055 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5058 // (1) Record the value for the admin so it's sticky
5059 if (ap.encryptionRequested != encrypt) {
5060 ap.encryptionRequested = encrypt;
5061 saveSettingsLocked(userHandle);
5064 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5065 // (2) Compute "max" for all admins
5066 boolean newRequested = false;
5067 final int N = policy.mAdminList.size();
5068 for (int i = 0; i < N; i++) {
5069 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5072 // Notify OS of new request
5073 setEncryptionRequested(newRequested);
5075 // Return the new global request status
5077 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5078 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5083 * Get the current storage encryption request status for a given admin, or aggregate of all
5087 public boolean getStorageEncryption(ComponentName who, int userHandle) {
5091 enforceFullCrossUsersPermission(userHandle);
5092 synchronized (this) {
5093 // Check for permissions if a particular caller is specified
5095 // When checking for a single caller, status is based on caller's request
5096 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5097 return ap != null ? ap.encryptionRequested : false;
5100 // If no particular caller is specified, return the aggregate set of requests.
5101 // This is short circuited by returning true on the first hit.
5102 DevicePolicyData policy = getUserData(userHandle);
5103 final int N = policy.mAdminList.size();
5104 for (int i = 0; i < N; i++) {
5105 if (policy.mAdminList.get(i).encryptionRequested) {
5114 * Get the current encryption status of the device.
5117 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5119 // Ok to return current status.
5121 enforceFullCrossUsersPermission(userHandle);
5123 // It's not critical here, but let's make sure the package name is correct, in case
5124 // we start using it for different purposes.
5125 ensureCallerPackage(callerPackage);
5127 final ApplicationInfo ai;
5129 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5130 } catch (RemoteException e) {
5131 throw new SecurityException(e);
5134 boolean legacyApp = false;
5135 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5137 } else if ("com.google.android.apps.enterprise.dmagent".equals(ai.packageName)
5138 && ai.versionCode == 697) {
5139 // TODO: STOPSHIP remove this (revert ag/895987) once a new prebuilt is dropped
5143 final int rawStatus = getEncryptionStatus();
5144 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5145 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5151 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
5153 private boolean isEncryptionSupported() {
5154 // Note, this can be implemented as
5155 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5156 // But is provided as a separate internal method if there's a faster way to do a
5157 // simple check for supported-or-not.
5158 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5162 * Hook to low-levels: Reporting the current status of encryption.
5163 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5164 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5165 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5166 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5167 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5169 private int getEncryptionStatus() {
5170 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5171 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5172 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5173 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5174 } else if (mInjector.storageManagerIsEncrypted()) {
5175 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5176 } else if (mInjector.storageManagerIsEncryptable()) {
5177 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5179 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5184 * Hook to low-levels: If needed, record the new admin setting for encryption.
5186 private void setEncryptionRequested(boolean encrypt) {
5190 * Set whether the screen capture is disabled for the user managed by the specified admin.
5193 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5197 Preconditions.checkNotNull(who, "ComponentName is null");
5198 final int userHandle = UserHandle.getCallingUserId();
5199 synchronized (this) {
5200 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5201 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5202 if (ap.disableScreenCapture != disabled) {
5203 ap.disableScreenCapture = disabled;
5204 saveSettingsLocked(userHandle);
5205 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5211 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5212 * active admin (if given admin is null).
5215 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5219 synchronized (this) {
5221 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5222 return (admin != null) ? admin.disableScreenCapture : false;
5225 DevicePolicyData policy = getUserData(userHandle);
5226 final int N = policy.mAdminList.size();
5227 for (int i = 0; i < N; i++) {
5228 ActiveAdmin admin = policy.mAdminList.get(i);
5229 if (admin.disableScreenCapture) {
5237 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5238 final boolean disabled) {
5239 mHandler.post(new Runnable() {
5243 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5244 } catch (RemoteException e) {
5245 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5252 * Set whether auto time is required by the specified admin (must be device owner).
5255 public void setAutoTimeRequired(ComponentName who, boolean required) {
5259 Preconditions.checkNotNull(who, "ComponentName is null");
5260 final int userHandle = UserHandle.getCallingUserId();
5261 synchronized (this) {
5262 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5263 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5264 if (admin.requireAutoTime != required) {
5265 admin.requireAutoTime = required;
5266 saveSettingsLocked(userHandle);
5270 // Turn AUTO_TIME on in settings if it is required
5272 long ident = mInjector.binderClearCallingIdentity();
5274 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5276 mInjector.binderRestoreCallingIdentity(ident);
5282 * Returns whether or not auto time is required by the device owner.
5285 public boolean getAutoTimeRequired() {
5289 synchronized (this) {
5290 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5291 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5296 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5300 Preconditions.checkNotNull(who, "ComponentName is null");
5301 // Allow setting this policy to true only if there is a split system user.
5302 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5303 throw new UnsupportedOperationException(
5304 "Cannot force ephemeral users on systems without split system user.");
5306 boolean removeAllUsers = false;
5307 synchronized (this) {
5308 final ActiveAdmin deviceOwner =
5309 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5310 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5311 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5312 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5313 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5314 removeAllUsers = forceEphemeralUsers;
5317 if (removeAllUsers) {
5318 long identitity = mInjector.binderClearCallingIdentity();
5320 mUserManagerInternal.removeAllUsers();
5322 mInjector.binderRestoreCallingIdentity(identitity);
5328 public boolean getForceEphemeralUsers(ComponentName who) {
5332 Preconditions.checkNotNull(who, "ComponentName is null");
5333 synchronized (this) {
5334 final ActiveAdmin deviceOwner =
5335 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5336 return deviceOwner.forceEphemeralUsers;
5340 private boolean isDeviceOwnerManagedSingleUserDevice() {
5341 synchronized (this) {
5342 if (!mOwners.hasDeviceOwner()) {
5346 final long callingIdentity = mInjector.binderClearCallingIdentity();
5348 if (mInjector.userManagerIsSplitSystemUser()) {
5349 // In split system user mode, only allow the case where the device owner is managing
5350 // the only non-system user of the device
5351 return (mUserManager.getUserCount() == 2
5352 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5354 return mUserManager.getUserCount() == 1;
5357 mInjector.binderRestoreCallingIdentity(callingIdentity);
5361 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5362 synchronized (this) {
5363 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5365 if (!isDeviceOwnerManagedSingleUserDevice()) {
5366 throw new SecurityException(
5367 "There should only be one user, managed by Device Owner");
5372 public boolean requestBugreport(ComponentName who) {
5376 Preconditions.checkNotNull(who, "ComponentName is null");
5377 ensureDeviceOwnerManagingSingleUser(who);
5379 if (mRemoteBugreportServiceIsActive.get()
5380 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5381 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5385 final long callingIdentity = mInjector.binderClearCallingIdentity();
5387 ActivityManagerNative.getDefault().requestBugReport(
5388 ActivityManager.BUGREPORT_OPTION_REMOTE);
5390 mRemoteBugreportServiceIsActive.set(true);
5391 mRemoteBugreportSharingAccepted.set(false);
5392 registerRemoteBugreportReceivers();
5393 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5394 RemoteBugreportUtils.buildNotification(mContext,
5395 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5396 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5397 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5399 } catch (RemoteException re) {
5400 // should never happen
5401 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5404 mInjector.binderRestoreCallingIdentity(callingIdentity);
5408 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5409 Intent intent = new Intent(action);
5410 intent.setComponent(mOwners.getDeviceOwnerComponent());
5411 if (extras != null) {
5412 intent.putExtras(extras);
5414 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5417 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5418 return mOwners.getDeviceOwnerRemoteBugreportUri();
5421 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5422 String bugreportHash) {
5423 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5426 private void registerRemoteBugreportReceivers() {
5428 IntentFilter filterFinished = new IntentFilter(
5429 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5430 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5431 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5432 } catch (IntentFilter.MalformedMimeTypeException e) {
5433 // should never happen, as setting a constant
5434 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5436 IntentFilter filterConsent = new IntentFilter();
5437 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5438 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5439 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5442 private void onBugreportFinished(Intent intent) {
5443 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5444 mRemoteBugreportServiceIsActive.set(false);
5445 Uri bugreportUri = intent.getData();
5446 String bugreportUriString = null;
5447 if (bugreportUri != null) {
5448 bugreportUriString = bugreportUri.toString();
5450 String bugreportHash = intent.getStringExtra(
5451 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5452 if (mRemoteBugreportSharingAccepted.get()) {
5453 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5454 mInjector.getNotificationManager().cancel(LOG_TAG,
5455 RemoteBugreportUtils.NOTIFICATION_ID);
5457 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5458 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5459 RemoteBugreportUtils.buildNotification(mContext,
5460 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5463 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5466 private void onBugreportFailed() {
5467 mRemoteBugreportServiceIsActive.set(false);
5468 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5469 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5470 mRemoteBugreportSharingAccepted.set(false);
5471 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5472 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5473 Bundle extras = new Bundle();
5474 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5475 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5476 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5477 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5478 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5481 private void onBugreportSharingAccepted() {
5482 mRemoteBugreportSharingAccepted.set(true);
5483 String bugreportUriString = null;
5484 String bugreportHash = null;
5485 synchronized (this) {
5486 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5487 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5489 if (bugreportUriString != null) {
5490 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5491 } else if (mRemoteBugreportServiceIsActive.get()) {
5492 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5493 RemoteBugreportUtils.buildNotification(mContext,
5494 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5499 private void onBugreportSharingDeclined() {
5500 if (mRemoteBugreportServiceIsActive.get()) {
5501 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5502 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5503 mRemoteBugreportServiceIsActive.set(false);
5504 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5505 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5507 mRemoteBugreportSharingAccepted.set(false);
5508 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5509 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5512 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5513 String bugreportHash) {
5514 ParcelFileDescriptor pfd = null;
5516 if (bugreportUriString == null) {
5517 throw new FileNotFoundException();
5519 Uri bugreportUri = Uri.parse(bugreportUriString);
5520 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5522 synchronized (this) {
5523 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5524 intent.setComponent(mOwners.getDeviceOwnerComponent());
5525 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5526 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5527 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
5529 LocalServices.getService(ActivityManagerInternal.class)
5530 .grantUriPermissionFromIntent(Process.SHELL_UID,
5531 mOwners.getDeviceOwnerComponent().getPackageName(),
5532 intent, mOwners.getDeviceOwnerUserId());
5533 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5535 } catch (FileNotFoundException e) {
5536 Bundle extras = new Bundle();
5537 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5538 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5539 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5545 } catch (IOException ex) {
5548 mRemoteBugreportSharingAccepted.set(false);
5549 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5554 * Disables all device cameras according to the specified admin.
5557 public void setCameraDisabled(ComponentName who, boolean disabled) {
5561 Preconditions.checkNotNull(who, "ComponentName is null");
5562 final int userHandle = mInjector.userHandleGetCallingUserId();
5563 synchronized (this) {
5564 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5565 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5566 if (ap.disableCamera != disabled) {
5567 ap.disableCamera = disabled;
5568 saveSettingsLocked(userHandle);
5571 // Tell the user manager that the restrictions have changed.
5572 pushUserRestrictions(userHandle);
5576 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5580 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5581 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5584 private boolean getCameraDisabled(ComponentName who, int userHandle,
5585 boolean mergeDeviceOwnerRestriction) {
5589 synchronized (this) {
5591 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5592 return (admin != null) ? admin.disableCamera : false;
5594 // First, see if DO has set it. If so, it's device-wide.
5595 if (mergeDeviceOwnerRestriction) {
5596 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5597 if (deviceOwner != null && deviceOwner.disableCamera) {
5602 // Then check each device admin on the user.
5603 DevicePolicyData policy = getUserData(userHandle);
5604 // Determine whether or not the device camera is disabled for any active admins.
5605 final int N = policy.mAdminList.size();
5606 for (int i = 0; i < N; i++) {
5607 ActiveAdmin admin = policy.mAdminList.get(i);
5608 if (admin.disableCamera) {
5617 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5621 Preconditions.checkNotNull(who, "ComponentName is null");
5622 final int userHandle = mInjector.userHandleGetCallingUserId();
5623 if (isManagedProfile(userHandle)) {
5625 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5627 which = which & PROFILE_KEYGUARD_FEATURES;
5630 synchronized (this) {
5631 ActiveAdmin ap = getActiveAdminForCallerLocked(
5632 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5633 if (ap.disabledKeyguardFeatures != which) {
5634 ap.disabledKeyguardFeatures = which;
5635 saveSettingsLocked(userHandle);
5641 * Gets the disabled state for features in keyguard for the given admin,
5642 * or the aggregate of all active admins if who is null.
5645 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5649 enforceFullCrossUsersPermission(userHandle);
5650 final long ident = mInjector.binderClearCallingIdentity();
5652 synchronized (this) {
5654 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5655 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5658 final List<ActiveAdmin> admins;
5659 if (!parent && isManagedProfile(userHandle)) {
5660 // If we are being asked about a managed profile, just return keyguard features
5661 // disabled by admins in the profile.
5662 admins = getUserDataUnchecked(userHandle).mAdminList;
5664 // Otherwise return those set by admins in the user and its profiles.
5665 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5668 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5669 final int N = admins.size();
5670 for (int i = 0; i < N; i++) {
5671 ActiveAdmin admin = admins.get(i);
5672 int userId = admin.getUserHandle().getIdentifier();
5673 boolean isRequestedUser = !parent && (userId == userHandle);
5674 if (isRequestedUser || !isManagedProfile(userId)) {
5675 // If we are being asked explicitly about this user
5676 // return all disabled features even if its a managed profile.
5677 which |= admin.disabledKeyguardFeatures;
5679 // Otherwise a managed profile is only allowed to disable
5680 // some features on the parent user.
5681 which |= (admin.disabledKeyguardFeatures
5682 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5688 mInjector.binderRestoreCallingIdentity(ident);
5693 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5697 Preconditions.checkNotNull(who, "ComponentName is null");
5698 Preconditions.checkNotNull(packageList, "packageList is null");
5699 final int userHandle = UserHandle.getCallingUserId();
5700 synchronized (this) {
5701 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5702 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5703 admin.keepUninstalledPackages = packageList;
5704 saveSettingsLocked(userHandle);
5705 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5710 public List<String> getKeepUninstalledPackages(ComponentName who) {
5711 Preconditions.checkNotNull(who, "ComponentName is null");
5715 // TODO In split system user mode, allow apps on user 0 to query the list
5716 synchronized (this) {
5717 // Check if this is the device owner who is calling
5718 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5719 return getKeepUninstalledPackagesLocked();
5723 private List<String> getKeepUninstalledPackagesLocked() {
5724 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5725 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5729 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5734 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5735 throw new IllegalArgumentException("Invalid component " + admin
5736 + " for device owner");
5738 synchronized (this) {
5739 enforceCanSetDeviceOwnerLocked(userId);
5740 if (getActiveAdminUncheckedLocked(admin, userId) == null) {
5741 throw new IllegalArgumentException("Not active admin: " + admin);
5744 // Shutting down backup manager service permanently.
5745 long ident = mInjector.binderClearCallingIdentity();
5747 if (mInjector.getIBackupManager() != null) {
5748 mInjector.getIBackupManager()
5749 .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5751 } catch (RemoteException e) {
5752 throw new IllegalStateException("Failed deactivating backup service.", e);
5754 mInjector.binderRestoreCallingIdentity(ident);
5757 mOwners.setDeviceOwner(admin, ownerName, userId);
5758 mOwners.writeDeviceOwner();
5759 updateDeviceOwnerLocked();
5760 setDeviceOwnerSystemPropertyLocked();
5761 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5763 ident = mInjector.binderClearCallingIdentity();
5765 // TODO Send to system too?
5766 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5768 mInjector.binderRestoreCallingIdentity(ident);
5774 public boolean isDeviceOwner(ComponentName who, int userId) {
5775 synchronized (this) {
5776 return mOwners.hasDeviceOwner()
5777 && mOwners.getDeviceOwnerUserId() == userId
5778 && mOwners.getDeviceOwnerComponent().equals(who);
5782 public boolean isProfileOwner(ComponentName who, int userId) {
5783 final ComponentName profileOwner = getProfileOwner(userId);
5784 return who != null && who.equals(profileOwner);
5788 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5792 if (!callingUserOnly) {
5793 enforceManageUsers();
5795 synchronized (this) {
5796 if (!mOwners.hasDeviceOwner()) {
5799 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
5800 mOwners.getDeviceOwnerUserId()) {
5803 return mOwners.getDeviceOwnerComponent();
5808 public int getDeviceOwnerUserId() {
5810 return UserHandle.USER_NULL;
5812 enforceManageUsers();
5813 synchronized (this) {
5814 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
5819 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
5823 public String getDeviceOwnerName() {
5827 enforceManageUsers();
5828 synchronized (this) {
5829 if (!mOwners.hasDeviceOwner()) {
5832 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
5833 // Should setDeviceOwner/ProfileOwner still take a name?
5834 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
5835 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
5839 // Returns the active device owner or null if there is no device owner.
5841 ActiveAdmin getDeviceOwnerAdminLocked() {
5842 ComponentName component = mOwners.getDeviceOwnerComponent();
5843 if (component == null) {
5847 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
5848 final int n = policy.mAdminList.size();
5849 for (int i = 0; i < n; i++) {
5850 ActiveAdmin admin = policy.mAdminList.get(i);
5851 if (component.equals(admin.info.getComponent())) {
5855 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
5860 public void clearDeviceOwner(String packageName) {
5861 Preconditions.checkNotNull(packageName, "packageName is null");
5862 final int callingUid = mInjector.binderGetCallingUid();
5864 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
5865 UserHandle.getUserId(callingUid));
5866 if (uid != callingUid) {
5867 throw new SecurityException("Invalid packageName");
5869 } catch (NameNotFoundException e) {
5870 throw new SecurityException(e);
5872 synchronized (this) {
5873 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
5874 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
5875 if (!mOwners.hasDeviceOwner()
5876 || !deviceOwnerComponent.getPackageName().equals(packageName)
5877 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
5878 throw new SecurityException(
5879 "clearDeviceOwner can only be called by the device owner");
5881 enforceUserUnlocked(deviceOwnerUserId);
5883 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
5884 long ident = mInjector.binderClearCallingIdentity();
5886 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
5887 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
5889 mInjector.binderRestoreCallingIdentity(ident);
5894 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
5895 if (admin != null) {
5896 admin.disableCamera = false;
5897 admin.userRestrictions = null;
5898 admin.forceEphemeralUsers = false;
5899 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
5901 clearUserPoliciesLocked(userId);
5903 mOwners.clearDeviceOwner();
5904 mOwners.writeDeviceOwner();
5905 updateDeviceOwnerLocked();
5906 disableSecurityLoggingIfNotCompliant();
5908 // Reactivate backup service.
5909 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
5910 } catch (RemoteException e) {
5911 throw new IllegalStateException("Failed reactivating backup service.", e);
5916 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
5921 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
5922 throw new IllegalArgumentException("Component " + who
5923 + " not installed for userId:" + userHandle);
5925 synchronized (this) {
5926 enforceCanSetProfileOwnerLocked(userHandle);
5928 if (getActiveAdminUncheckedLocked(who, userHandle) == null) {
5929 throw new IllegalArgumentException("Not active admin: " + who);
5932 mOwners.setProfileOwner(who, ownerName, userHandle);
5933 mOwners.writeProfileOwner(userHandle);
5939 public void clearProfileOwner(ComponentName who) {
5943 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
5944 final int userId = callingUser.getIdentifier();
5945 enforceNotManagedProfile(userId, "clear profile owner");
5946 enforceUserUnlocked(userId);
5947 // Check if this is the profile owner who is calling
5948 final ActiveAdmin admin =
5949 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5950 synchronized (this) {
5951 final long ident = mInjector.binderClearCallingIdentity();
5953 clearProfileOwnerLocked(admin, userId);
5954 removeActiveAdminLocked(who, userId);
5956 mInjector.binderRestoreCallingIdentity(ident);
5961 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
5962 if (admin != null) {
5963 admin.disableCamera = false;
5964 admin.userRestrictions = null;
5966 clearUserPoliciesLocked(userId);
5967 mOwners.removeProfileOwner(userId);
5968 mOwners.writeProfileOwner(userId);
5972 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
5973 Preconditions.checkNotNull(who, "ComponentName is null");
5978 synchronized (this) {
5979 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5980 long token = mInjector.binderClearCallingIdentity();
5982 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
5984 mInjector.binderRestoreCallingIdentity(token);
5990 public CharSequence getDeviceOwnerLockScreenInfo() {
5991 return mLockPatternUtils.getDeviceOwnerInfo();
5994 private void clearUserPoliciesLocked(int userId) {
5995 // Reset some of the user-specific policies
5996 DevicePolicyData policy = getUserData(userId);
5997 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
5998 policy.mDelegatedCertInstallerPackage = null;
5999 policy.mApplicationRestrictionsManagingPackage = null;
6000 policy.mStatusBarDisabled = false;
6001 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6002 saveSettingsLocked(userId);
6005 mIPackageManager.updatePermissionFlagsForAllApps(
6006 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6007 0 /* flagValues */, userId);
6008 pushUserRestrictions(userId);
6009 } catch (RemoteException re) {
6010 // Shouldn't happen.
6015 public boolean hasUserSetupCompleted() {
6016 return hasUserSetupCompleted(UserHandle.getCallingUserId());
6019 private boolean hasUserSetupCompleted(int userHandle) {
6023 return getUserData(userHandle).mUserSetupComplete;
6027 public int getUserProvisioningState() {
6029 return DevicePolicyManager.STATE_USER_UNMANAGED;
6031 int userHandle = mInjector.userHandleGetCallingUserId();
6032 return getUserProvisioningState(userHandle);
6035 private int getUserProvisioningState(int userHandle) {
6036 return getUserData(userHandle).mUserProvisioningState;
6040 public void setUserProvisioningState(int newState, int userHandle) {
6045 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6046 && getManagedUserId(userHandle) == -1) {
6047 // No managed device, user or profile, so setting provisioning state makes no sense.
6048 throw new IllegalStateException("Not allowed to change provisioning state unless a "
6049 + "device or profile owner is set.");
6052 synchronized (this) {
6053 boolean transitionCheckNeeded = true;
6055 // Calling identity/permission checks.
6056 final int callingUid = mInjector.binderGetCallingUid();
6057 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6058 // ADB shell can only move directly from un-managed to finalized as part of directly
6059 // setting profile-owner or device-owner.
6060 if (getUserProvisioningState(userHandle) !=
6061 DevicePolicyManager.STATE_USER_UNMANAGED
6062 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6063 throw new IllegalStateException("Not allowed to change provisioning state "
6064 + "unless current provisioning state is unmanaged, and new state is "
6067 transitionCheckNeeded = false;
6069 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6070 enforceCanManageProfileAndDeviceOwners();
6073 final DevicePolicyData policyData = getUserData(userHandle);
6074 if (transitionCheckNeeded) {
6075 // Optional state transition check for non-ADB case.
6076 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6078 policyData.mUserProvisioningState = newState;
6079 saveSettingsLocked(userHandle);
6083 private void checkUserProvisioningStateTransition(int currentState, int newState) {
6084 // Valid transitions for normal use-cases.
6085 switch (currentState) {
6086 case DevicePolicyManager.STATE_USER_UNMANAGED:
6087 // Can move to any state from unmanaged (except itself as an edge case)..
6088 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6092 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6093 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6094 // Can only move to finalized from these states.
6095 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6099 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6100 // Current user has a managed-profile, but current user is not managed, so
6101 // rather than moving to finalized state, go back to unmanaged once
6102 // profile provisioning is complete.
6103 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6107 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6108 // Cannot transition out of finalized.
6112 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6113 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6114 + "from state [" + currentState + "]");
6118 public void setProfileEnabled(ComponentName who) {
6122 Preconditions.checkNotNull(who, "ComponentName is null");
6123 synchronized (this) {
6124 // Check if this is the profile owner who is calling
6125 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6126 final int userId = UserHandle.getCallingUserId();
6127 enforceManagedProfile(userId, "enable the profile");
6129 long id = mInjector.binderClearCallingIdentity();
6131 mUserManager.setUserEnabled(userId);
6132 UserInfo parent = mUserManager.getProfileParent(userId);
6133 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6134 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6135 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6136 Intent.FLAG_RECEIVER_FOREGROUND);
6137 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6139 mInjector.binderRestoreCallingIdentity(id);
6145 public void setProfileName(ComponentName who, String profileName) {
6146 Preconditions.checkNotNull(who, "ComponentName is null");
6147 int userId = UserHandle.getCallingUserId();
6148 // Check if this is the profile owner (includes device owner).
6149 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6151 long id = mInjector.binderClearCallingIdentity();
6153 mUserManager.setUserName(userId, profileName);
6155 mInjector.binderRestoreCallingIdentity(id);
6160 public ComponentName getProfileOwner(int userHandle) {
6165 synchronized (this) {
6166 return mOwners.getProfileOwnerComponent(userHandle);
6170 // Returns the active profile owner for this user or null if the current user has no
6173 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6174 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6175 if (profileOwner == null) {
6178 DevicePolicyData policy = getUserData(userHandle);
6179 final int n = policy.mAdminList.size();
6180 for (int i = 0; i < n; i++) {
6181 ActiveAdmin admin = policy.mAdminList.get(i);
6182 if (profileOwner.equals(admin.info.getComponent())) {
6190 public String getProfileOwnerName(int userHandle) {
6194 enforceManageUsers();
6195 ComponentName profileOwner = getProfileOwner(userHandle);
6196 if (profileOwner == null) {
6199 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6203 * Canonical name for a given package.
6205 private String getApplicationLabel(String packageName, int userHandle) {
6206 long token = mInjector.binderClearCallingIdentity();
6208 final Context userContext;
6210 UserHandle handle = new UserHandle(userHandle);
6211 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6212 } catch (PackageManager.NameNotFoundException nnfe) {
6213 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6216 ApplicationInfo appInfo = userContext.getApplicationInfo();
6217 CharSequence result = null;
6218 if (appInfo != null) {
6219 PackageManager pm = userContext.getPackageManager();
6220 result = pm.getApplicationLabel(appInfo);
6222 return result != null ? result.toString() : null;
6224 mInjector.binderRestoreCallingIdentity(token);
6229 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6231 * The profile owner can only be set before the user setup phase has completed,
6234 * - adb if there are not accounts.
6236 private void enforceCanSetProfileOwnerLocked(int userHandle) {
6237 UserInfo info = getUserInfo(userHandle);
6239 // User doesn't exist.
6240 throw new IllegalArgumentException(
6241 "Attempted to set profile owner for invalid userId: " + userHandle);
6243 if (info.isGuest()) {
6244 throw new IllegalStateException("Cannot set a profile owner on a guest");
6246 if (mOwners.hasProfileOwner(userHandle)) {
6247 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6248 + "is already set.");
6250 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6251 throw new IllegalStateException("Trying to set the profile owner, but the user "
6252 + "already has a device owner.");
6254 int callingUid = mInjector.binderGetCallingUid();
6255 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6256 if (hasUserSetupCompleted(userHandle) &&
6257 AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) {
6258 throw new IllegalStateException("Not allowed to set the profile owner because "
6259 + "there are already some accounts on the profile");
6263 enforceCanManageProfileAndDeviceOwners();
6264 if (hasUserSetupCompleted(userHandle) && !isCallerWithSystemUid()) {
6265 throw new IllegalStateException("Cannot set the profile owner on a user which is "
6266 + "already set-up");
6271 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6274 private void enforceCanSetDeviceOwnerLocked(int userId) {
6275 int callingUid = mInjector.binderGetCallingUid();
6276 boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6278 enforceCanManageProfileAndDeviceOwners();
6281 final int code = checkSetDeviceOwnerPreCondition(userId, isAdb);
6285 case CODE_HAS_DEVICE_OWNER:
6286 throw new IllegalStateException(
6287 "Trying to set the device owner, but device owner is already set.");
6288 case CODE_USER_HAS_PROFILE_OWNER:
6289 throw new IllegalStateException("Trying to set the device owner, but the user "
6290 + "already has a profile owner.");
6291 case CODE_USER_NOT_RUNNING:
6292 throw new IllegalStateException("User not running: " + userId);
6293 case CODE_NOT_SYSTEM_USER:
6294 throw new IllegalStateException("User is not system user");
6295 case CODE_USER_SETUP_COMPLETED:
6296 throw new IllegalStateException(
6297 "Cannot set the device owner if the device is already set-up");
6298 case CODE_NONSYSTEM_USER_EXISTS:
6299 throw new IllegalStateException("Not allowed to set the device owner because there "
6300 + "are already several users on the device");
6301 case CODE_ACCOUNTS_NOT_EMPTY:
6302 throw new IllegalStateException("Not allowed to set the device owner because there "
6303 + "are already some accounts on the device");
6305 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6309 private void enforceUserUnlocked(int userId) {
6310 // Since we're doing this operation on behalf of an app, we only
6311 // want to use the actual "unlocked" state.
6312 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6313 "User must be running and unlocked");
6316 private void enforceUserUnlocked(int userId, boolean parent) {
6318 enforceUserUnlocked(getProfileParentId(userId));
6320 enforceUserUnlocked(userId);
6324 private void enforceManageUsers() {
6325 final int callingUid = mInjector.binderGetCallingUid();
6326 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6327 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6331 private void enforceFullCrossUsersPermission(int userHandle) {
6332 enforceSystemUserOrPermission(userHandle,
6333 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6336 private void enforceCrossUsersPermission(int userHandle) {
6337 enforceSystemUserOrPermission(userHandle,
6338 android.Manifest.permission.INTERACT_ACROSS_USERS);
6341 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6342 if (userHandle < 0) {
6343 throw new IllegalArgumentException("Invalid userId " + userHandle);
6345 final int callingUid = mInjector.binderGetCallingUid();
6346 if (userHandle == UserHandle.getUserId(callingUid)) {
6349 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6350 mContext.enforceCallingOrSelfPermission(permission,
6351 "Must be system or have " + permission + " permission");
6355 private void enforceManagedProfile(int userHandle, String message) {
6356 if(!isManagedProfile(userHandle)) {
6357 throw new SecurityException("You can not " + message + " outside a managed profile.");
6361 private void enforceNotManagedProfile(int userHandle, String message) {
6362 if(isManagedProfile(userHandle)) {
6363 throw new SecurityException("You can not " + message + " for a managed profile.");
6367 private void ensureCallerPackage(@Nullable String packageName) {
6368 if (packageName == null) {
6369 Preconditions.checkState(isCallerWithSystemUid(),
6370 "Only caller can omit package name");
6372 final int callingUid = mInjector.binderGetCallingUid();
6373 final int userId = mInjector.userHandleGetCallingUserId();
6375 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6376 packageName, 0, userId);
6377 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6378 } catch (RemoteException e) {
6384 private boolean isCallerWithSystemUid() {
6385 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6388 private int getProfileParentId(int userHandle) {
6389 final long ident = mInjector.binderClearCallingIdentity();
6391 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6392 return parentUser != null ? parentUser.id : userHandle;
6394 mInjector.binderRestoreCallingIdentity(ident);
6398 private int getCredentialOwner(int userHandle, boolean parent) {
6399 final long ident = mInjector.binderClearCallingIdentity();
6402 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6403 if (parentProfile != null) {
6404 userHandle = parentProfile.id;
6407 return mUserManager.getCredentialOwnerProfile(userHandle);
6409 mInjector.binderRestoreCallingIdentity(ident);
6413 private boolean isManagedProfile(int userHandle) {
6414 return getUserInfo(userHandle).isManagedProfile();
6417 private void enableIfNecessary(String packageName, int userId) {
6419 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6420 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6422 if (ai.enabledSetting
6423 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6424 mIPackageManager.setApplicationEnabledSetting(packageName,
6425 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6426 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6428 } catch (RemoteException e) {
6433 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6434 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6435 != PackageManager.PERMISSION_GRANTED) {
6437 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6438 + mInjector.binderGetCallingPid()
6439 + ", uid=" + mInjector.binderGetCallingUid());
6443 synchronized (this) {
6444 pw.println("Current Device Policy Manager state:");
6445 mOwners.dump(" ", pw);
6446 int userCount = mUserData.size();
6447 for (int u = 0; u < userCount; u++) {
6448 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6450 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6451 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6452 final int N = policy.mAdminList.size();
6453 for (int i=0; i<N; i++) {
6454 ActiveAdmin ap = policy.mAdminList.get(i);
6456 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6461 if (!policy.mRemovingAdmins.isEmpty()) {
6462 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6463 + policy.mRemovingAdmins);
6467 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6470 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6474 private String getEncryptionStatusName(int encryptionStatus) {
6475 switch (encryptionStatus) {
6476 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6478 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6479 return "block default key";
6480 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6482 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6484 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6485 return "unsupported";
6486 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6487 return "activating";
6494 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6495 ComponentName activity) {
6496 Preconditions.checkNotNull(who, "ComponentName is null");
6497 final int userHandle = UserHandle.getCallingUserId();
6498 synchronized (this) {
6499 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6501 long id = mInjector.binderClearCallingIdentity();
6503 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6504 } catch (RemoteException re) {
6507 mInjector.binderRestoreCallingIdentity(id);
6513 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6514 Preconditions.checkNotNull(who, "ComponentName is null");
6515 final int userHandle = UserHandle.getCallingUserId();
6516 synchronized (this) {
6517 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6519 long id = mInjector.binderClearCallingIdentity();
6521 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6522 } catch (RemoteException re) {
6525 mInjector.binderRestoreCallingIdentity(id);
6531 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6532 String packageName) {
6533 Preconditions.checkNotNull(admin, "ComponentName is null");
6535 final int userHandle = mInjector.userHandleGetCallingUserId();
6536 synchronized (this) {
6537 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6538 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6541 DevicePolicyData policy = getUserData(userHandle);
6542 policy.mApplicationRestrictionsManagingPackage = packageName;
6543 saveSettingsLocked(userHandle);
6549 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6550 Preconditions.checkNotNull(admin, "ComponentName is null");
6552 final int userHandle = mInjector.userHandleGetCallingUserId();
6553 synchronized (this) {
6554 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6555 DevicePolicyData policy = getUserData(userHandle);
6556 return policy.mApplicationRestrictionsManagingPackage;
6561 public boolean isCallerApplicationRestrictionsManagingPackage() {
6562 final int callingUid = mInjector.binderGetCallingUid();
6563 final int userHandle = UserHandle.getUserId(callingUid);
6564 synchronized (this) {
6565 final DevicePolicyData policy = getUserData(userHandle);
6566 if (policy.mApplicationRestrictionsManagingPackage == null) {
6571 int uid = mContext.getPackageManager().getPackageUidAsUser(
6572 policy.mApplicationRestrictionsManagingPackage, userHandle);
6573 return uid == callingUid;
6574 } catch (NameNotFoundException e) {
6580 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6582 synchronized (this) {
6583 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6585 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6586 throw new SecurityException(
6587 "No admin component given, and caller cannot manage application restrictions "
6588 + "for other apps.");
6593 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6594 enforceCanManageApplicationRestrictions(who);
6596 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6597 final long id = mInjector.binderClearCallingIdentity();
6599 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6601 mInjector.binderRestoreCallingIdentity(id);
6606 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6607 PersistableBundle args, boolean parent) {
6611 Preconditions.checkNotNull(admin, "admin is null");
6612 Preconditions.checkNotNull(agent, "agent is null");
6613 final int userHandle = UserHandle.getCallingUserId();
6614 synchronized (this) {
6615 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6616 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6617 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6618 saveSettingsLocked(userHandle);
6623 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6624 ComponentName agent, int userHandle, boolean parent) {
6628 Preconditions.checkNotNull(agent, "agent null");
6629 enforceFullCrossUsersPermission(userHandle);
6631 synchronized (this) {
6632 final String componentName = agent.flattenToString();
6633 if (admin != null) {
6634 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6635 if (ap == null) return null;
6636 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6637 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6638 List<PersistableBundle> result = new ArrayList<>();
6639 result.add(trustAgentInfo.options);
6643 // Return strictest policy for this user and profiles that are visible from this user.
6644 List<PersistableBundle> result = null;
6645 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6646 // of the options. If any admin doesn't have options, discard options for the rest
6648 List<ActiveAdmin> admins =
6649 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6650 boolean allAdminsHaveOptions = true;
6651 final int N = admins.size();
6652 for (int i = 0; i < N; i++) {
6653 final ActiveAdmin active = admins.get(i);
6655 final boolean disablesTrust = (active.disabledKeyguardFeatures
6656 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6657 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6658 if (info != null && info.options != null && !info.options.isEmpty()) {
6659 if (disablesTrust) {
6660 if (result == null) {
6661 result = new ArrayList<>();
6663 result.add(info.options);
6665 Log.w(LOG_TAG, "Ignoring admin " + active.info
6666 + " because it has trust options but doesn't declare "
6667 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6669 } else if (disablesTrust) {
6670 allAdminsHaveOptions = false;
6674 return allAdminsHaveOptions ? result : null;
6679 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6680 Preconditions.checkNotNull(who, "ComponentName is null");
6681 synchronized (this) {
6682 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6684 int userHandle = UserHandle.getCallingUserId();
6685 DevicePolicyData userData = getUserData(userHandle);
6686 userData.mRestrictionsProvider = permissionProvider;
6687 saveSettingsLocked(userHandle);
6692 public ComponentName getRestrictionsProvider(int userHandle) {
6693 synchronized (this) {
6694 if (!isCallerWithSystemUid()) {
6695 throw new SecurityException("Only the system can query the permission provider");
6697 DevicePolicyData userData = getUserData(userHandle);
6698 return userData != null ? userData.mRestrictionsProvider : null;
6703 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6704 Preconditions.checkNotNull(who, "ComponentName is null");
6705 int callingUserId = UserHandle.getCallingUserId();
6706 synchronized (this) {
6707 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6709 long id = mInjector.binderClearCallingIdentity();
6711 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6712 if (parent == null) {
6713 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6717 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6718 mIPackageManager.addCrossProfileIntentFilter(
6719 filter, who.getPackageName(), callingUserId, parent.id, 0);
6721 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6722 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6723 parent.id, callingUserId, 0);
6725 } catch (RemoteException re) {
6728 mInjector.binderRestoreCallingIdentity(id);
6734 public void clearCrossProfileIntentFilters(ComponentName who) {
6735 Preconditions.checkNotNull(who, "ComponentName is null");
6736 int callingUserId = UserHandle.getCallingUserId();
6737 synchronized (this) {
6738 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6739 long id = mInjector.binderClearCallingIdentity();
6741 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6742 if (parent == null) {
6743 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6747 // Removing those that go from the managed profile to the parent.
6748 mIPackageManager.clearCrossProfileIntentFilters(
6749 callingUserId, who.getPackageName());
6750 // And those that go from the parent to the managed profile.
6751 // If we want to support multiple managed profiles, we will have to only remove
6752 // those that have callingUserId as their target.
6753 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6754 } catch (RemoteException re) {
6757 mInjector.binderRestoreCallingIdentity(id);
6763 * @return true if all packages in enabledPackages are either in the list
6764 * permittedList or are a system app.
6766 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6767 List<String> permittedList, int userIdToCheck) {
6768 long id = mInjector.binderClearCallingIdentity();
6770 // If we have an enabled packages list for a managed profile the packages
6771 // we should check are installed for the parent user.
6772 UserInfo user = getUserInfo(userIdToCheck);
6773 if (user.isManagedProfile()) {
6774 userIdToCheck = user.profileGroupId;
6777 for (String enabledPackage : enabledPackages) {
6778 boolean systemService = false;
6780 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
6781 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
6782 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6783 } catch (RemoteException e) {
6784 Log.i(LOG_TAG, "Can't talk to package managed", e);
6786 if (!systemService && !permittedList.contains(enabledPackage)) {
6791 mInjector.binderRestoreCallingIdentity(id);
6796 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
6797 // Not using AccessibilityManager.getInstance because that guesses
6798 // at the user you require based on callingUid and caches for a given
6800 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
6801 IAccessibilityManager service = iBinder == null
6802 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
6803 return new AccessibilityManager(mContext, service, userId);
6807 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
6811 Preconditions.checkNotNull(who, "ComponentName is null");
6813 if (packageList != null) {
6814 int userId = UserHandle.getCallingUserId();
6815 List<AccessibilityServiceInfo> enabledServices = null;
6816 long id = mInjector.binderClearCallingIdentity();
6818 UserInfo user = getUserInfo(userId);
6819 if (user.isManagedProfile()) {
6820 userId = user.profileGroupId;
6822 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
6823 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
6824 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
6826 mInjector.binderRestoreCallingIdentity(id);
6829 if (enabledServices != null) {
6830 List<String> enabledPackages = new ArrayList<String>();
6831 for (AccessibilityServiceInfo service : enabledServices) {
6832 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
6834 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6836 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
6837 + "because it contains already enabled accesibility services.");
6843 synchronized (this) {
6844 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6845 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6846 admin.permittedAccessiblityServices = packageList;
6847 saveSettingsLocked(UserHandle.getCallingUserId());
6853 public List getPermittedAccessibilityServices(ComponentName who) {
6857 Preconditions.checkNotNull(who, "ComponentName is null");
6859 synchronized (this) {
6860 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6861 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6862 return admin.permittedAccessiblityServices;
6867 public List getPermittedAccessibilityServicesForUser(int userId) {
6871 enforceManageUsers();
6872 synchronized (this) {
6873 List<String> result = null;
6874 // If we have multiple profiles we return the intersection of the
6875 // permitted lists. This can happen in cases where we have a device
6876 // and profile owner.
6877 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
6878 for (int profileId : profileIds) {
6879 // Just loop though all admins, only device or profiles
6880 // owners can have permitted lists set.
6881 DevicePolicyData policy = getUserDataUnchecked(profileId);
6882 final int N = policy.mAdminList.size();
6883 for (int j = 0; j < N; j++) {
6884 ActiveAdmin admin = policy.mAdminList.get(j);
6885 List<String> fromAdmin = admin.permittedAccessiblityServices;
6886 if (fromAdmin != null) {
6887 if (result == null) {
6888 result = new ArrayList<>(fromAdmin);
6890 result.retainAll(fromAdmin);
6896 // If we have a permitted list add all system accessibility services.
6897 if (result != null) {
6898 long id = mInjector.binderClearCallingIdentity();
6900 UserInfo user = getUserInfo(userId);
6901 if (user.isManagedProfile()) {
6902 userId = user.profileGroupId;
6904 AccessibilityManager accessibilityManager =
6905 getAccessibilityManagerForUser(userId);
6906 List<AccessibilityServiceInfo> installedServices =
6907 accessibilityManager.getInstalledAccessibilityServiceList();
6909 if (installedServices != null) {
6910 for (AccessibilityServiceInfo service : installedServices) {
6911 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
6912 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
6913 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6914 result.add(serviceInfo.packageName);
6919 mInjector.binderRestoreCallingIdentity(id);
6928 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
6933 Preconditions.checkNotNull(who, "ComponentName is null");
6934 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
6935 if (!isCallerWithSystemUid()){
6936 throw new SecurityException(
6937 "Only the system can query if an accessibility service is disabled by admin");
6939 synchronized (this) {
6940 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6941 if (admin == null) {
6944 if (admin.permittedAccessiblityServices == null) {
6947 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
6948 admin.permittedAccessiblityServices, userHandle);
6952 private boolean checkCallerIsCurrentUserOrProfile() {
6953 int callingUserId = UserHandle.getCallingUserId();
6954 long token = mInjector.binderClearCallingIdentity();
6956 UserInfo currentUser;
6957 UserInfo callingUser = getUserInfo(callingUserId);
6959 currentUser = mInjector.getIActivityManager().getCurrentUser();
6960 } catch (RemoteException e) {
6961 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
6965 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
6966 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
6967 + "of a user that isn't the foreground user.");
6970 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
6971 Slog.e(LOG_TAG, "Cannot set permitted input methods "
6972 + "of a user that isn't the foreground user.");
6976 mInjector.binderRestoreCallingIdentity(token);
6982 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
6986 Preconditions.checkNotNull(who, "ComponentName is null");
6988 // TODO When InputMethodManager supports per user calls remove
6989 // this restriction.
6990 if (!checkCallerIsCurrentUserOrProfile()) {
6994 if (packageList != null) {
6995 // InputMethodManager fetches input methods for current user.
6996 // So this can only be set when calling user is the current user
6997 // or parent is current user in case of managed profiles.
6998 InputMethodManager inputMethodManager =
6999 mContext.getSystemService(InputMethodManager.class);
7000 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7002 if (enabledImes != null) {
7003 List<String> enabledPackages = new ArrayList<String>();
7004 for (InputMethodInfo ime : enabledImes) {
7005 enabledPackages.add(ime.getPackageName());
7007 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7008 mInjector.binderGetCallingUserHandle().getIdentifier())) {
7009 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7010 + "because it contains already enabled input method.");
7016 synchronized (this) {
7017 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7018 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7019 admin.permittedInputMethods = packageList;
7020 saveSettingsLocked(UserHandle.getCallingUserId());
7026 public List getPermittedInputMethods(ComponentName who) {
7030 Preconditions.checkNotNull(who, "ComponentName is null");
7032 synchronized (this) {
7033 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7034 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7035 return admin.permittedInputMethods;
7040 public List getPermittedInputMethodsForCurrentUser() {
7041 UserInfo currentUser;
7043 currentUser = mInjector.getIActivityManager().getCurrentUser();
7044 } catch (RemoteException e) {
7045 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7046 // Activity managed is dead, just allow all IMEs
7050 int userId = currentUser.id;
7051 synchronized (this) {
7052 List<String> result = null;
7053 // If we have multiple profiles we return the intersection of the
7054 // permitted lists. This can happen in cases where we have a device
7055 // and profile owner.
7056 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7057 for (int profileId : profileIds) {
7058 // Just loop though all admins, only device or profiles
7059 // owners can have permitted lists set.
7060 DevicePolicyData policy = getUserDataUnchecked(profileId);
7061 final int N = policy.mAdminList.size();
7062 for (int j = 0; j < N; j++) {
7063 ActiveAdmin admin = policy.mAdminList.get(j);
7064 List<String> fromAdmin = admin.permittedInputMethods;
7065 if (fromAdmin != null) {
7066 if (result == null) {
7067 result = new ArrayList<String>(fromAdmin);
7069 result.retainAll(fromAdmin);
7075 // If we have a permitted list add all system input methods.
7076 if (result != null) {
7077 InputMethodManager inputMethodManager =
7078 mContext.getSystemService(InputMethodManager.class);
7079 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7080 long id = mInjector.binderClearCallingIdentity();
7083 for (InputMethodInfo ime : imes) {
7084 ServiceInfo serviceInfo = ime.getServiceInfo();
7085 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7086 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7087 result.add(serviceInfo.packageName);
7092 mInjector.binderRestoreCallingIdentity(id);
7100 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7105 Preconditions.checkNotNull(who, "ComponentName is null");
7106 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7107 if (!isCallerWithSystemUid()) {
7108 throw new SecurityException(
7109 "Only the system can query if an input method is disabled by admin");
7111 synchronized (this) {
7112 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7113 if (admin == null) {
7116 if (admin.permittedInputMethods == null) {
7119 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7120 admin.permittedInputMethods, userHandle);
7124 private void sendAdminEnabledBroadcastLocked(int userHandle) {
7125 DevicePolicyData policyData = getUserData(userHandle);
7126 if (policyData.mAdminBroadcastPending) {
7127 // Send the initialization data to profile owner and delete the data
7128 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7129 if (admin != null) {
7130 PersistableBundle initBundle = policyData.mInitBundle;
7131 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7132 initBundle == null ? null : new Bundle(initBundle), null);
7134 policyData.mInitBundle = null;
7135 policyData.mAdminBroadcastPending = false;
7136 saveSettingsLocked(userHandle);
7141 public UserHandle createAndManageUser(ComponentName admin, String name,
7142 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7143 Preconditions.checkNotNull(admin, "admin is null");
7144 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7145 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7146 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7147 + admin + " are not in the same package");
7149 // Only allow the system user to use this method
7150 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7151 throw new SecurityException("createAndManageUser was called from non-system user");
7153 if (!mInjector.userManagerIsSplitSystemUser()
7154 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7155 throw new IllegalArgumentException(
7156 "Ephemeral users are only supported on systems with a split system user.");
7159 UserHandle user = null;
7160 synchronized (this) {
7161 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7163 final long id = mInjector.binderClearCallingIdentity();
7165 int userInfoFlags = 0;
7166 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7167 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7169 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7171 if (userInfo != null) {
7172 user = userInfo.getUserHandle();
7175 mInjector.binderRestoreCallingIdentity(id);
7182 final long id = mInjector.binderClearCallingIdentity();
7184 final String adminPkg = admin.getPackageName();
7186 final int userHandle = user.getIdentifier();
7188 // Install the profile owner if not present.
7189 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7190 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7192 } catch (RemoteException e) {
7193 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7194 + "removing created user", e);
7195 mUserManager.removeUser(user.getIdentifier());
7199 setActiveAdmin(profileOwner, true, userHandle);
7200 // User is not started yet, the broadcast by setActiveAdmin will not be received.
7201 // So we store adminExtras for broadcasting when the user starts for first time.
7202 synchronized(this) {
7203 DevicePolicyData policyData = getUserData(userHandle);
7204 policyData.mInitBundle = adminExtras;
7205 policyData.mAdminBroadcastPending = true;
7206 saveSettingsLocked(userHandle);
7208 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7209 setProfileOwner(profileOwner, ownerName, userHandle);
7211 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7212 Settings.Secure.putIntForUser(mContext.getContentResolver(),
7213 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7218 mInjector.binderRestoreCallingIdentity(id);
7223 public boolean removeUser(ComponentName who, UserHandle userHandle) {
7224 Preconditions.checkNotNull(who, "ComponentName is null");
7225 synchronized (this) {
7226 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7228 long id = mInjector.binderClearCallingIdentity();
7230 return mUserManager.removeUser(userHandle.getIdentifier());
7232 mInjector.binderRestoreCallingIdentity(id);
7238 public boolean switchUser(ComponentName who, UserHandle userHandle) {
7239 Preconditions.checkNotNull(who, "ComponentName is null");
7240 synchronized (this) {
7241 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7243 long id = mInjector.binderClearCallingIdentity();
7245 int userId = UserHandle.USER_SYSTEM;
7246 if (userHandle != null) {
7247 userId = userHandle.getIdentifier();
7249 return mInjector.getIActivityManager().switchUser(userId);
7250 } catch (RemoteException e) {
7251 Log.e(LOG_TAG, "Couldn't switch user", e);
7254 mInjector.binderRestoreCallingIdentity(id);
7260 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7261 enforceCanManageApplicationRestrictions(who);
7263 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7264 final long id = mInjector.binderClearCallingIdentity();
7266 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7267 // if no restrictions were saved, mUserManager.getApplicationRestrictions
7268 // returns null, but DPM method should return an empty Bundle as per JavaDoc
7269 return bundle != null ? bundle : Bundle.EMPTY;
7271 mInjector.binderRestoreCallingIdentity(id);
7276 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7277 boolean suspended) {
7278 Preconditions.checkNotNull(who, "ComponentName is null");
7279 int callingUserId = UserHandle.getCallingUserId();
7280 synchronized (this) {
7281 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7283 long id = mInjector.binderClearCallingIdentity();
7285 return mIPackageManager.setPackagesSuspendedAsUser(
7286 packageNames, suspended, callingUserId);
7287 } catch (RemoteException re) {
7288 // Shouldn't happen.
7289 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7291 mInjector.binderRestoreCallingIdentity(id);
7293 return packageNames;
7298 public boolean isPackageSuspended(ComponentName who, String packageName) {
7299 Preconditions.checkNotNull(who, "ComponentName is null");
7300 int callingUserId = UserHandle.getCallingUserId();
7301 synchronized (this) {
7302 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7304 long id = mInjector.binderClearCallingIdentity();
7306 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7307 } catch (RemoteException re) {
7308 // Shouldn't happen.
7309 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7311 mInjector.binderRestoreCallingIdentity(id);
7318 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7319 Preconditions.checkNotNull(who, "ComponentName is null");
7320 if (!UserRestrictionsUtils.isValidRestriction(key)) {
7324 final int userHandle = mInjector.userHandleGetCallingUserId();
7325 synchronized (this) {
7326 ActiveAdmin activeAdmin =
7327 getActiveAdminForCallerLocked(who,
7328 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7329 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7330 if (isDeviceOwner) {
7331 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7332 throw new SecurityException("Device owner cannot set user restriction " + key);
7334 } else { // profile owner
7335 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7336 throw new SecurityException("Profile owner cannot set user restriction " + key);
7340 // Save the restriction to ActiveAdmin.
7341 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7342 saveSettingsLocked(userHandle);
7344 pushUserRestrictions(userHandle);
7346 sendChangedNotification(userHandle);
7350 private void pushUserRestrictions(int userId) {
7351 synchronized (this) {
7352 final Bundle global;
7353 final Bundle local = new Bundle();
7354 if (mOwners.isDeviceOwnerUserId(userId)) {
7355 global = new Bundle();
7357 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7358 if (deviceOwner == null) {
7359 return; // Shouldn't happen.
7362 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7364 // DO can disable camera globally.
7365 if (deviceOwner.disableCamera) {
7366 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7371 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7372 if (profileOwner != null) {
7373 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7376 // Also merge in *local* camera restriction.
7377 if (getCameraDisabled(/* who= */ null,
7378 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7379 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7381 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7386 public Bundle getUserRestrictions(ComponentName who) {
7390 Preconditions.checkNotNull(who, "ComponentName is null");
7391 synchronized (this) {
7392 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7393 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7394 return activeAdmin.userRestrictions;
7399 public boolean setApplicationHidden(ComponentName who, String packageName,
7401 Preconditions.checkNotNull(who, "ComponentName is null");
7402 int callingUserId = UserHandle.getCallingUserId();
7403 synchronized (this) {
7404 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7406 long id = mInjector.binderClearCallingIdentity();
7408 return mIPackageManager.setApplicationHiddenSettingAsUser(
7409 packageName, hidden, callingUserId);
7410 } catch (RemoteException re) {
7412 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7414 mInjector.binderRestoreCallingIdentity(id);
7421 public boolean isApplicationHidden(ComponentName who, String packageName) {
7422 Preconditions.checkNotNull(who, "ComponentName is null");
7423 int callingUserId = UserHandle.getCallingUserId();
7424 synchronized (this) {
7425 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7427 long id = mInjector.binderClearCallingIdentity();
7429 return mIPackageManager.getApplicationHiddenSettingAsUser(
7430 packageName, callingUserId);
7431 } catch (RemoteException re) {
7433 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7435 mInjector.binderRestoreCallingIdentity(id);
7442 public void enableSystemApp(ComponentName who, String packageName) {
7443 Preconditions.checkNotNull(who, "ComponentName is null");
7444 synchronized (this) {
7445 // This API can only be called by an active device admin,
7446 // so try to retrieve it to check that the caller is one.
7447 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7449 int userId = UserHandle.getCallingUserId();
7450 long id = mInjector.binderClearCallingIdentity();
7454 Slog.v(LOG_TAG, "installing " + packageName + " for "
7458 int parentUserId = getProfileParentId(userId);
7459 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7460 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7464 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7466 } catch (RemoteException re) {
7468 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7470 mInjector.binderRestoreCallingIdentity(id);
7476 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7477 Preconditions.checkNotNull(who, "ComponentName is null");
7478 synchronized (this) {
7479 // This API can only be called by an active device admin,
7480 // so try to retrieve it to check that the caller is one.
7481 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7483 int userId = UserHandle.getCallingUserId();
7484 long id = mInjector.binderClearCallingIdentity();
7487 int parentUserId = getProfileParentId(userId);
7488 List<ResolveInfo> activitiesToEnable = mIPackageManager
7489 .queryIntentActivities(intent,
7490 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7491 PackageManager.MATCH_DIRECT_BOOT_AWARE
7492 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7497 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7499 int numberOfAppsInstalled = 0;
7500 if (activitiesToEnable != null) {
7501 for (ResolveInfo info : activitiesToEnable) {
7502 if (info.activityInfo != null) {
7503 String packageName = info.activityInfo.packageName;
7504 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7505 numberOfAppsInstalled++;
7506 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7508 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7514 return numberOfAppsInstalled;
7515 } catch (RemoteException e) {
7517 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7520 mInjector.binderRestoreCallingIdentity(id);
7525 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7526 throws RemoteException {
7527 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7529 if (appInfo == null) {
7530 throw new IllegalArgumentException("The application " + packageName +
7531 " is not present on this device");
7533 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7537 public void setAccountManagementDisabled(ComponentName who, String accountType,
7542 Preconditions.checkNotNull(who, "ComponentName is null");
7543 synchronized (this) {
7544 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7545 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7547 ap.accountTypesWithManagementDisabled.add(accountType);
7549 ap.accountTypesWithManagementDisabled.remove(accountType);
7551 saveSettingsLocked(UserHandle.getCallingUserId());
7556 public String[] getAccountTypesWithManagementDisabled() {
7557 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7561 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7562 enforceFullCrossUsersPermission(userId);
7566 synchronized (this) {
7567 DevicePolicyData policy = getUserData(userId);
7568 final int N = policy.mAdminList.size();
7569 ArraySet<String> resultSet = new ArraySet<>();
7570 for (int i = 0; i < N; i++) {
7571 ActiveAdmin admin = policy.mAdminList.get(i);
7572 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7574 return resultSet.toArray(new String[resultSet.size()]);
7579 public void setUninstallBlocked(ComponentName who, String packageName,
7580 boolean uninstallBlocked) {
7581 Preconditions.checkNotNull(who, "ComponentName is null");
7582 final int userId = UserHandle.getCallingUserId();
7583 synchronized (this) {
7584 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7586 long id = mInjector.binderClearCallingIdentity();
7588 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7589 } catch (RemoteException re) {
7590 // Shouldn't happen.
7591 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7593 mInjector.binderRestoreCallingIdentity(id);
7599 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7600 // This function should return true if and only if the package is blocked by
7601 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7602 // when the package is a system app, or when it is an active device admin.
7603 final int userId = UserHandle.getCallingUserId();
7605 synchronized (this) {
7607 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7610 long id = mInjector.binderClearCallingIdentity();
7612 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7613 } catch (RemoteException re) {
7614 // Shouldn't happen.
7615 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7617 mInjector.binderRestoreCallingIdentity(id);
7624 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7628 Preconditions.checkNotNull(who, "ComponentName is null");
7629 synchronized (this) {
7630 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7631 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7632 if (admin.disableCallerId != disabled) {
7633 admin.disableCallerId = disabled;
7634 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7640 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7644 Preconditions.checkNotNull(who, "ComponentName is null");
7645 synchronized (this) {
7646 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7647 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7648 return admin.disableCallerId;
7653 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7654 enforceCrossUsersPermission(userId);
7655 synchronized (this) {
7656 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7657 return (admin != null) ? admin.disableCallerId : false;
7662 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7666 Preconditions.checkNotNull(who, "ComponentName is null");
7667 synchronized (this) {
7668 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7669 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7670 if (admin.disableContactsSearch != disabled) {
7671 admin.disableContactsSearch = disabled;
7672 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7678 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7682 Preconditions.checkNotNull(who, "ComponentName is null");
7683 synchronized (this) {
7684 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7685 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7686 return admin.disableContactsSearch;
7691 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7692 enforceCrossUsersPermission(userId);
7693 synchronized (this) {
7694 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7695 return (admin != null) ? admin.disableContactsSearch : false;
7700 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7701 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7702 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7703 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7704 final int callingUserId = UserHandle.getCallingUserId();
7706 final long ident = mInjector.binderClearCallingIdentity();
7708 synchronized (this) {
7709 final int managedUserId = getManagedUserId(callingUserId);
7710 if (managedUserId < 0) {
7713 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7716 "Cross-profile contacts access disabled for user " + managedUserId);
7720 ContactsInternal.startQuickContactWithErrorToastForUser(
7721 mContext, intent, new UserHandle(managedUserId));
7724 mInjector.binderRestoreCallingIdentity(ident);
7729 * @return true if cross-profile QuickContact is disabled
7731 private boolean isCrossProfileQuickContactDisabled(int userId) {
7732 return getCrossProfileCallerIdDisabledForUser(userId)
7733 && getCrossProfileContactsSearchDisabledForUser(userId);
7737 * @return the user ID of the managed user that is linked to the current user, if any.
7740 public int getManagedUserId(int callingUserId) {
7742 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7745 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7746 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7747 continue; // Caller user self, or not a managed profile. Skip.
7750 Log.v(LOG_TAG, "Managed user=" + ui.id);
7755 Log.v(LOG_TAG, "Managed user not found.");
7761 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7765 Preconditions.checkNotNull(who, "ComponentName is null");
7766 synchronized (this) {
7767 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7768 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7769 if (admin.disableBluetoothContactSharing != disabled) {
7770 admin.disableBluetoothContactSharing = disabled;
7771 saveSettingsLocked(UserHandle.getCallingUserId());
7777 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
7781 Preconditions.checkNotNull(who, "ComponentName is null");
7782 synchronized (this) {
7783 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7784 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7785 return admin.disableBluetoothContactSharing;
7790 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
7791 // TODO: Should there be a check to make sure this relationship is
7792 // within a profile group?
7793 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
7794 synchronized (this) {
7795 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7796 return (admin != null) ? admin.disableBluetoothContactSharing : false;
7801 * Sets which packages may enter lock task mode.
7803 * <p>This function can only be called by the device owner or alternatively by the profile owner
7804 * in case the user is affiliated.
7806 * @param packages The list of packages allowed to enter lock task mode.
7809 public void setLockTaskPackages(ComponentName who, String[] packages)
7810 throws SecurityException {
7811 Preconditions.checkNotNull(who, "ComponentName is null");
7812 synchronized (this) {
7813 ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
7814 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
7815 ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
7816 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
7817 if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
7818 int userHandle = mInjector.userHandleGetCallingUserId();
7819 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
7821 throw new SecurityException("Admin " + who +
7822 " is neither the device owner or affiliated user's profile owner.");
7827 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
7828 DevicePolicyData policy = getUserData(userHandle);
7829 policy.mLockTaskPackages = packages;
7831 // Store the settings persistently.
7832 saveSettingsLocked(userHandle);
7833 updateLockTaskPackagesLocked(packages, userHandle);
7837 * This function returns the list of components allowed to start the task lock mode.
7840 public String[] getLockTaskPackages(ComponentName who) {
7841 Preconditions.checkNotNull(who, "ComponentName is null");
7842 synchronized (this) {
7843 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7844 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
7845 final List<String> packages = getLockTaskPackagesLocked(userHandle);
7846 return packages.toArray(new String[packages.size()]);
7850 private List<String> getLockTaskPackagesLocked(int userHandle) {
7851 final DevicePolicyData policy = getUserData(userHandle);
7852 return policy.mLockTaskPackages;
7856 * This function lets the caller know whether the given package is allowed to start the
7858 * @param pkg The package to check
7861 public boolean isLockTaskPermitted(String pkg) {
7862 // Get current user's devicepolicy
7863 int uid = mInjector.binderGetCallingUid();
7864 int userHandle = UserHandle.getUserId(uid);
7865 DevicePolicyData policy = getUserData(userHandle);
7866 synchronized (this) {
7867 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
7868 String lockTaskPackage = policy.mLockTaskPackages.get(i);
7870 // If the given package equals one of the packages stored our list,
7871 // we allow this package to start lock task mode.
7872 if (lockTaskPackage.equals(pkg)) {
7881 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
7882 if (!isCallerWithSystemUid()) {
7883 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
7885 synchronized (this) {
7886 final DevicePolicyData policy = getUserData(userHandle);
7887 Bundle adminExtras = new Bundle();
7888 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
7889 for (ActiveAdmin admin : policy.mAdminList) {
7890 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
7891 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
7892 if (ownsDevice || ownsProfile) {
7894 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
7897 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
7905 public void setGlobalSetting(ComponentName who, String setting, String value) {
7906 Preconditions.checkNotNull(who, "ComponentName is null");
7908 synchronized (this) {
7909 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7911 // Some settings are no supported any more. However we do not want to throw a
7912 // SecurityException to avoid breaking apps.
7913 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
7914 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
7918 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
7919 throw new SecurityException(String.format(
7920 "Permission denial: device owners cannot update %1$s", setting));
7923 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
7924 // ignore if it contradicts an existing policy
7925 long timeMs = getMaximumTimeToLock(
7926 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
7927 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
7932 long id = mInjector.binderClearCallingIdentity();
7934 mInjector.settingsGlobalPutString(setting, value);
7936 mInjector.binderRestoreCallingIdentity(id);
7942 public void setSecureSetting(ComponentName who, String setting, String value) {
7943 Preconditions.checkNotNull(who, "ComponentName is null");
7944 int callingUserId = mInjector.userHandleGetCallingUserId();
7946 synchronized (this) {
7947 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7949 if (isDeviceOwner(who, callingUserId)) {
7950 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
7951 throw new SecurityException(String.format(
7952 "Permission denial: Device owners cannot update %1$s", setting));
7954 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
7955 throw new SecurityException(String.format(
7956 "Permission denial: Profile owners cannot update %1$s", setting));
7959 long id = mInjector.binderClearCallingIdentity();
7961 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
7963 mInjector.binderRestoreCallingIdentity(id);
7969 public void setMasterVolumeMuted(ComponentName who, boolean on) {
7970 Preconditions.checkNotNull(who, "ComponentName is null");
7971 synchronized (this) {
7972 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7973 int userId = UserHandle.getCallingUserId();
7974 long identity = mInjector.binderClearCallingIdentity();
7976 IAudioService iAudioService = IAudioService.Stub.asInterface(
7977 ServiceManager.getService(Context.AUDIO_SERVICE));
7978 iAudioService.setMasterMute(on, 0, mContext.getPackageName(), userId);
7979 } catch (RemoteException re) {
7980 Slog.e(LOG_TAG, "Failed to setMasterMute", re);
7982 mInjector.binderRestoreCallingIdentity(identity);
7988 public boolean isMasterVolumeMuted(ComponentName who) {
7989 Preconditions.checkNotNull(who, "ComponentName is null");
7990 synchronized (this) {
7991 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7993 AudioManager audioManager =
7994 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
7995 return audioManager.isMasterMute();
8000 public void setUserIcon(ComponentName who, Bitmap icon) {
8001 synchronized (this) {
8002 Preconditions.checkNotNull(who, "ComponentName is null");
8003 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8005 int userId = UserHandle.getCallingUserId();
8006 long id = mInjector.binderClearCallingIdentity();
8008 mUserManagerInternal.setUserIcon(userId, icon);
8010 mInjector.binderRestoreCallingIdentity(id);
8016 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8017 Preconditions.checkNotNull(who, "ComponentName is null");
8018 synchronized (this) {
8019 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8021 final int userId = UserHandle.getCallingUserId();
8023 long ident = mInjector.binderClearCallingIdentity();
8025 // disallow disabling the keyguard if a password is currently set
8026 if (disabled && mLockPatternUtils.isSecure(userId)) {
8029 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8031 mInjector.binderRestoreCallingIdentity(ident);
8037 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8038 int userId = UserHandle.getCallingUserId();
8039 synchronized (this) {
8040 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8041 DevicePolicyData policy = getUserData(userId);
8042 if (policy.mStatusBarDisabled != disabled) {
8043 if (!setStatusBarDisabledInternal(disabled, userId)) {
8046 policy.mStatusBarDisabled = disabled;
8047 saveSettingsLocked(userId);
8053 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8054 long ident = mInjector.binderClearCallingIdentity();
8056 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8057 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8058 if (statusBarService != null) {
8059 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8060 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8061 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8062 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8065 } catch (RemoteException e) {
8066 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8068 mInjector.binderRestoreCallingIdentity(ident);
8074 * We need to update the internal state of whether a user has completed setup once. After
8075 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
8076 * as we don't trust any apps that might try to reset it.
8078 * Unfortunately, we don't know which user's setup state was changed, so we write all of
8081 void updateUserSetupComplete() {
8082 List<UserInfo> users = mUserManager.getUsers(true);
8083 final int N = users.size();
8084 for (int i = 0; i < N; i++) {
8085 int userHandle = users.get(i).id;
8086 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8088 DevicePolicyData policy = getUserData(userHandle);
8089 if (!policy.mUserSetupComplete) {
8090 policy.mUserSetupComplete = true;
8091 synchronized (this) {
8092 saveSettingsLocked(userHandle);
8099 private class SetupContentObserver extends ContentObserver {
8101 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8102 Settings.Secure.USER_SETUP_COMPLETE);
8103 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8104 Settings.Global.DEVICE_PROVISIONED);
8106 public SetupContentObserver(Handler handler) {
8111 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8112 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8116 public void onChange(boolean selfChange, Uri uri) {
8117 if (mUserSetupComplete.equals(uri)) {
8118 updateUserSetupComplete();
8119 } else if (mDeviceProvisioned.equals(uri)) {
8120 synchronized (DevicePolicyManagerService.this) {
8121 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8122 // is delayed until device is marked as provisioned.
8123 setDeviceOwnerSystemPropertyLocked();
8130 final class LocalService extends DevicePolicyManagerInternal {
8131 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8134 public List<String> getCrossProfileWidgetProviders(int profileId) {
8135 synchronized (DevicePolicyManagerService.this) {
8136 if (mOwners == null) {
8137 return Collections.emptyList();
8139 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8140 if (ownerComponent == null) {
8141 return Collections.emptyList();
8144 DevicePolicyData policy = getUserDataUnchecked(profileId);
8145 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8147 if (admin == null || admin.crossProfileWidgetProviders == null
8148 || admin.crossProfileWidgetProviders.isEmpty()) {
8149 return Collections.emptyList();
8152 return admin.crossProfileWidgetProviders;
8157 public void addOnCrossProfileWidgetProvidersChangeListener(
8158 OnCrossProfileWidgetProvidersChangeListener listener) {
8159 synchronized (DevicePolicyManagerService.this) {
8160 if (mWidgetProviderListeners == null) {
8161 mWidgetProviderListeners = new ArrayList<>();
8163 if (!mWidgetProviderListeners.contains(listener)) {
8164 mWidgetProviderListeners.add(listener);
8170 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8171 synchronized(DevicePolicyManagerService.this) {
8172 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8176 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8177 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8178 synchronized (DevicePolicyManagerService.this) {
8179 listeners = new ArrayList<>(mWidgetProviderListeners);
8181 final int listenerCount = listeners.size();
8182 for (int i = 0; i < listenerCount; i++) {
8183 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8184 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8189 public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
8190 Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8191 intent.putExtra(Intent.EXTRA_USER_ID, userId);
8192 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8194 // This method is called from AM with its lock held, so don't take the DPMS lock.
8197 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8198 if (profileOwner != null) {
8199 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
8203 final Pair<Integer, ComponentName> deviceOwner =
8204 mOwners.getDeviceOwnerUserIdAndComponent();
8205 if (deviceOwner != null && deviceOwner.first == userId) {
8206 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
8210 // We're not specifying the device admin because there isn't one.
8216 * Returns true if specified admin is allowed to limit passwords and has a
8217 * {@code passwordQuality} of at least {@code minPasswordQuality}
8219 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8220 if (admin.passwordQuality < minPasswordQuality) {
8223 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8227 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8228 if (policy != null && !policy.isValid()) {
8229 throw new IllegalArgumentException("Invalid system update policy.");
8231 synchronized (this) {
8232 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8233 if (policy == null) {
8234 mOwners.clearSystemUpdatePolicy();
8236 mOwners.setSystemUpdatePolicy(policy);
8238 mOwners.writeDeviceOwner();
8240 mContext.sendBroadcastAsUser(
8241 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8246 public SystemUpdatePolicy getSystemUpdatePolicy() {
8247 synchronized (this) {
8248 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
8249 if (policy != null && !policy.isValid()) {
8250 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8258 * Checks if the caller of the method is the device owner app.
8260 * @param callerUid UID of the caller.
8261 * @return true if the caller is the device owner app
8264 boolean isCallerDeviceOwner(int callerUid) {
8265 synchronized (this) {
8266 if (!mOwners.hasDeviceOwner()) {
8269 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8272 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8274 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8276 for (String pkg : pkgs) {
8277 if (deviceOwnerPackageName.equals(pkg)) {
8287 public void notifyPendingSystemUpdate(long updateReceivedTime) {
8288 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8289 "Only the system update service can broadcast update information");
8291 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8292 Slog.w(LOG_TAG, "Only the system update service in the system user " +
8293 "can broadcast update information.");
8296 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8297 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8298 updateReceivedTime);
8300 synchronized (this) {
8301 final String deviceOwnerPackage =
8302 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8304 if (deviceOwnerPackage == null) {
8307 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8309 ActivityInfo[] receivers = null;
8311 receivers = mContext.getPackageManager().getPackageInfo(
8312 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8313 } catch (NameNotFoundException e) {
8314 Log.e(LOG_TAG, "Cannot find device owner package", e);
8316 if (receivers != null) {
8317 long ident = mInjector.binderClearCallingIdentity();
8319 for (int i = 0; i < receivers.length; i++) {
8320 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8321 intent.setComponent(new ComponentName(deviceOwnerPackage,
8322 receivers[i].name));
8323 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8327 mInjector.binderRestoreCallingIdentity(ident);
8334 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8335 int userId = UserHandle.getCallingUserId();
8336 synchronized (this) {
8337 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8338 DevicePolicyData userPolicy = getUserData(userId);
8339 if (userPolicy.mPermissionPolicy != policy) {
8340 userPolicy.mPermissionPolicy = policy;
8341 saveSettingsLocked(userId);
8347 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8348 int userId = UserHandle.getCallingUserId();
8349 synchronized (this) {
8350 DevicePolicyData userPolicy = getUserData(userId);
8351 return userPolicy.mPermissionPolicy;
8356 public boolean setPermissionGrantState(ComponentName admin, String packageName,
8357 String permission, int grantState) throws RemoteException {
8358 UserHandle user = mInjector.binderGetCallingUserHandle();
8359 synchronized (this) {
8360 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8361 long ident = mInjector.binderClearCallingIdentity();
8363 if (getTargetSdk(packageName, user.getIdentifier())
8364 < android.os.Build.VERSION_CODES.M) {
8367 if (!isRuntimePermission(permission)) {
8368 EventLog.writeEvent(0x534e4554, "62623498", user.getIdentifier(), "");
8371 final PackageManager packageManager = mContext.getPackageManager();
8372 switch (grantState) {
8373 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8374 packageManager.grantRuntimePermission(packageName, permission, user);
8375 packageManager.updatePermissionFlags(permission, packageName,
8376 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8377 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8380 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8381 packageManager.revokeRuntimePermission(packageName,
8383 packageManager.updatePermissionFlags(permission, packageName,
8384 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8385 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8388 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8389 packageManager.updatePermissionFlags(permission, packageName,
8390 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8394 } catch (SecurityException se) {
8396 } catch (NameNotFoundException e) {
8399 mInjector.binderRestoreCallingIdentity(ident);
8404 public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
8405 final PackageManager packageManager = mContext.getPackageManager();
8406 PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
8407 return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
8408 == PermissionInfo.PROTECTION_DANGEROUS;
8412 public int getPermissionGrantState(ComponentName admin, String packageName,
8413 String permission) throws RemoteException {
8414 PackageManager packageManager = mContext.getPackageManager();
8416 UserHandle user = mInjector.binderGetCallingUserHandle();
8417 synchronized (this) {
8418 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8419 long ident = mInjector.binderClearCallingIdentity();
8421 int granted = mIPackageManager.checkPermission(permission,
8422 packageName, user.getIdentifier());
8423 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8424 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8425 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8426 // Not controlled by policy
8427 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8429 // Policy controlled so return result based on permission grant state
8430 return granted == PackageManager.PERMISSION_GRANTED
8431 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8432 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8435 mInjector.binderRestoreCallingIdentity(ident);
8440 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8442 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8444 return (pi != null) && (pi.applicationInfo.flags != 0);
8445 } catch (RemoteException re) {
8446 throw new RuntimeException("Package manager has died", re);
8451 public boolean isProvisioningAllowed(String action) {
8456 final int callingUserId = mInjector.userHandleGetCallingUserId();
8457 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8458 if (!hasFeatureManagedUsers()) {
8461 synchronized (this) {
8462 if (mOwners.hasDeviceOwner()) {
8463 if (!mInjector.userManagerIsSplitSystemUser()) {
8464 // Only split-system-user systems support managed-profiles in combination with
8468 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8469 // Only system device-owner supports managed-profiles. Non-system device-owner
8473 if (callingUserId == UserHandle.USER_SYSTEM) {
8474 // Managed-profiles cannot be setup on the system user, only regular users.
8479 if (getProfileOwner(callingUserId) != null) {
8480 // Managed user cannot have a managed profile.
8483 final long ident = mInjector.binderClearCallingIdentity();
8485 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8489 mInjector.binderRestoreCallingIdentity(ident);
8492 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8493 return isDeviceOwnerProvisioningAllowed(callingUserId);
8494 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8495 if (!hasFeatureManagedUsers()) {
8498 if (!mInjector.userManagerIsSplitSystemUser()) {
8499 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8502 if (callingUserId == UserHandle.USER_SYSTEM) {
8503 // System user cannot be a managed user.
8506 if (hasUserSetupCompleted(callingUserId)) {
8510 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8511 if (!mInjector.userManagerIsSplitSystemUser()) {
8512 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8515 return isDeviceOwnerProvisioningAllowed(callingUserId);
8517 throw new IllegalArgumentException("Unknown provisioning action " + action);
8521 * The device owner can only be set before the setup phase of the primary user has completed,
8522 * except for adb command if no accounts or additional users are present on the device.
8524 private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreCondition(
8525 int deviceOwnerUserId, boolean isAdb) {
8526 if (mOwners.hasDeviceOwner()) {
8527 return CODE_HAS_DEVICE_OWNER;
8529 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8530 return CODE_USER_HAS_PROFILE_OWNER;
8532 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8533 return CODE_USER_NOT_RUNNING;
8536 // if shell command runs after user setup completed check device status. Otherwise, OK.
8537 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8538 if (!mInjector.userManagerIsSplitSystemUser()) {
8539 if (mUserManager.getUserCount() > 1) {
8540 return CODE_NONSYSTEM_USER_EXISTS;
8542 if (AccountManager.get(mContext).getAccounts().length > 0) {
8543 return CODE_ACCOUNTS_NOT_EMPTY;
8546 // STOPSHIP Do proper check in split user mode
8551 if (!mInjector.userManagerIsSplitSystemUser()) {
8552 // In non-split user mode, DO has to be user 0
8553 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8554 return CODE_NOT_SYSTEM_USER;
8556 // In non-split user mode, only provision DO before setup wizard completes
8557 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8558 return CODE_USER_SETUP_COMPLETED;
8561 // STOPSHIP Do proper check in split user mode
8567 private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8568 return CODE_OK == checkSetDeviceOwnerPreCondition(deviceOwnerUserId, /* isAdb */ false);
8571 private boolean hasFeatureManagedUsers() {
8573 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8574 } catch (RemoteException e) {
8580 public String getWifiMacAddress(ComponentName admin) {
8581 // Make sure caller has DO.
8582 synchronized (this) {
8583 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8586 final long ident = mInjector.binderClearCallingIdentity();
8588 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8589 if (wifiInfo == null) {
8592 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8594 mInjector.binderRestoreCallingIdentity(ident);
8599 * Returns the target sdk version number that the given packageName was built for
8600 * in the given user.
8602 private int getTargetSdk(String packageName, int userId) {
8603 final ApplicationInfo ai;
8605 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8606 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8607 return targetSdkVersion;
8608 } catch (RemoteException e) {
8615 public boolean isManagedProfile(ComponentName admin) {
8616 synchronized (this) {
8617 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8619 final int callingUserId = mInjector.userHandleGetCallingUserId();
8620 final UserInfo user = getUserInfo(callingUserId);
8621 return user != null && user.isManagedProfile();
8625 public boolean isSystemOnlyUser(ComponentName admin) {
8626 synchronized (this) {
8627 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8629 final int callingUserId = mInjector.userHandleGetCallingUserId();
8630 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8634 public void reboot(ComponentName admin) {
8635 Preconditions.checkNotNull(admin);
8636 // Make sure caller has DO.
8637 synchronized (this) {
8638 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8640 long ident = mInjector.binderClearCallingIdentity();
8642 // Make sure there are no ongoing calls on the device.
8643 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8644 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8646 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8648 mInjector.binderRestoreCallingIdentity(ident);
8653 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8657 Preconditions.checkNotNull(who, "ComponentName is null");
8658 final int userHandle = mInjector.userHandleGetCallingUserId();
8659 synchronized (this) {
8660 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8661 mInjector.binderGetCallingUid());
8662 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8663 admin.shortSupportMessage = message;
8664 saveSettingsLocked(userHandle);
8670 public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8674 Preconditions.checkNotNull(who, "ComponentName is null");
8675 synchronized (this) {
8676 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8677 mInjector.binderGetCallingUid());
8678 return admin.shortSupportMessage;
8683 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8687 Preconditions.checkNotNull(who, "ComponentName is null");
8688 final int userHandle = mInjector.userHandleGetCallingUserId();
8689 synchronized (this) {
8690 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8691 mInjector.binderGetCallingUid());
8692 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8693 admin.longSupportMessage = message;
8694 saveSettingsLocked(userHandle);
8700 public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8704 Preconditions.checkNotNull(who, "ComponentName is null");
8705 synchronized (this) {
8706 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8707 mInjector.binderGetCallingUid());
8708 return admin.longSupportMessage;
8713 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8717 Preconditions.checkNotNull(who, "ComponentName is null");
8718 if (!isCallerWithSystemUid()) {
8719 throw new SecurityException("Only the system can query support message for user");
8721 synchronized (this) {
8722 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8723 if (admin != null) {
8724 return admin.shortSupportMessage;
8731 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8735 Preconditions.checkNotNull(who, "ComponentName is null");
8736 if (!isCallerWithSystemUid()) {
8737 throw new SecurityException("Only the system can query support message for user");
8739 synchronized (this) {
8740 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8741 if (admin != null) {
8742 return admin.longSupportMessage;
8749 public void setOrganizationColor(@NonNull ComponentName who, int color) {
8753 Preconditions.checkNotNull(who, "ComponentName is null");
8754 final int userHandle = mInjector.userHandleGetCallingUserId();
8755 enforceManagedProfile(userHandle, "set organization color");
8756 synchronized (this) {
8757 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8758 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8759 admin.organizationColor = color;
8760 saveSettingsLocked(userHandle);
8765 public void setOrganizationColorForUser(int color, int userId) {
8769 enforceFullCrossUsersPermission(userId);
8770 enforceManageUsers();
8771 enforceManagedProfile(userId, "set organization color");
8772 synchronized (this) {
8773 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8774 admin.organizationColor = color;
8775 saveSettingsLocked(userId);
8780 public int getOrganizationColor(@NonNull ComponentName who) {
8782 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8784 Preconditions.checkNotNull(who, "ComponentName is null");
8785 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
8786 synchronized (this) {
8787 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8788 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8789 return admin.organizationColor;
8794 public int getOrganizationColorForUser(int userHandle) {
8796 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8798 enforceFullCrossUsersPermission(userHandle);
8799 enforceManagedProfile(userHandle, "get organization color");
8800 synchronized (this) {
8801 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8802 return (profileOwner != null)
8803 ? profileOwner.organizationColor
8804 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
8809 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
8813 Preconditions.checkNotNull(who, "ComponentName is null");
8814 final int userHandle = mInjector.userHandleGetCallingUserId();
8815 enforceManagedProfile(userHandle, "set organization name");
8816 synchronized (this) {
8817 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8818 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8819 if (!TextUtils.equals(admin.organizationName, text)) {
8820 admin.organizationName = (text == null || text.length() == 0)
8821 ? null : text.toString();
8822 saveSettingsLocked(userHandle);
8828 public CharSequence getOrganizationName(@NonNull ComponentName who) {
8832 Preconditions.checkNotNull(who, "ComponentName is null");
8833 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
8834 synchronized(this) {
8835 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8836 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8837 return admin.organizationName;
8842 public CharSequence getOrganizationNameForUser(int userHandle) {
8846 enforceFullCrossUsersPermission(userHandle);
8847 enforceManagedProfile(userHandle, "get organization name");
8848 synchronized (this) {
8849 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8850 return (profileOwner != null)
8851 ? profileOwner.organizationName
8857 public void setAffiliationIds(ComponentName admin, List<String> ids) {
8858 final Set<String> affiliationIds = new ArraySet<String>(ids);
8859 final int callingUserId = mInjector.userHandleGetCallingUserId();
8861 synchronized (this) {
8862 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8863 getUserData(callingUserId).mAffiliationIds = affiliationIds;
8864 saveSettingsLocked(callingUserId);
8865 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
8866 // Affiliation ids specified by the device owner are additionally stored in
8867 // UserHandle.USER_SYSTEM's DevicePolicyData.
8868 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
8869 saveSettingsLocked(UserHandle.USER_SYSTEM);
8875 public boolean isAffiliatedUser() {
8876 final int callingUserId = mInjector.userHandleGetCallingUserId();
8878 synchronized (this) {
8879 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
8880 // The user that the DO is installed on is always affiliated.
8883 final ComponentName profileOwner = getProfileOwner(callingUserId);
8884 if (profileOwner == null
8885 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
8888 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
8889 final Set<String> deviceAffiliationIds =
8890 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
8891 for (String id : userAffiliationIds) {
8892 if (deviceAffiliationIds.contains(id)) {
8900 private synchronized void disableSecurityLoggingIfNotCompliant() {
8901 if (!isDeviceOwnerManagedSingleUserDevice()) {
8902 mInjector.securityLogSetLoggingEnabledProperty(false);
8903 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user device.");
8908 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
8909 Preconditions.checkNotNull(admin);
8910 ensureDeviceOwnerManagingSingleUser(admin);
8912 synchronized (this) {
8913 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
8916 mInjector.securityLogSetLoggingEnabledProperty(enabled);
8918 mSecurityLogMonitor.start();
8920 mSecurityLogMonitor.stop();
8926 public boolean isSecurityLoggingEnabled(ComponentName admin) {
8927 Preconditions.checkNotNull(admin);
8928 synchronized (this) {
8929 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8930 return mInjector.securityLogGetLoggingEnabledProperty();
8935 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
8936 Preconditions.checkNotNull(admin);
8937 ensureDeviceOwnerManagingSingleUser(admin);
8939 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
8943 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
8945 SecurityLog.readPreviousEvents(output);
8946 return new ParceledListSlice<SecurityEvent>(output);
8947 } catch (IOException e) {
8948 Slog.w(LOG_TAG, "Fail to read previous events" , e);
8949 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
8954 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
8955 Preconditions.checkNotNull(admin);
8956 ensureDeviceOwnerManagingSingleUser(admin);
8958 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
8959 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
8962 private void enforceCanManageDeviceAdmin() {
8963 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
8967 private void enforceCanManageProfileAndDeviceOwners() {
8968 mContext.enforceCallingOrSelfPermission(
8969 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
8973 public boolean isUninstallInQueue(final String packageName) {
8974 enforceCanManageDeviceAdmin();
8975 final int userId = mInjector.userHandleGetCallingUserId();
8976 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8977 synchronized (this) {
8978 return mPackagesToRemove.contains(packageUserPair);
8983 public void uninstallPackageWithActiveAdmins(final String packageName) {
8984 enforceCanManageDeviceAdmin();
8985 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
8987 final int userId = mInjector.userHandleGetCallingUserId();
8989 enforceUserUnlocked(userId);
8991 final ComponentName profileOwner = getProfileOwner(userId);
8992 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
8993 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
8996 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
8997 if (getDeviceOwnerUserId() == userId && deviceOwner != null
8998 && packageName.equals(deviceOwner.getPackageName())) {
8999 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
9002 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9003 synchronized (this) {
9004 mPackagesToRemove.add(packageUserPair);
9007 // All active admins on the user.
9008 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
9010 // Active admins in the target package.
9011 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
9012 if (allActiveAdmins != null) {
9013 for (ComponentName activeAdmin : allActiveAdmins) {
9014 if (packageName.equals(activeAdmin.getPackageName())) {
9015 packageActiveAdmins.add(activeAdmin);
9016 removeActiveAdmin(activeAdmin, userId);
9020 if (packageActiveAdmins.size() == 0) {
9021 startUninstallIntent(packageName, userId);
9023 mHandler.postDelayed(new Runnable() {
9026 for (ComponentName activeAdmin : packageActiveAdmins) {
9027 removeAdminArtifacts(activeAdmin, userId);
9029 startUninstallIntent(packageName, userId);
9031 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9035 private void removePackageIfRequired(final String packageName, final int userId) {
9036 if (!packageHasActiveAdmins(packageName, userId)) {
9037 // Will not do anything if uninstall was not requested or was already started.
9038 startUninstallIntent(packageName, userId);
9042 private void startUninstallIntent(final String packageName, final int userId) {
9043 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9044 synchronized (this) {
9045 if (!mPackagesToRemove.contains(packageUserPair)) {
9046 // Do nothing if uninstall was not requested or was already started.
9049 mPackagesToRemove.remove(packageUserPair);
9052 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9053 // Package does not exist. Nothing to do.
9056 } catch (RemoteException re) {
9057 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9060 try { // force stop the package before uninstalling
9061 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9062 } catch (RemoteException re) {
9063 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9065 final Uri packageURI = Uri.parse("package:" + packageName);
9066 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9067 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9068 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9072 * Removes the admin from the policy. Ideally called after the admin's
9073 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9075 * @param adminReceiver The admin to remove
9076 * @param userHandle The user for which this admin has to be removed.
9078 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9079 synchronized (this) {
9080 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9081 if (admin == null) {
9084 final DevicePolicyData policy = getUserData(userHandle);
9085 final boolean doProxyCleanup = admin.info.usesPolicy(
9086 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9087 policy.mAdminList.remove(admin);
9088 policy.mAdminMap.remove(adminReceiver);
9089 validatePasswordOwnerLocked(policy);
9090 if (doProxyCleanup) {
9091 resetGlobalProxyLocked(policy);
9093 saveSettingsLocked(userHandle);
9094 updateMaximumTimeToLockLocked(userHandle);
9095 policy.mRemovingAdmins.remove(adminReceiver);
9097 // The removed admin might have disabled camera, so update user
9099 pushUserRestrictions(userHandle);