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;
24 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
25 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
26 import static org.xmlpull.v1.XmlPullParser.END_TAG;
27 import static org.xmlpull.v1.XmlPullParser.TEXT;
29 import com.google.android.collect.Sets;
31 import android.Manifest.permission;
32 import android.accessibilityservice.AccessibilityServiceInfo;
33 import android.accounts.AccountManager;
34 import android.annotation.NonNull;
35 import android.app.Activity;
36 import android.app.ActivityManager;
37 import android.app.ActivityManagerNative;
38 import android.app.AlarmManager;
39 import android.app.AppGlobals;
40 import android.app.IActivityManager;
41 import android.app.Notification;
42 import android.app.NotificationManager;
43 import android.app.PendingIntent;
44 import android.app.StatusBarManager;
45 import android.app.admin.DeviceAdminInfo;
46 import android.app.admin.DeviceAdminReceiver;
47 import android.app.admin.DevicePolicyManager;
48 import android.app.admin.DevicePolicyManagerInternal;
49 import android.app.admin.IDevicePolicyManager;
50 import android.app.admin.SystemUpdatePolicy;
51 import android.app.backup.IBackupManager;
52 import android.auditing.SecurityLog;
53 import android.auditing.SecurityLog.SecurityEvent;
54 import android.content.BroadcastReceiver;
55 import android.content.ComponentName;
56 import android.content.ContentResolver;
57 import android.content.Context;
58 import android.content.Intent;
59 import android.content.IntentFilter;
60 import android.content.pm.ActivityInfo;
61 import android.content.pm.ApplicationInfo;
62 import android.content.pm.IPackageManager;
63 import android.content.pm.PackageInfo;
64 import android.content.pm.PackageManager;
65 import android.content.pm.PackageManager.NameNotFoundException;
66 import android.content.pm.PackageManagerInternal;
67 import android.content.pm.ParceledListSlice;
68 import android.content.pm.ResolveInfo;
69 import android.content.pm.ServiceInfo;
70 import android.content.pm.UserInfo;
71 import android.database.ContentObserver;
72 import android.graphics.Bitmap;
73 import android.graphics.Color;
74 import android.media.AudioManager;
75 import android.media.IAudioService;
76 import android.net.ConnectivityManager;
77 import android.net.ProxyInfo;
78 import android.net.Uri;
79 import android.net.wifi.WifiInfo;
80 import android.net.wifi.WifiManager;
81 import android.os.AsyncTask;
82 import android.os.Binder;
83 import android.os.Build;
84 import android.os.Bundle;
85 import android.os.Environment;
86 import android.os.FileUtils;
87 import android.os.Handler;
88 import android.os.IBinder;
89 import android.os.Looper;
90 import android.os.ParcelFileDescriptor;
91 import android.os.PersistableBundle;
92 import android.os.PowerManager;
93 import android.os.PowerManagerInternal;
94 import android.os.Process;
95 import android.os.RecoverySystem;
96 import android.os.RemoteCallback;
97 import android.os.RemoteException;
98 import android.os.ServiceManager;
99 import android.os.SystemClock;
100 import android.os.SystemProperties;
101 import android.os.UserHandle;
102 import android.os.UserManager;
103 import android.os.UserManagerInternal;
104 import android.os.storage.StorageManager;
105 import android.provider.ContactsContract.QuickContact;
106 import android.provider.ContactsInternal;
107 import android.provider.Settings;
108 import android.security.Credentials;
109 import android.security.IKeyChainAliasCallback;
110 import android.security.IKeyChainService;
111 import android.security.KeyChain;
112 import android.security.KeyChain.KeyChainConnection;
113 import android.service.persistentdata.PersistentDataBlockManager;
114 import android.text.TextUtils;
115 import android.util.ArrayMap;
116 import android.util.ArraySet;
117 import android.util.Log;
118 import android.util.Slog;
119 import android.util.SparseArray;
120 import android.util.Xml;
121 import android.view.IWindowManager;
122 import android.view.accessibility.AccessibilityManager;
123 import android.view.accessibility.IAccessibilityManager;
124 import android.view.inputmethod.InputMethodInfo;
125 import android.view.inputmethod.InputMethodManager;
127 import com.android.internal.R;
128 import com.android.internal.annotations.VisibleForTesting;
129 import com.android.internal.statusbar.IStatusBarService;
130 import com.android.internal.util.FastXmlSerializer;
131 import com.android.internal.util.JournaledFile;
132 import com.android.internal.util.Preconditions;
133 import com.android.internal.util.XmlUtils;
134 import com.android.internal.widget.LockPatternUtils;
135 import com.android.server.LocalServices;
136 import com.android.server.SystemService;
137 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
138 import com.android.server.pm.UserRestrictionsUtils;
140 import org.xmlpull.v1.XmlPullParser;
141 import org.xmlpull.v1.XmlPullParserException;
142 import org.xmlpull.v1.XmlSerializer;
144 import java.io.ByteArrayInputStream;
146 import java.io.FileDescriptor;
147 import java.io.FileInputStream;
148 import java.io.FileNotFoundException;
149 import java.io.FileOutputStream;
150 import java.io.IOException;
151 import java.io.PrintWriter;
152 import java.nio.charset.StandardCharsets;
153 import java.security.cert.CertificateException;
154 import java.security.cert.CertificateFactory;
155 import java.security.cert.X509Certificate;
156 import java.text.DateFormat;
157 import java.util.ArrayList;
158 import java.util.Arrays;
159 import java.util.Collections;
160 import java.util.Date;
161 import java.util.List;
162 import java.util.Map.Entry;
163 import java.util.Set;
164 import java.util.concurrent.atomic.AtomicBoolean;
167 * Implementation of the device policy APIs.
169 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
171 private static final String LOG_TAG = "DevicePolicyManagerService";
173 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
175 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
177 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
179 private static final String TAG_STATUS_BAR = "statusbar";
181 private static final String ATTR_DISABLED = "disabled";
183 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
184 "do-not-ask-credentials-on-boot";
186 private static final String TAG_AFFILIATION_ID = "affiliation-id";
188 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
190 private static final String ATTR_VALUE = "value";
192 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
194 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
196 private static final long MS_PER_DAY = 86400 * 1000;
198 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
200 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
201 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
203 private static final int MONITORING_CERT_NOTIFICATION_ID = R.string.ssl_ca_cert_warning;
204 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
206 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
207 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
208 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
209 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
211 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
212 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
213 = "application-restrictions-manager";
216 * System property whose value is either "true" or "false", indicating whether
218 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
220 private static final int STATUS_BAR_DISABLE_MASK =
221 StatusBarManager.DISABLE_EXPAND |
222 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
223 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
224 StatusBarManager.DISABLE_SEARCH;
226 private static final int STATUS_BAR_DISABLE2_MASK =
227 StatusBarManager.DISABLE2_QUICK_SETTINGS;
229 private static final Set<String> SECURE_SETTINGS_WHITELIST;
230 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
231 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
232 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
234 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
235 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
236 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
237 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
239 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
240 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
241 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
243 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
244 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
245 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
246 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
247 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
248 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
249 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
250 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
251 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
253 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
254 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
255 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
256 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
257 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
258 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
261 /** Keyguard features that when set on a profile will affect the profiles parent user. */
262 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
263 // STOPSHIP If the work challenge supports fingerprint, move DISABLE_FINGERPRINT
264 // to PROFILE_KEYGUARD_FEATURES_AFFECT_PROFILE?
265 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
266 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
268 /** Keyguard features that when set on a profile affect the profile content or challenge only */
269 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_PROFILE =
270 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
272 /** Keyguard features that are allowed to be set on a managed profile */
273 private static final int PROFILE_KEYGUARD_FEATURES =
274 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_AFFECT_PROFILE;
276 final Context mContext;
277 final Injector mInjector;
278 final IPackageManager mIPackageManager;
279 final UserManager mUserManager;
280 final UserManagerInternal mUserManagerInternal;
281 private final LockPatternUtils mLockPatternUtils;
283 final LocalService mLocalService;
285 // Stores and loads state on device and profile owners.
287 final Owners mOwners;
289 private final Binder mToken = new Binder();
292 * Whether or not device admin feature is supported. If it isn't return defaults for all
295 private boolean mHasFeature;
297 private final SecurityLogMonitor mSecurityLogMonitor;
299 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
300 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
302 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
305 if(mRemoteBugreportServiceIsActive.get()) {
311 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
314 public void onReceive(Context context, Intent intent) {
315 if (RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
316 && mRemoteBugreportServiceIsActive.get()) {
317 onBugreportFinished(intent);
322 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
325 public void onReceive(Context context, Intent intent) {
326 String action = intent.getAction();
327 mInjector.getNotificationManager().cancel(LOG_TAG,
328 RemoteBugreportUtils.REMOTE_BUGREPORT_CONSENT_NOTIFICATION_ID);
329 if (RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
330 onBugreportSharingAccepted();
331 } else if (RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_DECLINED
333 onBugreportSharingDeclined();
335 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
339 public static final class Lifecycle extends SystemService {
340 private DevicePolicyManagerService mService;
342 public Lifecycle(Context context) {
344 mService = new DevicePolicyManagerService(context);
348 public void onStart() {
349 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
353 public void onBootPhase(int phase) {
354 mService.systemReady(phase);
358 public void onStartUser(int userHandle) {
359 mService.onStartUser(userHandle);
363 public static class DevicePolicyData {
364 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
365 int mActivePasswordLength = 0;
366 int mActivePasswordUpperCase = 0;
367 int mActivePasswordLowerCase = 0;
368 int mActivePasswordLetters = 0;
369 int mActivePasswordNumeric = 0;
370 int mActivePasswordSymbols = 0;
371 int mActivePasswordNonLetter = 0;
372 int mFailedPasswordAttempts = 0;
375 int mPasswordOwner = -1;
376 long mLastMaximumTimeToLock = -1;
377 boolean mUserSetupComplete = false;
378 int mUserProvisioningState;
379 int mPermissionPolicy;
381 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
382 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
383 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
385 // This is the list of component allowed to start lock task mode.
386 List<String> mLockTaskPackages = new ArrayList<>();
388 boolean mStatusBarDisabled = false;
390 ComponentName mRestrictionsProvider;
392 String mDelegatedCertInstallerPackage;
394 boolean doNotAskCredentialsOnBoot = false;
396 String mApplicationRestrictionsManagingPackage;
398 Set<String> mAffiliationIds = new ArraySet<>();
400 // Used for initialization of users created by createAndManageUsers.
401 boolean mAdminBroadcastPending = false;
402 PersistableBundle mInitBundle = null;
404 public DevicePolicyData(int userHandle) {
405 mUserHandle = userHandle;
409 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
411 final Handler mHandler;
413 BroadcastReceiver mReceiver = new BroadcastReceiver() {
415 public void onReceive(Context context, Intent intent) {
416 final String action = intent.getAction();
417 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
420 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
421 && userHandle == mOwners.getDeviceOwnerUserId()
422 && getDeviceOwnerRemoteBugreportUri() != null) {
423 IntentFilter filterConsent = new IntentFilter();
424 filterConsent.addAction(
425 RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_DECLINED);
426 filterConsent.addAction(
427 RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_ACCEPTED);
428 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
429 mInjector.getNotificationManager().notify(
430 LOG_TAG, RemoteBugreportUtils.REMOTE_BUGREPORT_CONSENT_NOTIFICATION_ID,
431 RemoteBugreportUtils.buildRemoteBugreportConsentNotification(mContext));
433 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
434 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
436 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
437 + action + " for user " + userHandle);
439 mHandler.post(new Runnable() {
442 handlePasswordExpirationNotification(userHandle);
446 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
447 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
448 new MonitoringCertNotificationTask().execute(intent);
450 if (Intent.ACTION_USER_ADDED.equals(action)) {
451 disableDeviceLoggingIfNotCompliant();
452 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
453 disableDeviceLoggingIfNotCompliant();
454 removeUserData(userHandle);
455 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
456 synchronized (DevicePolicyManagerService.this) {
457 // Reset the policy data
458 mUserData.remove(userHandle);
459 sendAdminEnabledBroadcastLocked(userHandle);
461 handlePackagesChanged(null /* check all admins */, userHandle);
462 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
463 handlePackagesChanged(null /* check all admins */, userHandle);
464 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
465 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
466 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
467 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
468 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
469 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
470 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
471 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
472 clearWipeProfileNotification();
477 static class ActiveAdmin {
478 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
479 private static final String TAG_DISABLE_CAMERA = "disable-camera";
480 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
481 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
482 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
483 = "disable-bt-contacts-sharing";
484 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
485 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
486 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
487 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
488 private static final String TAG_ACCOUNT_TYPE = "account-type";
489 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
490 = "permitted-accessiblity-services";
491 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
492 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
493 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
494 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
495 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
496 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
497 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
498 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
499 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
500 private static final String TAG_PERMITTED_IMES = "permitted-imes";
501 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
502 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
503 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
504 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
505 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
506 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
507 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
508 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
509 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
510 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
511 private static final String ATTR_VALUE = "value";
512 private static final String TAG_PASSWORD_QUALITY = "password-quality";
513 private static final String TAG_POLICIES = "policies";
514 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
515 "cross-profile-widget-providers";
516 private static final String TAG_PROVIDER = "provider";
517 private static final String TAG_PACKAGE_LIST_ITEM = "item";
518 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
519 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
520 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
521 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
522 private static final String TAG_PARENT_ADMIN = "parent-admin";
523 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
524 private static final String TAG_ORGANIZATION_NAME = "organization-name";
526 final DeviceAdminInfo info;
528 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
530 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
531 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
533 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
534 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
536 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
537 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
539 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
540 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
542 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
543 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
545 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
546 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
548 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
549 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
551 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
552 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
554 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
555 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
557 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
558 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
560 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
561 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
563 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
564 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
566 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
568 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
570 boolean encryptionRequested = false;
571 boolean disableCamera = false;
572 boolean disableCallerId = false;
573 boolean disableContactsSearch = false;
574 boolean disableBluetoothContactSharing = true;
575 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
576 boolean requireAutoTime = false; // Can only be set by a device owner.
577 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
579 ActiveAdmin parentAdmin;
580 final boolean isParent;
582 static class TrustAgentInfo {
583 public PersistableBundle options;
584 TrustAgentInfo(PersistableBundle bundle) {
589 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
591 // The list of permitted accessibility services package namesas set by a profile
592 // or device owner. Null means all accessibility services are allowed, empty means
593 // none except system services are allowed.
594 List<String> permittedAccessiblityServices;
596 // The list of permitted input methods package names as set by a profile or device owner.
597 // Null means all input methods are allowed, empty means none except system imes are
599 List<String> permittedInputMethods;
601 // List of package names to keep cached.
602 List<String> keepUninstalledPackages;
604 // TODO: review implementation decisions with frameworks team
605 boolean specifiesGlobalProxy = false;
606 String globalProxySpec = null;
607 String globalProxyExclusionList = null;
609 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
611 List<String> crossProfileWidgetProviders;
613 Bundle userRestrictions;
615 // Support text provided by the admin to display to the user.
616 String shortSupportMessage = null;
617 String longSupportMessage = null;
619 // Background color of confirm credentials screen. Default: gray.
620 static final int DEF_ORGANIZATION_COLOR = Color.GRAY;
621 int organizationColor = DEF_ORGANIZATION_COLOR;
623 // Default title of confirm credentials screen
624 String organizationName = null;
626 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
631 ActiveAdmin getParentActiveAdmin() {
632 Preconditions.checkState(!isParent);
634 if (parentAdmin == null) {
635 parentAdmin = new ActiveAdmin(info, /* parent */ true);
640 boolean hasParentActiveAdmin() {
641 return parentAdmin != null;
644 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
646 public UserHandle getUserHandle() {
647 return new UserHandle(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
650 void writeToXml(XmlSerializer out)
651 throws IllegalArgumentException, IllegalStateException, IOException {
652 out.startTag(null, TAG_POLICIES);
653 info.writePoliciesToXml(out);
654 out.endTag(null, TAG_POLICIES);
655 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
656 out.startTag(null, TAG_PASSWORD_QUALITY);
657 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
658 out.endTag(null, TAG_PASSWORD_QUALITY);
659 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
660 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
661 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
662 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
664 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
665 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
666 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
667 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
669 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
670 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
671 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
672 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
674 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
675 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
676 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
677 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
679 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
680 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
681 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
682 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
684 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
685 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
686 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
687 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
689 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
690 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
691 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
692 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
694 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
695 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
696 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
697 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
700 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
701 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
702 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
703 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
705 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
706 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
707 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
708 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
710 if (specifiesGlobalProxy) {
711 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
712 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
713 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
714 if (globalProxySpec != null) {
715 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
716 out.attribute(null, ATTR_VALUE, globalProxySpec);
717 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
719 if (globalProxyExclusionList != null) {
720 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
721 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
722 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
725 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
726 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
727 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
728 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
730 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
731 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
732 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
733 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
735 if (encryptionRequested) {
736 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
737 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
738 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
741 out.startTag(null, TAG_DISABLE_CAMERA);
742 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
743 out.endTag(null, TAG_DISABLE_CAMERA);
745 if (disableCallerId) {
746 out.startTag(null, TAG_DISABLE_CALLER_ID);
747 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
748 out.endTag(null, TAG_DISABLE_CALLER_ID);
750 if (disableContactsSearch) {
751 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
752 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
753 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
755 if (disableBluetoothContactSharing) {
756 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
757 out.attribute(null, ATTR_VALUE,
758 Boolean.toString(disableBluetoothContactSharing));
759 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
761 if (disableScreenCapture) {
762 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
763 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
764 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
766 if (requireAutoTime) {
767 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
768 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
769 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
771 if (forceEphemeralUsers) {
772 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
773 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
774 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
776 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
777 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
778 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
779 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
781 if (!accountTypesWithManagementDisabled.isEmpty()) {
782 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
783 for (String ac : accountTypesWithManagementDisabled) {
784 out.startTag(null, TAG_ACCOUNT_TYPE);
785 out.attribute(null, ATTR_VALUE, ac);
786 out.endTag(null, TAG_ACCOUNT_TYPE);
788 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
790 if (!trustAgentInfos.isEmpty()) {
791 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
792 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
793 for (Entry<String, TrustAgentInfo> entry : set) {
794 TrustAgentInfo trustAgentInfo = entry.getValue();
795 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
796 out.attribute(null, ATTR_VALUE, entry.getKey());
797 if (trustAgentInfo.options != null) {
798 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
800 trustAgentInfo.options.saveToXml(out);
801 } catch (XmlPullParserException e) {
802 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
804 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
806 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
808 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
810 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
811 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
812 final int providerCount = crossProfileWidgetProviders.size();
813 for (int i = 0; i < providerCount; i++) {
814 String provider = crossProfileWidgetProviders.get(i);
815 out.startTag(null, TAG_PROVIDER);
816 out.attribute(null, ATTR_VALUE, provider);
817 out.endTag(null, TAG_PROVIDER);
819 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
821 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
822 permittedAccessiblityServices);
823 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
824 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
825 if (hasUserRestrictions()) {
826 UserRestrictionsUtils.writeRestrictions(
827 out, userRestrictions, TAG_USER_RESTRICTIONS);
829 if (!TextUtils.isEmpty(shortSupportMessage)) {
830 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
831 out.text(shortSupportMessage);
832 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
834 if (!TextUtils.isEmpty(longSupportMessage)) {
835 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
836 out.text(longSupportMessage);
837 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
839 if (parentAdmin != null) {
840 out.startTag(null, TAG_PARENT_ADMIN);
841 parentAdmin.writeToXml(out);
842 out.endTag(null, TAG_PARENT_ADMIN);
844 if (organizationColor != DEF_ORGANIZATION_COLOR) {
845 out.startTag(null, TAG_ORGANIZATION_COLOR);
846 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
847 out.endTag(null, TAG_ORGANIZATION_COLOR);
849 if (organizationName != null) {
850 out.startTag(null, TAG_ORGANIZATION_NAME);
851 out.text(organizationName);
852 out.endTag(null, TAG_ORGANIZATION_NAME);
856 void writePackageListToXml(XmlSerializer out, String outerTag,
857 List<String> packageList)
858 throws IllegalArgumentException, IllegalStateException, IOException {
859 if (packageList == null) {
863 out.startTag(null, outerTag);
864 for (String packageName : packageList) {
865 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
866 out.attribute(null, ATTR_VALUE, packageName);
867 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
869 out.endTag(null, outerTag);
872 void readFromXml(XmlPullParser parser)
873 throws XmlPullParserException, IOException {
874 int outerDepth = parser.getDepth();
876 while ((type=parser.next()) != END_DOCUMENT
877 && (type != END_TAG || parser.getDepth() > outerDepth)) {
878 if (type == END_TAG || type == TEXT) {
881 String tag = parser.getName();
882 if (TAG_POLICIES.equals(tag)) {
883 info.readPoliciesFromXml(parser);
884 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
885 passwordQuality = Integer.parseInt(
886 parser.getAttributeValue(null, ATTR_VALUE));
887 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
888 minimumPasswordLength = Integer.parseInt(
889 parser.getAttributeValue(null, ATTR_VALUE));
890 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
891 passwordHistoryLength = Integer.parseInt(
892 parser.getAttributeValue(null, ATTR_VALUE));
893 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
894 minimumPasswordUpperCase = Integer.parseInt(
895 parser.getAttributeValue(null, ATTR_VALUE));
896 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
897 minimumPasswordLowerCase = Integer.parseInt(
898 parser.getAttributeValue(null, ATTR_VALUE));
899 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
900 minimumPasswordLetters = Integer.parseInt(
901 parser.getAttributeValue(null, ATTR_VALUE));
902 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
903 minimumPasswordNumeric = Integer.parseInt(
904 parser.getAttributeValue(null, ATTR_VALUE));
905 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
906 minimumPasswordSymbols = Integer.parseInt(
907 parser.getAttributeValue(null, ATTR_VALUE));
908 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
909 minimumPasswordNonLetter = Integer.parseInt(
910 parser.getAttributeValue(null, ATTR_VALUE));
911 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
912 maximumTimeToUnlock = Long.parseLong(
913 parser.getAttributeValue(null, ATTR_VALUE));
914 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
915 maximumFailedPasswordsForWipe = Integer.parseInt(
916 parser.getAttributeValue(null, ATTR_VALUE));
917 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
918 specifiesGlobalProxy = Boolean.parseBoolean(
919 parser.getAttributeValue(null, ATTR_VALUE));
920 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
922 parser.getAttributeValue(null, ATTR_VALUE);
923 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
924 globalProxyExclusionList =
925 parser.getAttributeValue(null, ATTR_VALUE);
926 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
927 passwordExpirationTimeout = Long.parseLong(
928 parser.getAttributeValue(null, ATTR_VALUE));
929 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
930 passwordExpirationDate = Long.parseLong(
931 parser.getAttributeValue(null, ATTR_VALUE));
932 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
933 encryptionRequested = Boolean.parseBoolean(
934 parser.getAttributeValue(null, ATTR_VALUE));
935 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
936 disableCamera = Boolean.parseBoolean(
937 parser.getAttributeValue(null, ATTR_VALUE));
938 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
939 disableCallerId = Boolean.parseBoolean(
940 parser.getAttributeValue(null, ATTR_VALUE));
941 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
942 disableContactsSearch = Boolean.parseBoolean(
943 parser.getAttributeValue(null, ATTR_VALUE));
944 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
945 disableBluetoothContactSharing = Boolean.parseBoolean(parser
946 .getAttributeValue(null, ATTR_VALUE));
947 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
948 disableScreenCapture = Boolean.parseBoolean(
949 parser.getAttributeValue(null, ATTR_VALUE));
950 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
951 requireAutoTime = Boolean.parseBoolean(
952 parser.getAttributeValue(null, ATTR_VALUE));
953 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
954 forceEphemeralUsers = Boolean.parseBoolean(
955 parser.getAttributeValue(null, ATTR_VALUE));
956 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
957 disabledKeyguardFeatures = Integer.parseInt(
958 parser.getAttributeValue(null, ATTR_VALUE));
959 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
960 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
961 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
962 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
963 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
964 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
965 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
966 permittedAccessiblityServices = readPackageList(parser, tag);
967 } else if (TAG_PERMITTED_IMES.equals(tag)) {
968 permittedInputMethods = readPackageList(parser, tag);
969 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
970 keepUninstalledPackages = readPackageList(parser, tag);
971 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
972 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
973 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
974 type = parser.next();
975 if (type == XmlPullParser.TEXT) {
976 shortSupportMessage = parser.getText();
978 Log.w(LOG_TAG, "Missing text when loading short support message");
980 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
981 type = parser.next();
982 if (type == XmlPullParser.TEXT) {
983 longSupportMessage = parser.getText();
985 Log.w(LOG_TAG, "Missing text when loading long support message");
987 } else if (TAG_PARENT_ADMIN.equals(tag)) {
988 Preconditions.checkState(!isParent);
990 parentAdmin = new ActiveAdmin(info, /* parent */ true);
991 parentAdmin.readFromXml(parser);
992 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
993 organizationColor = Integer.parseInt(
994 parser.getAttributeValue(null, ATTR_VALUE));
995 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
996 type = parser.next();
997 if (type == XmlPullParser.TEXT) {
998 organizationName = parser.getText();
1000 Log.w(LOG_TAG, "Missing text when loading organization name");
1003 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1004 XmlUtils.skipCurrentTag(parser);
1009 private List<String> readPackageList(XmlPullParser parser,
1010 String tag) throws XmlPullParserException, IOException {
1011 List<String> result = new ArrayList<String>();
1012 int outerDepth = parser.getDepth();
1014 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1015 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1016 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1019 String outerTag = parser.getName();
1020 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1021 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1022 if (packageName != null) {
1023 result.add(packageName);
1025 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1028 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1034 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1035 throws XmlPullParserException, IOException {
1036 int outerDepthDAM = parser.getDepth();
1038 Set<String> result = new ArraySet<>();
1039 while ((typeDAM=parser.next()) != END_DOCUMENT
1040 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1041 if (typeDAM == END_TAG || typeDAM == TEXT) {
1044 String tagDAM = parser.getName();
1045 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1046 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1048 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1054 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1055 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1056 int outerDepthDAM = parser.getDepth();
1058 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1059 while ((typeDAM=parser.next()) != END_DOCUMENT
1060 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1061 if (typeDAM == END_TAG || typeDAM == TEXT) {
1064 String tagDAM = parser.getName();
1065 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1066 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1067 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1068 result.put(component, trustAgentInfo);
1070 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1076 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1077 throws XmlPullParserException, IOException {
1078 int outerDepthDAM = parser.getDepth();
1080 TrustAgentInfo result = new TrustAgentInfo(null);
1081 while ((typeDAM=parser.next()) != END_DOCUMENT
1082 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1083 if (typeDAM == END_TAG || typeDAM == TEXT) {
1086 String tagDAM = parser.getName();
1087 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1088 PersistableBundle bundle = new PersistableBundle();
1089 bundle.restoreFromXml(parser);
1090 result.options = bundle;
1092 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1098 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1099 throws XmlPullParserException, IOException {
1100 int outerDepthDAM = parser.getDepth();
1102 ArrayList<String> result = null;
1103 while ((typeDAM=parser.next()) != END_DOCUMENT
1104 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1105 if (typeDAM == END_TAG || typeDAM == TEXT) {
1108 String tagDAM = parser.getName();
1109 if (TAG_PROVIDER.equals(tagDAM)) {
1110 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1111 if (result == null) {
1112 result = new ArrayList<>();
1114 result.add(provider);
1116 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1122 boolean hasUserRestrictions() {
1123 return userRestrictions != null && userRestrictions.size() > 0;
1126 Bundle ensureUserRestrictions() {
1127 if (userRestrictions == null) {
1128 userRestrictions = new Bundle();
1130 return userRestrictions;
1133 void dump(String prefix, PrintWriter pw) {
1134 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1135 pw.print(prefix); pw.println("policies:");
1136 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1138 for (int i=0; i<pols.size(); i++) {
1139 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1142 pw.print(prefix); pw.print("passwordQuality=0x");
1143 pw.println(Integer.toHexString(passwordQuality));
1144 pw.print(prefix); pw.print("minimumPasswordLength=");
1145 pw.println(minimumPasswordLength);
1146 pw.print(prefix); pw.print("passwordHistoryLength=");
1147 pw.println(passwordHistoryLength);
1148 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1149 pw.println(minimumPasswordUpperCase);
1150 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1151 pw.println(minimumPasswordLowerCase);
1152 pw.print(prefix); pw.print("minimumPasswordLetters=");
1153 pw.println(minimumPasswordLetters);
1154 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1155 pw.println(minimumPasswordNumeric);
1156 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1157 pw.println(minimumPasswordSymbols);
1158 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1159 pw.println(minimumPasswordNonLetter);
1160 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1161 pw.println(maximumTimeToUnlock);
1162 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1163 pw.println(maximumFailedPasswordsForWipe);
1164 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1165 pw.println(specifiesGlobalProxy);
1166 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1167 pw.println(passwordExpirationTimeout);
1168 pw.print(prefix); pw.print("passwordExpirationDate=");
1169 pw.println(passwordExpirationDate);
1170 if (globalProxySpec != null) {
1171 pw.print(prefix); pw.print("globalProxySpec=");
1172 pw.println(globalProxySpec);
1174 if (globalProxyExclusionList != null) {
1175 pw.print(prefix); pw.print("globalProxyEclusionList=");
1176 pw.println(globalProxyExclusionList);
1178 pw.print(prefix); pw.print("encryptionRequested=");
1179 pw.println(encryptionRequested);
1180 pw.print(prefix); pw.print("disableCamera=");
1181 pw.println(disableCamera);
1182 pw.print(prefix); pw.print("disableCallerId=");
1183 pw.println(disableCallerId);
1184 pw.print(prefix); pw.print("disableContactsSearch=");
1185 pw.println(disableContactsSearch);
1186 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1187 pw.println(disableBluetoothContactSharing);
1188 pw.print(prefix); pw.print("disableScreenCapture=");
1189 pw.println(disableScreenCapture);
1190 pw.print(prefix); pw.print("requireAutoTime=");
1191 pw.println(requireAutoTime);
1192 pw.print(prefix); pw.print("forceEphemeralUsers=");
1193 pw.println(forceEphemeralUsers);
1194 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1195 pw.println(disabledKeyguardFeatures);
1196 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1197 pw.println(crossProfileWidgetProviders);
1198 if (permittedAccessiblityServices != null) {
1199 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1200 pw.println(permittedAccessiblityServices);
1202 if (permittedInputMethods != null) {
1203 pw.print(prefix); pw.print("permittedInputMethods=");
1204 pw.println(permittedInputMethods);
1206 if (keepUninstalledPackages != null) {
1207 pw.print(prefix); pw.print("keepUninstalledPackages=");
1208 pw.println(keepUninstalledPackages);
1210 pw.print(prefix); pw.print("organizationColor=");
1211 pw.println(organizationColor);
1212 if (organizationName != null) {
1213 pw.print(prefix); pw.print("organizationName=");
1214 pw.println(organizationName);
1216 pw.print(prefix); pw.println("userRestrictions:");
1217 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1218 pw.print(prefix); pw.print("isParent=");
1219 pw.println(isParent);
1220 if (parentAdmin != null) {
1221 pw.print(prefix); pw.println("parentAdmin:");
1222 parentAdmin.dump(prefix + " ", pw);
1227 private void handlePackagesChanged(String packageName, int userHandle) {
1228 boolean removed = false;
1229 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1230 DevicePolicyData policy = getUserData(userHandle);
1231 synchronized (this) {
1232 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1233 ActiveAdmin aa = policy.mAdminList.get(i);
1235 // If we're checking all packages or if the specific one we're checking matches,
1236 // then check if the package and receiver still exist.
1237 final String adminPackage = aa.info.getPackageName();
1238 if (packageName == null || packageName.equals(adminPackage)) {
1239 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1240 || mIPackageManager.getReceiverInfo(
1241 aa.info.getComponent(), 0, userHandle) == null) {
1243 policy.mAdminList.remove(i);
1244 policy.mAdminMap.remove(aa.info.getComponent());
1247 } catch (RemoteException re) {
1252 validatePasswordOwnerLocked(policy);
1253 saveSettingsLocked(policy.mUserHandle);
1256 // Check if delegated cert installer or app restrictions managing packages are removed.
1257 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1258 policy.mDelegatedCertInstallerPackage = null;
1259 saveSettingsLocked(policy.mUserHandle);
1261 if (isRemovedPackage(
1262 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1263 policy.mApplicationRestrictionsManagingPackage = null;
1264 saveSettingsLocked(policy.mUserHandle);
1268 // The removed admin might have disabled camera, so update user restrictions.
1269 pushUserRestrictions(userHandle);
1273 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1275 return targetPackage != null
1276 && (changedPackage == null || changedPackage.equals(targetPackage))
1277 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1278 } catch (RemoteException e) {
1286 * Unit test will subclass it to inject mocks.
1289 static class Injector {
1291 private final Context mContext;
1293 Injector(Context context) {
1297 Owners newOwners() {
1298 return new Owners(mContext, getUserManager(), getUserManagerInternal());
1301 UserManager getUserManager() {
1302 return UserManager.get(mContext);
1305 UserManagerInternal getUserManagerInternal() {
1306 return LocalServices.getService(UserManagerInternal.class);
1309 PackageManagerInternal getPackageManagerInternal() {
1310 return LocalServices.getService(PackageManagerInternal.class);
1313 NotificationManager getNotificationManager() {
1314 return mContext.getSystemService(NotificationManager.class);
1317 PowerManagerInternal getPowerManagerInternal() {
1318 return LocalServices.getService(PowerManagerInternal.class);
1321 IWindowManager getIWindowManager() {
1322 return IWindowManager.Stub
1323 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1326 IActivityManager getIActivityManager() {
1327 return ActivityManagerNative.getDefault();
1330 IPackageManager getIPackageManager() {
1331 return AppGlobals.getPackageManager();
1334 IBackupManager getIBackupManager() {
1335 return IBackupManager.Stub.asInterface(
1336 ServiceManager.getService(Context.BACKUP_SERVICE));
1339 IAudioService getIAudioService() {
1340 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1343 LockPatternUtils newLockPatternUtils() {
1344 return new LockPatternUtils(mContext);
1347 Looper getMyLooper() {
1348 return Looper.myLooper();
1351 WifiManager getWifiManager() {
1352 return mContext.getSystemService(WifiManager.class);
1355 long binderClearCallingIdentity() {
1356 return Binder.clearCallingIdentity();
1359 void binderRestoreCallingIdentity(long token) {
1360 Binder.restoreCallingIdentity(token);
1363 int binderGetCallingUid() {
1364 return Binder.getCallingUid();
1367 int binderGetCallingPid() {
1368 return Binder.getCallingPid();
1371 UserHandle binderGetCallingUserHandle() {
1372 return Binder.getCallingUserHandle();
1375 boolean binderIsCallingUidMyUid() {
1376 return getCallingUid() == Process.myUid();
1379 final int userHandleGetCallingUserId() {
1380 return UserHandle.getUserId(binderGetCallingUid());
1383 File environmentGetUserSystemDirectory(int userId) {
1384 return Environment.getUserSystemDirectory(userId);
1387 void powerManagerGoToSleep(long time, int reason, int flags) {
1388 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1391 void powerManagerReboot(String reason) {
1392 mContext.getSystemService(PowerManager.class).reboot(reason);
1395 boolean systemPropertiesGetBoolean(String key, boolean def) {
1396 return SystemProperties.getBoolean(key, def);
1399 long systemPropertiesGetLong(String key, long def) {
1400 return SystemProperties.getLong(key, def);
1403 String systemPropertiesGet(String key, String def) {
1404 return SystemProperties.get(key, def);
1407 String systemPropertiesGet(String key) {
1408 return SystemProperties.get(key);
1411 void systemPropertiesSet(String key, String value) {
1412 SystemProperties.set(key, value);
1415 boolean userManagerIsSplitSystemUser() {
1416 return UserManager.isSplitSystemUser();
1419 String getDevicePolicyFilePathForSystemUser() {
1420 return "/data/system/";
1423 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1424 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1425 name, def, userHandle);
1428 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1429 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1430 name, value, userHandle);
1433 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1434 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1435 name, value, userHandle);
1438 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1439 Settings.Global.putStringForUser(mContext.getContentResolver(),
1440 name, value, userHandle);
1443 void settingsSecurePutInt(String name, int value) {
1444 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1447 int settingsGlobalGetInt(String name, int def) {
1448 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1451 void settingsGlobalPutInt(String name, int value) {
1452 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1455 void settingsSecurePutString(String name, String value) {
1456 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1459 void settingsGlobalPutString(String name, String value) {
1460 Settings.Global.putString(mContext.getContentResolver(), name, value);
1463 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1464 SecurityLog.setLoggingEnabledProperty(enabled);
1469 * Instantiates the service.
1471 public DevicePolicyManagerService(Context context) {
1472 this(new Injector(context));
1476 DevicePolicyManagerService(Injector injector) {
1477 mInjector = injector;
1478 mContext = Preconditions.checkNotNull(injector.mContext);
1479 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1480 mOwners = Preconditions.checkNotNull(injector.newOwners());
1482 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1483 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1484 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1486 mLocalService = new LocalService();
1487 mLockPatternUtils = injector.newLockPatternUtils();
1489 mSecurityLogMonitor = new SecurityLogMonitor(this);
1491 mHasFeature = mContext.getPackageManager()
1492 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1494 // Skip the rest of the initialization
1497 IntentFilter filter = new IntentFilter();
1498 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1499 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1500 filter.addAction(Intent.ACTION_USER_ADDED);
1501 filter.addAction(Intent.ACTION_USER_REMOVED);
1502 filter.addAction(Intent.ACTION_USER_STARTED);
1503 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1504 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1505 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1506 filter = new IntentFilter();
1507 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1508 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1509 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1510 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1511 filter.addDataScheme("package");
1512 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1513 filter = new IntentFilter();
1514 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1515 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1517 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1521 * Creates and loads the policy data from xml.
1522 * @param userHandle the user for whom to load the policy data
1526 DevicePolicyData getUserData(int userHandle) {
1527 synchronized (this) {
1528 DevicePolicyData policy = mUserData.get(userHandle);
1529 if (policy == null) {
1530 policy = new DevicePolicyData(userHandle);
1531 mUserData.append(userHandle, policy);
1532 loadSettingsLocked(policy, userHandle);
1539 * Creates and loads the policy data from xml for data that is shared between
1540 * various profiles of a user. In contrast to {@link #getUserData(int)}
1541 * it allows access to data of users other than the calling user.
1543 * This function should only be used for shared data, e.g. everything regarding
1544 * passwords and should be removed once multiple screen locks are present.
1545 * @param userHandle the user for whom to load the policy data
1548 DevicePolicyData getUserDataUnchecked(int userHandle) {
1549 long ident = mInjector.binderClearCallingIdentity();
1551 return getUserData(userHandle);
1553 mInjector.binderRestoreCallingIdentity(ident);
1557 void removeUserData(int userHandle) {
1558 synchronized (this) {
1559 if (userHandle == UserHandle.USER_SYSTEM) {
1560 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1563 mOwners.removeProfileOwner(userHandle);
1564 mOwners.writeProfileOwner(userHandle);
1566 DevicePolicyData policy = mUserData.get(userHandle);
1567 if (policy != null) {
1568 mUserData.remove(userHandle);
1570 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1571 DEVICE_POLICIES_XML);
1572 policyFile.delete();
1573 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1575 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1579 synchronized (this) {
1581 setDeviceOwnerSystemPropertyLocked();
1582 findOwnerComponentIfNecessaryLocked();
1583 migrateUserRestrictionsIfNecessaryLocked();
1585 // TODO PO may not have a class name either due to b/17652534. Address that too.
1587 updateDeviceOwnerLocked();
1591 private void setDeviceOwnerSystemPropertyLocked() {
1592 // Device owner may still be provisioned, do not set the read-only system property yet.
1593 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1596 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1597 // always false at this point.
1598 if ("encrypted".equals(mInjector.systemPropertiesGet("ro.crypto.state"))
1599 && "trigger_restart_min_framework".equals(
1600 mInjector.systemPropertiesGet("vold.decrypt"))){
1604 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1605 Slog.wtf(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1607 if (mOwners.hasDeviceOwner()) {
1608 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1609 disableDeviceLoggingIfNotCompliant();
1610 if (SecurityLog.getLoggingEnabledProperty()) {
1611 mSecurityLogMonitor.start();
1614 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1619 private void findOwnerComponentIfNecessaryLocked() {
1620 if (!mOwners.hasDeviceOwner()) {
1623 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1625 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1626 return; // Already a full component name.
1629 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1630 doComponentName.getPackageName(),
1631 mOwners.getDeviceOwnerUserId());
1632 if (doComponent == null) {
1633 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1635 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1637 mOwners.getDeviceOwnerName(),
1638 mOwners.getDeviceOwnerUserId(),
1639 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1640 mOwners.writeDeviceOwner();
1642 Log.v(LOG_TAG, "Device owner component filled in");
1648 * We didn't use to persist user restrictions for each owners but only persisted in user
1651 private void migrateUserRestrictionsIfNecessaryLocked() {
1652 boolean migrated = false;
1653 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1654 // except for the "system controlled" ones.
1655 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1657 Log.v(LOG_TAG, "Migrating DO user restrictions");
1661 // Migrate user 0 restrictions to DO.
1662 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1664 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1665 /* exceptionList =*/ null);
1667 // Push DO user restrictions to user manager.
1668 pushUserRestrictions(UserHandle.USER_SYSTEM);
1670 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1673 // Migrate for POs. We have a few more exceptions.
1674 final Set<String> normalExceptionList = Sets.newArraySet(
1675 UserManager.DISALLOW_OUTGOING_CALLS,
1676 UserManager.DISALLOW_SMS);
1678 final Set<String> managedExceptionList = new ArraySet<>(normalExceptionList.size() + 1);
1679 managedExceptionList.addAll(normalExceptionList);
1680 managedExceptionList.add(UserManager.DISALLOW_WALLPAPER);
1682 for (UserInfo ui : mUserManager.getUsers()) {
1683 final int userId = ui.id;
1684 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1685 if (userId != UserHandle.USER_SYSTEM) {
1687 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1691 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1693 final Set<String> exceptionList =
1694 ui.isManagedProfile() ? managedExceptionList : normalExceptionList;
1696 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1699 // Note if a secondary user has no PO but has a DA that disables camera, we
1700 // don't get here and won't push the camera user restriction to UserManager
1701 // here. That's okay because we'll push user restrictions anyway when a user
1702 // starts. But we still do it because we want to let user manager persist
1704 pushUserRestrictions(userId);
1707 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1710 if (VERBOSE_LOG && migrated) {
1711 Log.v(LOG_TAG, "User restrictions migrated.");
1715 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1716 Set<String> exceptionList) {
1717 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1718 user.getIdentifier());
1720 final Bundle newBaseRestrictions = new Bundle();
1721 final Bundle newOwnerRestrictions = new Bundle();
1723 for (String key : origRestrictions.keySet()) {
1724 if (!origRestrictions.getBoolean(key)) {
1727 if (exceptionList!= null && exceptionList.contains(key)) {
1728 newBaseRestrictions.putBoolean(key, true);
1730 newOwnerRestrictions.putBoolean(key, true);
1735 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1736 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1737 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1739 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1740 newBaseRestrictions);
1742 if (admin != null) {
1743 admin.ensureUserRestrictions().clear();
1744 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1746 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1748 saveSettingsLocked(user.getIdentifier());
1751 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1752 final DevicePolicyData policy = getUserData(userId);
1753 final int n = policy.mAdminList.size();
1754 ComponentName found = null;
1756 for (int i = 0; i < n; i++) {
1757 final ActiveAdmin admin = policy.mAdminList.get(i);
1758 if (packageName.equals(admin.info.getPackageName())) {
1761 found = admin.info.getComponent();
1767 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1773 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1774 * reminders. Clears alarm if no expirations are configured.
1776 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1777 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1778 final long now = System.currentTimeMillis();
1779 final long timeToExpire = expiration - now;
1780 final long alarmTime;
1781 if (expiration == 0) {
1782 // No expirations are currently configured: Cancel alarm.
1784 } else if (timeToExpire <= 0) {
1785 // The password has already expired: Repeat every 24 hours.
1786 alarmTime = now + MS_PER_DAY;
1788 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1789 // the expiration time.
1790 long alarmInterval = timeToExpire % MS_PER_DAY;
1791 if (alarmInterval == 0) {
1792 alarmInterval = MS_PER_DAY;
1794 alarmTime = now + alarmInterval;
1797 long token = mInjector.binderClearCallingIdentity();
1799 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1800 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1801 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1802 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1803 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1804 UserHandle.of(affectedUserHandle));
1806 if (alarmTime != 0) {
1807 am.set(AlarmManager.RTC, alarmTime, pi);
1810 mInjector.binderRestoreCallingIdentity(token);
1814 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1815 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1817 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1818 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1824 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
1826 enforceManagedProfile(userHandle, "call APIs on the parent profile");
1828 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1829 if (admin != null && parent) {
1830 admin = admin.getParentActiveAdmin();
1835 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1836 throws SecurityException {
1837 final int callingUid = mInjector.binderGetCallingUid();
1839 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1840 if (result != null) {
1845 final int userId = UserHandle.getUserId(callingUid);
1846 final DevicePolicyData policy = getUserData(userId);
1847 ActiveAdmin admin = policy.mAdminMap.get(who);
1848 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1849 throw new SecurityException("Admin " + admin.info.getComponent()
1850 + " does not own the device");
1852 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1853 throw new SecurityException("Admin " + admin.info.getComponent()
1854 + " does not own the profile");
1856 throw new SecurityException("Admin " + admin.info.getComponent()
1857 + " did not specify uses-policy for: "
1858 + admin.info.getTagForPolicy(reqPolicy));
1860 throw new SecurityException("No active admin owned by uid "
1861 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
1865 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
1866 throws SecurityException {
1868 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
1869 "call APIs on the parent profile");
1871 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
1872 return parent ? admin.getParentActiveAdmin() : admin;
1875 * Find the admin for the component and userId bit of the uid, then check
1876 * the admin's uid matches the uid.
1878 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
1879 final int userId = UserHandle.getUserId(uid);
1880 final DevicePolicyData policy = getUserData(userId);
1881 ActiveAdmin admin = policy.mAdminMap.get(who);
1882 if (admin == null) {
1883 throw new SecurityException("No active admin " + who);
1885 if (admin.getUid() != uid) {
1886 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1891 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
1893 // Try to find an admin which can use reqPolicy
1894 final int userId = UserHandle.getUserId(uid);
1895 final DevicePolicyData policy = getUserData(userId);
1897 ActiveAdmin admin = policy.mAdminMap.get(who);
1898 if (admin == null) {
1899 throw new SecurityException("No active admin " + who);
1901 if (admin.getUid() != uid) {
1902 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1904 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
1908 for (ActiveAdmin admin : policy.mAdminList) {
1909 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
1920 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
1922 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
1923 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
1925 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1927 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1928 // DO always has the PO power.
1929 return ownsDevice || ownsProfile;
1931 return admin.info.usesPolicy(reqPolicy);
1935 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
1936 sendAdminCommandLocked(admin, action, null);
1939 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
1940 sendAdminCommandLocked(admin, action, null, result);
1944 * Send an update to one specific admin, get notified when that admin returns a result.
1946 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
1947 BroadcastReceiver result) {
1948 Intent intent = new Intent(action);
1949 intent.setComponent(admin.info.getComponent());
1950 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
1951 intent.putExtra("expiration", admin.passwordExpirationDate);
1953 if (adminExtras != null) {
1954 intent.putExtras(adminExtras);
1956 if (result != null) {
1957 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
1958 null, result, mHandler, Activity.RESULT_OK, null, null);
1960 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
1965 * Send an update to all admins of a user that enforce a specified policy.
1967 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
1968 final DevicePolicyData policy = getUserData(userHandle);
1969 final int count = policy.mAdminList.size();
1971 for (int i = 0; i < count; i++) {
1972 final ActiveAdmin admin = policy.mAdminList.get(i);
1973 if (admin.info.usesPolicy(reqPolicy)) {
1974 sendAdminCommandLocked(admin, action);
1981 * Send an update intent to all admins of a user and its profiles. Only send to admins that
1982 * enforce a specified policy.
1984 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
1986 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1987 for (UserInfo ui : profiles) {
1989 sendAdminCommandLocked(action, reqPolicy, id);
1994 * Sends a broadcast to each profile that share the password unlock with the given user id.
1996 private void sendAdminCommandForLockscreenPoliciesLocked(
1997 String action, int reqPolicy, int userHandle) {
1998 if (isSeparateProfileChallengeEnabled(userHandle)) {
1999 sendAdminCommandLocked(action, reqPolicy, userHandle);
2001 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2005 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2006 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2007 if (admin != null) {
2008 synchronized (this) {
2009 getUserData(userHandle).mRemovingAdmins.add(adminReceiver);
2011 sendAdminCommandLocked(admin,
2012 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2013 new BroadcastReceiver() {
2015 public void onReceive(Context context, Intent intent) {
2016 synchronized (DevicePolicyManagerService.this) {
2017 int userHandle = admin.getUserHandle().getIdentifier();
2018 DevicePolicyData policy = getUserData(userHandle);
2019 boolean doProxyCleanup = admin.info.usesPolicy(
2020 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
2021 policy.mAdminList.remove(admin);
2022 policy.mAdminMap.remove(adminReceiver);
2023 validatePasswordOwnerLocked(policy);
2024 if (doProxyCleanup) {
2025 resetGlobalProxyLocked(getUserData(userHandle));
2027 saveSettingsLocked(userHandle);
2028 updateMaximumTimeToLockLocked(userHandle);
2029 policy.mRemovingAdmins.remove(adminReceiver);
2031 // The removed admin might have disabled camera, so update user
2033 pushUserRestrictions(userHandle);
2039 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2040 boolean throwForMissiongPermission) {
2044 enforceFullCrossUsersPermission(userHandle);
2045 Intent resolveIntent = new Intent();
2046 resolveIntent.setComponent(adminName);
2047 List<ResolveInfo> infos = mContext.getPackageManager().queryBroadcastReceiversAsUser(
2049 PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
2051 if (infos == null || infos.size() <= 0) {
2052 throw new IllegalArgumentException("Unknown admin: " + adminName);
2055 final ResolveInfo ri = infos.get(0);
2057 if (!permission.BIND_DEVICE_ADMIN.equals(ri.activityInfo.permission)) {
2058 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2059 + permission.BIND_DEVICE_ADMIN;
2060 Slog.w(LOG_TAG, message);
2061 if (throwForMissiongPermission &&
2062 ri.activityInfo.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2063 throw new IllegalArgumentException(message);
2068 return new DeviceAdminInfo(mContext, ri);
2069 } catch (XmlPullParserException | IOException e) {
2070 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2076 private JournaledFile makeJournaledFile(int userHandle) {
2077 final String base = userHandle == UserHandle.USER_SYSTEM
2078 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2079 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2080 DEVICE_POLICIES_XML).getAbsolutePath();
2082 Log.v(LOG_TAG, "Opening " + base);
2084 return new JournaledFile(new File(base), new File(base + ".tmp"));
2087 private void saveSettingsLocked(int userHandle) {
2088 DevicePolicyData policy = getUserData(userHandle);
2089 JournaledFile journal = makeJournaledFile(userHandle);
2090 FileOutputStream stream = null;
2092 stream = new FileOutputStream(journal.chooseForWrite(), false);
2093 XmlSerializer out = new FastXmlSerializer();
2094 out.setOutput(stream, StandardCharsets.UTF_8.name());
2095 out.startDocument(null, true);
2097 out.startTag(null, "policies");
2098 if (policy.mRestrictionsProvider != null) {
2099 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2100 policy.mRestrictionsProvider.flattenToString());
2102 if (policy.mUserSetupComplete) {
2103 out.attribute(null, ATTR_SETUP_COMPLETE,
2104 Boolean.toString(true));
2106 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2107 out.attribute(null, ATTR_PROVISIONING_STATE,
2108 Integer.toString(policy.mUserProvisioningState));
2110 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2111 out.attribute(null, ATTR_PERMISSION_POLICY,
2112 Integer.toString(policy.mPermissionPolicy));
2114 if (policy.mDelegatedCertInstallerPackage != null) {
2115 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2116 policy.mDelegatedCertInstallerPackage);
2118 if (policy.mApplicationRestrictionsManagingPackage != null) {
2119 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2120 policy.mApplicationRestrictionsManagingPackage);
2123 final int N = policy.mAdminList.size();
2124 for (int i=0; i<N; i++) {
2125 ActiveAdmin ap = policy.mAdminList.get(i);
2127 out.startTag(null, "admin");
2128 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2130 out.endTag(null, "admin");
2134 if (policy.mPasswordOwner >= 0) {
2135 out.startTag(null, "password-owner");
2136 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2137 out.endTag(null, "password-owner");
2140 if (policy.mFailedPasswordAttempts != 0) {
2141 out.startTag(null, "failed-password-attempts");
2142 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2143 out.endTag(null, "failed-password-attempts");
2146 if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2147 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2148 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2149 || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
2150 out.startTag(null, "active-password");
2151 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2152 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2153 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2154 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2155 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2156 out.attribute(null, "numeric", Integer
2157 .toString(policy.mActivePasswordNumeric));
2158 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2159 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2160 out.endTag(null, "active-password");
2163 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2164 String component = policy.mLockTaskPackages.get(i);
2165 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2166 out.attribute(null, "name", component);
2167 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2170 if (policy.mStatusBarDisabled) {
2171 out.startTag(null, TAG_STATUS_BAR);
2172 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2173 out.endTag(null, TAG_STATUS_BAR);
2176 if (policy.doNotAskCredentialsOnBoot) {
2177 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2178 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2181 for (String id : policy.mAffiliationIds) {
2182 out.startTag(null, TAG_AFFILIATION_ID);
2183 out.attribute(null, "id", id);
2184 out.endTag(null, TAG_AFFILIATION_ID);
2187 if (policy.mAdminBroadcastPending) {
2188 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2189 out.attribute(null, ATTR_VALUE,
2190 Boolean.toString(policy.mAdminBroadcastPending));
2191 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2194 if (policy.mInitBundle != null) {
2195 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2196 policy.mInitBundle.saveToXml(out);
2197 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2200 out.endTag(null, "policies");
2204 FileUtils.sync(stream);
2207 sendChangedNotification(userHandle);
2208 } catch (XmlPullParserException | IOException e) {
2209 Slog.w(LOG_TAG, "failed writing file", e);
2211 if (stream != null) {
2214 } catch (IOException ex) {
2221 private void sendChangedNotification(int userHandle) {
2222 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2223 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2224 long ident = mInjector.binderClearCallingIdentity();
2226 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2228 mInjector.binderRestoreCallingIdentity(ident);
2232 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2233 JournaledFile journal = makeJournaledFile(userHandle);
2234 FileInputStream stream = null;
2235 File file = journal.chooseForRead();
2237 stream = new FileInputStream(file);
2238 XmlPullParser parser = Xml.newPullParser();
2239 parser.setInput(stream, StandardCharsets.UTF_8.name());
2242 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2243 && type != XmlPullParser.START_TAG) {
2245 String tag = parser.getName();
2246 if (!"policies".equals(tag)) {
2247 throw new XmlPullParserException(
2248 "Settings do not start with policies tag: found " + tag);
2251 // Extract the permission provider component name if available
2252 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2253 if (permissionProvider != null) {
2254 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2256 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2257 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2258 policy.mUserSetupComplete = true;
2260 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2261 if (!TextUtils.isEmpty(provisioningState)) {
2262 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2264 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2265 if (!TextUtils.isEmpty(permissionPolicy)) {
2266 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2268 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2269 ATTR_DELEGATED_CERT_INSTALLER);
2270 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2271 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2273 type = parser.next();
2274 int outerDepth = parser.getDepth();
2275 policy.mLockTaskPackages.clear();
2276 policy.mAdminList.clear();
2277 policy.mAdminMap.clear();
2278 policy.mAffiliationIds.clear();
2279 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2280 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2281 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2284 tag = parser.getName();
2285 if ("admin".equals(tag)) {
2286 String name = parser.getAttributeValue(null, "name");
2288 DeviceAdminInfo dai = findAdmin(
2289 ComponentName.unflattenFromString(name), userHandle,
2290 /* throwForMissionPermission= */ false);
2292 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2294 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2295 + dai.getActivityInfo().applicationInfo.uid + " for user "
2299 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2300 ap.readFromXml(parser);
2301 policy.mAdminMap.put(ap.info.getComponent(), ap);
2303 } catch (RuntimeException e) {
2304 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2306 } else if ("failed-password-attempts".equals(tag)) {
2307 policy.mFailedPasswordAttempts = Integer.parseInt(
2308 parser.getAttributeValue(null, "value"));
2309 } else if ("password-owner".equals(tag)) {
2310 policy.mPasswordOwner = Integer.parseInt(
2311 parser.getAttributeValue(null, "value"));
2312 } else if ("active-password".equals(tag)) {
2313 policy.mActivePasswordQuality = Integer.parseInt(
2314 parser.getAttributeValue(null, "quality"));
2315 policy.mActivePasswordLength = Integer.parseInt(
2316 parser.getAttributeValue(null, "length"));
2317 policy.mActivePasswordUpperCase = Integer.parseInt(
2318 parser.getAttributeValue(null, "uppercase"));
2319 policy.mActivePasswordLowerCase = Integer.parseInt(
2320 parser.getAttributeValue(null, "lowercase"));
2321 policy.mActivePasswordLetters = Integer.parseInt(
2322 parser.getAttributeValue(null, "letters"));
2323 policy.mActivePasswordNumeric = Integer.parseInt(
2324 parser.getAttributeValue(null, "numeric"));
2325 policy.mActivePasswordSymbols = Integer.parseInt(
2326 parser.getAttributeValue(null, "symbols"));
2327 policy.mActivePasswordNonLetter = Integer.parseInt(
2328 parser.getAttributeValue(null, "nonletter"));
2329 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2330 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2331 } else if (TAG_STATUS_BAR.equals(tag)) {
2332 policy.mStatusBarDisabled = Boolean.parseBoolean(
2333 parser.getAttributeValue(null, ATTR_DISABLED));
2334 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2335 policy.doNotAskCredentialsOnBoot = true;
2336 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2337 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2338 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2339 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2340 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2341 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2342 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2344 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2345 XmlUtils.skipCurrentTag(parser);
2348 } catch (FileNotFoundException e) {
2349 // Don't be noisy, this is normal if we haven't defined any policies.
2350 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2351 | IndexOutOfBoundsException e) {
2352 Slog.w(LOG_TAG, "failed parsing " + file, e);
2355 if (stream != null) {
2358 } catch (IOException e) {
2362 // Generate a list of admins from the admin map
2363 policy.mAdminList.addAll(policy.mAdminMap.values());
2365 // Validate that what we stored for the password quality matches
2366 // sufficiently what is currently set. Note that this is only
2367 // a sanity check in case the two get out of sync; this should
2368 // never normally happen.
2369 final long identity = mInjector.binderClearCallingIdentity();
2371 int actualPasswordQuality = mLockPatternUtils.getActivePasswordQuality(userHandle);
2372 if (actualPasswordQuality < policy.mActivePasswordQuality) {
2373 Slog.w(LOG_TAG, "Active password quality 0x"
2374 + Integer.toHexString(policy.mActivePasswordQuality)
2375 + " does not match actual quality 0x"
2376 + Integer.toHexString(actualPasswordQuality));
2377 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2378 policy.mActivePasswordLength = 0;
2379 policy.mActivePasswordUpperCase = 0;
2380 policy.mActivePasswordLowerCase = 0;
2381 policy.mActivePasswordLetters = 0;
2382 policy.mActivePasswordNumeric = 0;
2383 policy.mActivePasswordSymbols = 0;
2384 policy.mActivePasswordNonLetter = 0;
2387 mInjector.binderRestoreCallingIdentity(identity);
2390 validatePasswordOwnerLocked(policy);
2391 updateMaximumTimeToLockLocked(userHandle);
2392 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2393 if (policy.mStatusBarDisabled) {
2394 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2398 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2399 long ident = mInjector.binderClearCallingIdentity();
2401 mInjector.getIActivityManager()
2402 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2403 } catch (RemoteException e) {
2404 // Not gonna happen.
2406 mInjector.binderRestoreCallingIdentity(ident);
2410 private void updateDeviceOwnerLocked() {
2411 long ident = mInjector.binderClearCallingIdentity();
2413 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2414 // user id and also protect all other DAs too.
2415 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2416 if (deviceOwnerComponent != null) {
2417 mInjector.getIActivityManager()
2418 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2420 } catch (RemoteException e) {
2421 // Not gonna happen.
2423 mInjector.binderRestoreCallingIdentity(ident);
2427 static void validateQualityConstant(int quality) {
2429 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2430 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2431 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2432 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2433 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2434 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2435 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2436 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2437 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2440 throw new IllegalArgumentException("Invalid quality constant: 0x"
2441 + Integer.toHexString(quality));
2444 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2445 if (policy.mPasswordOwner >= 0) {
2446 boolean haveOwner = false;
2447 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2448 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2454 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2455 + " no longer active; disabling");
2456 policy.mPasswordOwner = -1;
2462 void systemReady(int phase) {
2467 case SystemService.PHASE_LOCK_SETTINGS_READY:
2468 onLockSettingsReady();
2470 case SystemService.PHASE_BOOT_COMPLETED:
2471 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2476 private void onLockSettingsReady() {
2477 getUserData(UserHandle.USER_SYSTEM);
2481 onStartUser(UserHandle.USER_SYSTEM);
2483 // Register an observer for watching for user setup complete.
2484 new SetupContentObserver(mHandler).register(mContext.getContentResolver());
2485 // Initialize the user setup state, to handle the upgrade case.
2486 updateUserSetupComplete();
2488 List<String> packageList;
2489 synchronized (this) {
2490 packageList = getKeepUninstalledPackagesLocked();
2492 if (packageList != null) {
2493 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2496 synchronized (this) {
2497 // push the force-ephemeral-users policy to the user manager.
2498 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2499 if (deviceOwner != null) {
2500 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2505 private void ensureDeviceOwnerUserStarted() {
2507 synchronized (this) {
2508 if (!mOwners.hasDeviceOwner()) {
2511 userId = mOwners.getDeviceOwnerUserId();
2514 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2516 if (userId != UserHandle.USER_SYSTEM) {
2518 mInjector.getIActivityManager().startUserInBackground(userId);
2520 // STOPSHIP Prevent the DO user from being killed.
2522 } catch (RemoteException e) {
2523 Slog.w(LOG_TAG, "Exception starting user", e);
2528 private void onStartUser(int userId) {
2529 updateScreenCaptureDisabledInWindowManager(userId,
2530 getScreenCaptureDisabled(null, userId));
2531 pushUserRestrictions(userId);
2534 private void cleanUpOldUsers() {
2535 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2537 Set<Integer> usersWithProfileOwners;
2538 Set<Integer> usersWithData;
2539 synchronized(this) {
2540 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2541 usersWithData = new ArraySet<>();
2542 for (int i = 0; i < mUserData.size(); i++) {
2543 usersWithData.add(mUserData.keyAt(i));
2546 List<UserInfo> allUsers = mUserManager.getUsers();
2548 Set<Integer> deletedUsers = new ArraySet<>();
2549 deletedUsers.addAll(usersWithProfileOwners);
2550 deletedUsers.addAll(usersWithData);
2551 for (UserInfo userInfo : allUsers) {
2552 deletedUsers.remove(userInfo.id);
2554 for (Integer userId : deletedUsers) {
2555 removeUserData(userId);
2559 private void handlePasswordExpirationNotification(int userHandle) {
2560 synchronized (this) {
2561 final long now = System.currentTimeMillis();
2563 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2564 userHandle, /* parent */ false);
2565 final int N = admins.size();
2566 for (int i = 0; i < N; i++) {
2567 ActiveAdmin admin = admins.get(i);
2568 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2569 && admin.passwordExpirationTimeout > 0L
2570 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2571 && admin.passwordExpirationDate > 0L) {
2572 sendAdminCommandLocked(admin,
2573 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2576 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2580 private class MonitoringCertNotificationTask extends AsyncTask<Intent, Void, Void> {
2582 protected Void doInBackground(Intent... params) {
2583 int userHandle = params[0].getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
2585 if (userHandle == UserHandle.USER_ALL) {
2586 for (UserInfo userInfo : mUserManager.getUsers()) {
2587 manageNotification(userInfo.getUserHandle());
2590 manageNotification(new UserHandle(userHandle));
2595 private void manageNotification(UserHandle userHandle) {
2596 if (!mUserManager.isUserRunning(userHandle)) {
2600 // Call out to KeyChain to check for user-added CAs
2601 boolean hasCert = false;
2603 KeyChainConnection kcs = KeyChain.bindAsUser(mContext, userHandle);
2605 if (!kcs.getService().getUserCaAliases().getList().isEmpty()) {
2608 } catch (RemoteException e) {
2609 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
2613 } catch (InterruptedException e) {
2614 Thread.currentThread().interrupt();
2615 } catch (RuntimeException e) {
2616 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
2619 mInjector.getNotificationManager().cancelAsUser(
2620 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2624 // Build and show a warning notification
2627 // TODO Why does it use the DO name? The cert APIs are all for PO. b/25772443
2628 final String ownerName = getDeviceOwnerName();
2629 if (isManagedProfile(userHandle.getIdentifier())) {
2630 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_administrator);
2631 smallIconId = R.drawable.stat_sys_certificate_info;
2632 } else if (ownerName != null) {
2633 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, ownerName);
2634 smallIconId = R.drawable.stat_sys_certificate_info;
2636 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2637 smallIconId = android.R.drawable.stat_sys_warning;
2640 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2641 dialogIntent.setFlags(
2642 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2643 dialogIntent.setPackage("com.android.settings");
2644 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2645 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, userHandle);
2647 final Context userContext;
2649 userContext = mContext.createPackageContextAsUser("android", 0, userHandle);
2650 } catch (PackageManager.NameNotFoundException e) {
2651 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2654 final Notification noti = new Notification.Builder(userContext)
2655 .setSmallIcon(smallIconId)
2656 .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning))
2657 .setContentText(contentText)
2658 .setContentIntent(notifyIntent)
2659 .setPriority(Notification.PRIORITY_HIGH)
2661 .setColor(mContext.getColor(
2662 com.android.internal.R.color.system_notification_accent_color))
2665 mInjector.getNotificationManager().notifyAsUser(
2666 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2671 * @param adminReceiver The admin to add
2672 * @param refreshing true = update an active admin, no error
2675 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2679 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2682 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2683 Bundle onEnableData) {
2684 mContext.enforceCallingOrSelfPermission(
2685 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2686 enforceFullCrossUsersPermission(userHandle);
2688 DevicePolicyData policy = getUserData(userHandle);
2689 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2690 /* throwForMissionPermission= */ true);
2692 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2694 synchronized (this) {
2695 long ident = mInjector.binderClearCallingIdentity();
2698 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
2699 throw new IllegalArgumentException("Admin is already added");
2701 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2702 policy.mAdminMap.put(adminReceiver, newAdmin);
2703 int replaceIndex = -1;
2704 final int N = policy.mAdminList.size();
2705 for (int i=0; i < N; i++) {
2706 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2707 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2712 if (replaceIndex == -1) {
2713 policy.mAdminList.add(newAdmin);
2714 enableIfNecessary(info.getPackageName(), userHandle);
2716 policy.mAdminList.set(replaceIndex, newAdmin);
2718 saveSettingsLocked(userHandle);
2719 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2720 onEnableData, null);
2722 mInjector.binderRestoreCallingIdentity(ident);
2728 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2732 enforceFullCrossUsersPermission(userHandle);
2733 synchronized (this) {
2734 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2739 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2743 enforceFullCrossUsersPermission(userHandle);
2744 synchronized (this) {
2745 DevicePolicyData policyData = getUserData(userHandle);
2746 return policyData.mRemovingAdmins.contains(adminReceiver);
2751 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2755 enforceFullCrossUsersPermission(userHandle);
2756 synchronized (this) {
2757 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2758 if (administrator == null) {
2759 throw new SecurityException("No active admin " + adminReceiver);
2761 return administrator.info.usesPolicy(policyId);
2766 @SuppressWarnings("unchecked")
2767 public List<ComponentName> getActiveAdmins(int userHandle) {
2769 return Collections.EMPTY_LIST;
2772 enforceFullCrossUsersPermission(userHandle);
2773 synchronized (this) {
2774 DevicePolicyData policy = getUserData(userHandle);
2775 final int N = policy.mAdminList.size();
2779 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2780 for (int i=0; i<N; i++) {
2781 res.add(policy.mAdminList.get(i).info.getComponent());
2788 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2792 enforceFullCrossUsersPermission(userHandle);
2793 synchronized (this) {
2794 DevicePolicyData policy = getUserData(userHandle);
2795 final int N = policy.mAdminList.size();
2796 for (int i=0; i<N; i++) {
2797 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2806 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
2810 enforceFullCrossUsersPermission(userHandle);
2811 synchronized (this) {
2812 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2813 if (admin == null) {
2816 if (admin.getUid() != mInjector.binderGetCallingUid()) {
2817 // Active device/profile owners must remain active admins.
2818 if (isDeviceOwner(adminReceiver, userHandle)
2819 || isProfileOwner(adminReceiver, userHandle)) {
2820 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
2824 mContext.enforceCallingOrSelfPermission(
2825 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2827 long ident = mInjector.binderClearCallingIdentity();
2829 removeActiveAdminLocked(adminReceiver, userHandle);
2831 mInjector.binderRestoreCallingIdentity(ident);
2836 private boolean isAdminApiLevelMOrBelow(@NonNull ComponentName who, int userHandle) {
2837 DeviceAdminInfo adminInfo = findAdmin(who, userHandle, false);
2838 return adminInfo.getActivityInfo().applicationInfo.targetSdkVersion
2839 <= Build.VERSION_CODES.M;
2843 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
2844 ComponentName profileOwner = getProfileOwner(userHandle);
2845 return profileOwner != null && !isAdminApiLevelMOrBelow(profileOwner, userHandle);
2849 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
2853 Preconditions.checkNotNull(who, "ComponentName is null");
2854 validateQualityConstant(quality);
2856 synchronized (this) {
2857 ActiveAdmin ap = getActiveAdminForCallerLocked(
2858 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
2859 if (ap.passwordQuality != quality) {
2860 ap.passwordQuality = quality;
2861 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
2867 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
2869 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2871 enforceFullCrossUsersPermission(userHandle);
2872 synchronized (this) {
2873 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2876 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
2877 return admin != null ? admin.passwordQuality : mode;
2880 // Return the strictest policy across all participating admins.
2881 List<ActiveAdmin> admins =
2882 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
2883 final int N = admins.size();
2884 for (int i = 0; i < N; i++) {
2885 ActiveAdmin admin = admins.get(i);
2886 if (mode < admin.passwordQuality) {
2887 mode = admin.passwordQuality;
2894 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
2895 int userHandle, boolean parent) {
2896 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
2897 // If this user has a separate challenge, only return its restrictions.
2898 return getUserDataUnchecked(userHandle).mAdminList;
2900 // Return all admins for this user and the profiles that are visible from this
2901 // user that do not use a separate work challenge.
2902 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
2903 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
2904 DevicePolicyData policy = getUserData(userInfo.id);
2905 if (!isManagedProfile(userInfo.id)) {
2906 admins.addAll(policy.mAdminList);
2908 // For managed profiles, we always include the policies set on the parent
2909 // profile. Additionally, we include the ones set on the managed profile
2910 // if no separate challenge is in place.
2911 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
2912 final int N = policy.mAdminList.size();
2913 for (int i = 0; i < N; i++) {
2914 ActiveAdmin admin = policy.mAdminList.get(i);
2915 if (admin.hasParentActiveAdmin()) {
2916 admins.add(admin.getParentActiveAdmin());
2918 if (!hasSeparateChallenge) {
2928 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
2929 long ident = mInjector.binderClearCallingIdentity();
2931 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
2933 mInjector.binderRestoreCallingIdentity(ident);
2938 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
2942 Preconditions.checkNotNull(who, "ComponentName is null");
2943 synchronized (this) {
2944 ActiveAdmin ap = getActiveAdminForCallerLocked(
2945 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
2946 if (ap.minimumPasswordLength != length) {
2947 ap.minimumPasswordLength = length;
2948 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
2954 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
2958 enforceFullCrossUsersPermission(userHandle);
2959 synchronized (this) {
2963 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
2964 return admin != null ? admin.minimumPasswordLength : length;
2967 // Return the strictest policy across all participating admins.
2968 List<ActiveAdmin> admins =
2969 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
2970 final int N = admins.size();
2971 for (int i = 0; i < N; i++) {
2972 ActiveAdmin admin = admins.get(i);
2973 if (length < admin.minimumPasswordLength) {
2974 length = admin.minimumPasswordLength;
2982 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
2986 Preconditions.checkNotNull(who, "ComponentName is null");
2987 synchronized (this) {
2988 ActiveAdmin ap = getActiveAdminForCallerLocked(
2989 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
2990 if (ap.passwordHistoryLength != length) {
2991 ap.passwordHistoryLength = length;
2992 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
2998 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3002 enforceFullCrossUsersPermission(userHandle);
3003 synchronized (this) {
3007 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3008 return admin != null ? admin.passwordHistoryLength : length;
3011 // Return the strictest policy across all participating admins.
3012 List<ActiveAdmin> admins =
3013 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3014 final int N = admins.size();
3015 for (int i = 0; i < N; i++) {
3016 ActiveAdmin admin = admins.get(i);
3017 if (length < admin.passwordHistoryLength) {
3018 length = admin.passwordHistoryLength;
3027 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3031 Preconditions.checkNotNull(who, "ComponentName is null");
3032 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3033 final int userHandle = mInjector.userHandleGetCallingUserId();
3034 synchronized (this) {
3035 ActiveAdmin ap = getActiveAdminForCallerLocked(
3036 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3037 // Calling this API automatically bumps the expiration date
3038 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3039 ap.passwordExpirationDate = expiration;
3040 ap.passwordExpirationTimeout = timeout;
3042 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3043 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3044 .format(new Date(expiration)));
3046 saveSettingsLocked(userHandle);
3048 // in case this is the first one, set the alarm on the appropriate user.
3049 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3054 * Return a single admin's expiration cycle time, or the min of all cycle times.
3055 * Returns 0 if not configured.
3058 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3062 enforceFullCrossUsersPermission(userHandle);
3063 synchronized (this) {
3067 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3068 return admin != null ? admin.passwordExpirationTimeout : timeout;
3071 // Return the strictest policy across all participating admins.
3072 List<ActiveAdmin> admins =
3073 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3074 final int N = admins.size();
3075 for (int i = 0; i < N; i++) {
3076 ActiveAdmin admin = admins.get(i);
3077 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3078 && timeout > admin.passwordExpirationTimeout)) {
3079 timeout = admin.passwordExpirationTimeout;
3087 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3088 final int userId = UserHandle.getCallingUserId();
3089 List<String> changedProviders = null;
3091 synchronized (this) {
3092 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3093 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3094 if (activeAdmin.crossProfileWidgetProviders == null) {
3095 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3097 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3098 if (!providers.contains(packageName)) {
3099 providers.add(packageName);
3100 changedProviders = new ArrayList<>(providers);
3101 saveSettingsLocked(userId);
3105 if (changedProviders != null) {
3106 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3114 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3115 final int userId = UserHandle.getCallingUserId();
3116 List<String> changedProviders = null;
3118 synchronized (this) {
3119 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3120 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3121 if (activeAdmin.crossProfileWidgetProviders == null) {
3124 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3125 if (providers.remove(packageName)) {
3126 changedProviders = new ArrayList<>(providers);
3127 saveSettingsLocked(userId);
3131 if (changedProviders != null) {
3132 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3140 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3141 synchronized (this) {
3142 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3143 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3144 if (activeAdmin.crossProfileWidgetProviders == null
3145 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3148 if (mInjector.binderIsCallingUidMyUid()) {
3149 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3151 return activeAdmin.crossProfileWidgetProviders;
3157 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3158 * Returns 0 if not configured.
3160 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3164 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3165 return admin != null ? admin.passwordExpirationDate : timeout;
3168 // Return the strictest policy across all participating admins.
3169 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3170 final int N = admins.size();
3171 for (int i = 0; i < N; i++) {
3172 ActiveAdmin admin = admins.get(i);
3173 if (timeout == 0L || (admin.passwordExpirationDate != 0
3174 && timeout > admin.passwordExpirationDate)) {
3175 timeout = admin.passwordExpirationDate;
3182 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3186 enforceFullCrossUsersPermission(userHandle);
3187 synchronized (this) {
3188 return getPasswordExpirationLocked(who, userHandle, parent);
3193 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3197 Preconditions.checkNotNull(who, "ComponentName is null");
3198 synchronized (this) {
3199 ActiveAdmin ap = getActiveAdminForCallerLocked(
3200 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3201 if (ap.minimumPasswordUpperCase != length) {
3202 ap.minimumPasswordUpperCase = length;
3203 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3209 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3213 enforceFullCrossUsersPermission(userHandle);
3214 synchronized (this) {
3218 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3219 return admin != null ? admin.minimumPasswordUpperCase : length;
3222 // Return the strictest policy across all participating admins.
3223 List<ActiveAdmin> admins =
3224 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3225 final int N = admins.size();
3226 for (int i = 0; i < N; i++) {
3227 ActiveAdmin admin = admins.get(i);
3228 if (length < admin.minimumPasswordUpperCase) {
3229 length = admin.minimumPasswordUpperCase;
3237 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3238 Preconditions.checkNotNull(who, "ComponentName is null");
3239 synchronized (this) {
3240 ActiveAdmin ap = getActiveAdminForCallerLocked(
3241 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3242 if (ap.minimumPasswordLowerCase != length) {
3243 ap.minimumPasswordLowerCase = length;
3244 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3250 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3254 enforceFullCrossUsersPermission(userHandle);
3255 synchronized (this) {
3259 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3260 return admin != null ? admin.minimumPasswordLowerCase : length;
3263 // Return the strictest policy across all participating admins.
3264 List<ActiveAdmin> admins =
3265 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3266 final int N = admins.size();
3267 for (int i = 0; i < N; i++) {
3268 ActiveAdmin admin = admins.get(i);
3269 if (length < admin.minimumPasswordLowerCase) {
3270 length = admin.minimumPasswordLowerCase;
3278 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3282 Preconditions.checkNotNull(who, "ComponentName is null");
3283 synchronized (this) {
3284 ActiveAdmin ap = getActiveAdminForCallerLocked(
3285 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3286 if (ap.minimumPasswordLetters != length) {
3287 ap.minimumPasswordLetters = length;
3288 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3294 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3298 enforceFullCrossUsersPermission(userHandle);
3299 synchronized (this) {
3303 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3304 return admin != null ? admin.minimumPasswordLetters : length;
3307 // Return the strictest policy across all participating admins.
3308 List<ActiveAdmin> admins =
3309 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3310 final int N = admins.size();
3311 for (int i = 0; i < N; i++) {
3312 ActiveAdmin admin = admins.get(i);
3313 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3316 if (length < admin.minimumPasswordLetters) {
3317 length = admin.minimumPasswordLetters;
3325 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3329 Preconditions.checkNotNull(who, "ComponentName is null");
3330 synchronized (this) {
3331 ActiveAdmin ap = getActiveAdminForCallerLocked(
3332 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3333 if (ap.minimumPasswordNumeric != length) {
3334 ap.minimumPasswordNumeric = length;
3335 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3341 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3345 enforceFullCrossUsersPermission(userHandle);
3346 synchronized (this) {
3350 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3351 return admin != null ? admin.minimumPasswordNumeric : length;
3354 // Return the strictest policy across all participating admins.
3355 List<ActiveAdmin> admins =
3356 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3357 final int N = admins.size();
3358 for (int i = 0; i < N; i++) {
3359 ActiveAdmin admin = admins.get(i);
3360 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3363 if (length < admin.minimumPasswordNumeric) {
3364 length = admin.minimumPasswordNumeric;
3372 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3376 Preconditions.checkNotNull(who, "ComponentName is null");
3377 synchronized (this) {
3378 ActiveAdmin ap = getActiveAdminForCallerLocked(
3379 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3380 if (ap.minimumPasswordSymbols != length) {
3381 ap.minimumPasswordSymbols = length;
3382 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3388 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3392 enforceFullCrossUsersPermission(userHandle);
3393 synchronized (this) {
3397 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3398 return admin != null ? admin.minimumPasswordSymbols : length;
3401 // Return the strictest policy across all participating admins.
3402 List<ActiveAdmin> admins =
3403 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3404 final int N = admins.size();
3405 for (int i = 0; i < N; i++) {
3406 ActiveAdmin admin = admins.get(i);
3407 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3410 if (length < admin.minimumPasswordSymbols) {
3411 length = admin.minimumPasswordSymbols;
3419 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3423 Preconditions.checkNotNull(who, "ComponentName is null");
3424 synchronized (this) {
3425 ActiveAdmin ap = getActiveAdminForCallerLocked(
3426 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3427 if (ap.minimumPasswordNonLetter != length) {
3428 ap.minimumPasswordNonLetter = length;
3429 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3435 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3439 enforceFullCrossUsersPermission(userHandle);
3440 synchronized (this) {
3444 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3445 return admin != null ? admin.minimumPasswordNonLetter : length;
3448 // Return the strictest policy across all participating admins.
3449 List<ActiveAdmin> admins =
3450 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3451 final int N = admins.size();
3452 for (int i = 0; i < N; i++) {
3453 ActiveAdmin admin = admins.get(i);
3454 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3457 if (length < admin.minimumPasswordNonLetter) {
3458 length = admin.minimumPasswordNonLetter;
3466 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3470 enforceFullCrossUsersPermission(userHandle);
3472 synchronized (this) {
3473 // This API can only be called by an active device admin,
3474 // so try to retrieve it to check that the caller is one.
3475 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3476 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3477 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3482 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3486 enforceFullCrossUsersPermission(userHandle);
3487 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3489 synchronized (this) {
3490 int targetUser = getProfileParentId(userHandle);
3491 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3492 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3496 private boolean isActivePasswordSufficientForUserLocked(
3497 DevicePolicyData policy, int userHandle, boolean parent) {
3498 if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle, parent)
3499 || policy.mActivePasswordLength < getPasswordMinimumLength(
3500 null, userHandle, parent)) {
3503 if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3506 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3507 null, userHandle, parent)
3508 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3509 null, userHandle, parent)
3510 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3511 null, userHandle, parent)
3512 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3513 null, userHandle, parent)
3514 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3515 null, userHandle, parent)
3516 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3517 null, userHandle, parent);
3521 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3522 synchronized (this) {
3523 // This API can only be called by an active device admin,
3524 // so try to retrieve it to check that the caller is one.
3525 getActiveAdminForCallerLocked(
3526 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3528 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3530 return policy.mFailedPasswordAttempts;
3535 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3539 Preconditions.checkNotNull(who, "ComponentName is null");
3540 synchronized (this) {
3541 // This API can only be called by an active device admin,
3542 // so try to retrieve it to check that the caller is one.
3543 getActiveAdminForCallerLocked(
3544 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3545 ActiveAdmin ap = getActiveAdminForCallerLocked(
3546 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3547 if (ap.maximumFailedPasswordsForWipe != num) {
3548 ap.maximumFailedPasswordsForWipe = num;
3549 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3555 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3559 enforceFullCrossUsersPermission(userHandle);
3560 synchronized (this) {
3561 ActiveAdmin admin = (who != null)
3562 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3563 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3564 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3569 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3571 return UserHandle.USER_NULL;
3573 enforceFullCrossUsersPermission(userHandle);
3574 synchronized (this) {
3575 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3576 userHandle, parent);
3577 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3582 * Returns the admin with the strictest policy on maximum failed passwords for:
3584 * <li>this user if it has a separate profile challenge, or
3585 * <li>this user and all profiles that don't have their own challenge otherwise.
3587 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3588 * the primary profile.
3589 * Returns {@code null} if no participating admin has that policy set.
3591 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3592 int userHandle, boolean parent) {
3594 ActiveAdmin strictestAdmin = null;
3596 // Return the strictest policy across all participating admins.
3597 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3598 final int N = admins.size();
3599 for (int i = 0; i < N; i++) {
3600 ActiveAdmin admin = admins.get(i);
3601 if (admin.maximumFailedPasswordsForWipe ==
3602 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3603 continue; // No max number of failed passwords policy set for this profile.
3606 // We always favor the primary profile if several profiles have the same value set.
3607 int userId = admin.getUserHandle().getIdentifier();
3609 count > admin.maximumFailedPasswordsForWipe ||
3610 (count == admin.maximumFailedPasswordsForWipe &&
3611 mUserManager.getUserInfo(userId).isPrimary())) {
3612 count = admin.maximumFailedPasswordsForWipe;
3613 strictestAdmin = admin;
3616 return strictestAdmin;
3620 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3624 final int callingUid = mInjector.binderGetCallingUid();
3625 final int userHandle = mInjector.userHandleGetCallingUserId();
3627 if (getCredentialOwner(userHandle, /* parent */ false) != userHandle) {
3628 throw new SecurityException("You can not change password for this profile because"
3629 + " it shares the password with the owner profile");
3632 String password = passwordOrNull != null ? passwordOrNull : "";
3635 synchronized (this) {
3636 // If caller has PO (or DO), it can clear the password, so see if that's the case
3638 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3639 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3640 if (admin == null) {
3641 // Otherwise, make sure the caller has any active admin with the right policy.
3642 admin = getActiveAdminForCallerLocked(null,
3643 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3646 final ComponentName adminComponent = admin.info.getComponent();
3648 // As of N, only profile owners and device owners can reset the password.
3649 if (!(isProfileOwner(adminComponent, userHandle)
3650 || isDeviceOwner(adminComponent, userHandle))) {
3651 final boolean preN = getTargetSdk(admin.info.getPackageName(), userHandle)
3652 < android.os.Build.VERSION_CODES.N;
3653 // As of N, password resetting to empty/null is not allowed anymore.
3654 // TODO Should we allow DO/PO to set an empty password?
3655 if (TextUtils.isEmpty(password)) {
3657 throw new SecurityException("Cannot call with null password");
3659 Slog.e(LOG_TAG, "Cannot call with null password");
3663 // As of N, password cannot be changed by the admin if it is already set.
3664 if (isLockScreenSecureUnchecked(userHandle)) {
3666 throw new SecurityException("Admin cannot change current password");
3668 Slog.e(LOG_TAG, "Admin cannot change current password");
3673 quality = getPasswordQuality(null, userHandle, /* parent */ false);
3674 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
3675 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3677 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
3678 int realQuality = LockPatternUtils.computePasswordQuality(password);
3679 if (realQuality < quality
3680 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3681 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
3682 + Integer.toHexString(realQuality)
3683 + " does not meet required quality 0x"
3684 + Integer.toHexString(quality));
3687 quality = Math.max(realQuality, quality);
3689 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
3690 if (password.length() < length) {
3691 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
3692 + " does not meet required length " + length);
3695 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3702 for (int i = 0; i < password.length(); i++) {
3703 char c = password.charAt(i);
3704 if (c >= 'A' && c <= 'Z') {
3707 } else if (c >= 'a' && c <= 'z') {
3710 } else if (c >= '0' && c <= '9') {
3718 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
3719 if(letters < neededLetters) {
3720 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
3721 + " does not meet required number of letters " + neededLetters);
3724 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
3725 if (numbers < neededNumbers) {
3726 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
3727 + " does not meet required number of numerical digits "
3731 int neededLowerCase = getPasswordMinimumLowerCase(
3732 null, userHandle, /* parent */ false);
3733 if (lowercase < neededLowerCase) {
3734 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
3735 + " does not meet required number of lowercase letters "
3739 int neededUpperCase = getPasswordMinimumUpperCase(
3740 null, userHandle, /* parent */ false);
3741 if (uppercase < neededUpperCase) {
3742 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
3743 + " does not meet required number of uppercase letters "
3747 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
3748 if (symbols < neededSymbols) {
3749 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
3750 + " does not meet required number of special symbols " + neededSymbols);
3753 int neededNonLetter = getPasswordMinimumNonLetter(
3754 null, userHandle, /* parent */ false);
3755 if (nonletter < neededNonLetter) {
3756 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
3757 + " does not meet required number of non-letter characters "
3764 DevicePolicyData policy = getUserData(userHandle);
3765 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
3766 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
3770 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
3771 boolean doNotAskCredentialsOnBoot =
3772 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
3773 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
3774 setDoNotAskCredentialsOnBoot();
3777 // Don't do this with the lock held, because it is going to call
3778 // back in to the service.
3779 final long ident = mInjector.binderClearCallingIdentity();
3781 if (!TextUtils.isEmpty(password)) {
3782 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
3784 mLockPatternUtils.clearLock(userHandle);
3786 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
3788 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
3789 UserHandle.USER_ALL);
3791 synchronized (this) {
3792 int newOwner = requireEntry ? callingUid : -1;
3793 if (policy.mPasswordOwner != newOwner) {
3794 policy.mPasswordOwner = newOwner;
3795 saveSettingsLocked(userHandle);
3799 mInjector.binderRestoreCallingIdentity(ident);
3805 private boolean isLockScreenSecureUnchecked(int userId) {
3806 long ident = mInjector.binderClearCallingIdentity();
3808 return mLockPatternUtils.isSecure(userId);
3810 mInjector.binderRestoreCallingIdentity(ident);
3814 private void setDoNotAskCredentialsOnBoot() {
3815 synchronized (this) {
3816 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
3817 if (!policyData.doNotAskCredentialsOnBoot) {
3818 policyData.doNotAskCredentialsOnBoot = true;
3819 saveSettingsLocked(UserHandle.USER_SYSTEM);
3825 public boolean getDoNotAskCredentialsOnBoot() {
3826 mContext.enforceCallingOrSelfPermission(
3827 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
3828 synchronized (this) {
3829 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
3830 return policyData.doNotAskCredentialsOnBoot;
3835 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
3839 Preconditions.checkNotNull(who, "ComponentName is null");
3840 final int userHandle = mInjector.userHandleGetCallingUserId();
3841 synchronized (this) {
3842 ActiveAdmin ap = getActiveAdminForCallerLocked(
3843 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
3844 if (ap.maximumTimeToUnlock != timeMs) {
3845 ap.maximumTimeToUnlock = timeMs;
3846 saveSettingsLocked(userHandle);
3847 updateMaximumTimeToLockLocked(userHandle);
3852 void updateMaximumTimeToLockLocked(int userHandle) {
3853 // Calculate the min timeout for all profiles - including the ones with a separate
3854 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
3855 // challenge only and keep the screen on. However there is no easy way of doing that at the
3856 // moment so we set the screen off timeout regardless of whether it affects the parent user
3857 // or the profile challenge only.
3858 long timeMs = Integer.MAX_VALUE;
3859 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3860 for (UserInfo userInfo : profiles) {
3861 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
3862 final int N = policy.mAdminList.size();
3863 for (int i = 0; i < N; i++) {
3864 ActiveAdmin admin = policy.mAdminList.get(i);
3865 if (admin.maximumTimeToUnlock > 0
3866 && timeMs > admin.maximumTimeToUnlock) {
3867 timeMs = admin.maximumTimeToUnlock;
3872 // We only store the last maximum time to lock on the parent profile. So if calling from a
3873 // managed profile, retrieve the policy for the parent.
3874 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
3875 if (policy.mLastMaximumTimeToLock == timeMs) {
3878 policy.mLastMaximumTimeToLock = timeMs;
3880 final long ident = mInjector.binderClearCallingIdentity();
3882 if (policy.mLastMaximumTimeToLock != Integer.MAX_VALUE) {
3883 // Make sure KEEP_SCREEN_ON is disabled, since that
3884 // would allow bypassing of the maximum time to lock.
3885 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
3888 // TODO It can overflow. Cap it.
3889 mInjector.getPowerManagerInternal()
3890 .setMaximumScreenOffTimeoutFromDeviceAdmin((int)policy.mLastMaximumTimeToLock);
3892 mInjector.binderRestoreCallingIdentity(ident);
3897 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
3901 enforceFullCrossUsersPermission(userHandle);
3902 synchronized (this) {
3906 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3907 return admin != null ? admin.maximumTimeToUnlock : time;
3910 // Return the strictest policy across all participating admins.
3911 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
3912 userHandle, parent);
3913 final int N = admins.size();
3914 for (int i = 0; i < N; i++) {
3915 ActiveAdmin admin = admins.get(i);
3917 time = admin.maximumTimeToUnlock;
3918 } else if (admin.maximumTimeToUnlock != 0
3919 && time > admin.maximumTimeToUnlock) {
3920 time = admin.maximumTimeToUnlock;
3928 public void lockNow(boolean parent) {
3932 synchronized (this) {
3933 // This API can only be called by an active device admin,
3934 // so try to retrieve it to check that the caller is one.
3935 getActiveAdminForCallerLocked(
3936 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
3938 int userToLock = mInjector.userHandleGetCallingUserId();
3940 // Unless this is a managed profile with work challenge enabled, lock all users.
3941 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
3942 userToLock = UserHandle.USER_ALL;
3944 final long ident = mInjector.binderClearCallingIdentity();
3946 mLockPatternUtils.requireStrongAuth(
3947 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
3948 if (userToLock == UserHandle.USER_ALL) {
3949 // Power off the display
3950 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
3951 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
3952 mInjector.getIWindowManager().lockNow(null);
3954 } catch (RemoteException e) {
3956 mInjector.binderRestoreCallingIdentity(ident);
3962 public void enforceCanManageCaCerts(ComponentName who) {
3964 if (!isCallerDelegatedCertInstaller()) {
3965 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
3968 synchronized (this) {
3969 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3974 private void enforceCanManageInstalledKeys(ComponentName who) {
3976 if (!isCallerDelegatedCertInstaller()) {
3977 throw new SecurityException("who == null, but caller is not cert installer");
3980 synchronized (this) {
3981 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3986 private boolean isCallerDelegatedCertInstaller() {
3987 final int callingUid = mInjector.binderGetCallingUid();
3988 final int userHandle = UserHandle.getUserId(callingUid);
3989 synchronized (this) {
3990 final DevicePolicyData policy = getUserData(userHandle);
3991 if (policy.mDelegatedCertInstallerPackage == null) {
3996 int uid = mContext.getPackageManager().getPackageUidAsUser(
3997 policy.mDelegatedCertInstallerPackage, userHandle);
3998 return uid == callingUid;
3999 } catch (NameNotFoundException e) {
4006 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4007 enforceCanManageCaCerts(admin);
4011 X509Certificate cert = parseCert(certBuffer);
4012 pemCert = Credentials.convertToPem(cert);
4013 } catch (CertificateException ce) {
4014 Log.e(LOG_TAG, "Problem converting cert", ce);
4016 } catch (IOException ioe) {
4017 Log.e(LOG_TAG, "Problem reading cert", ioe);
4021 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4022 final long id = mInjector.binderClearCallingIdentity();
4024 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4026 keyChainConnection.getService().installCaCertificate(pemCert);
4028 } catch (RemoteException e) {
4029 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4031 keyChainConnection.close();
4033 } catch (InterruptedException e1) {
4034 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4035 Thread.currentThread().interrupt();
4037 mInjector.binderRestoreCallingIdentity(id);
4042 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4043 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4044 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4049 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4050 enforceCanManageCaCerts(admin);
4052 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4053 final long id = mInjector.binderClearCallingIdentity();
4055 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4057 for (int i = 0 ; i < aliases.length; i++) {
4058 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4060 } catch (RemoteException e) {
4061 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4063 keyChainConnection.close();
4065 } catch (InterruptedException ie) {
4066 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4067 Thread.currentThread().interrupt();
4069 mInjector.binderRestoreCallingIdentity(id);
4074 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, String alias) {
4075 enforceCanManageInstalledKeys(who);
4077 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4078 final long id = mInjector.binderClearCallingIdentity();
4080 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4082 IKeyChainService keyChain = keyChainConnection.getService();
4083 return keyChain.installKeyPair(privKey, cert, alias);
4084 } catch (RemoteException e) {
4085 Log.e(LOG_TAG, "Installing certificate", e);
4087 keyChainConnection.close();
4089 } catch (InterruptedException e) {
4090 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4091 Thread.currentThread().interrupt();
4093 mInjector.binderRestoreCallingIdentity(id);
4099 public boolean removeKeyPair(ComponentName who, String alias) {
4100 enforceCanManageInstalledKeys(who);
4102 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4103 final long id = Binder.clearCallingIdentity();
4105 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4107 IKeyChainService keyChain = keyChainConnection.getService();
4108 return keyChain.removeKeyPair(alias);
4109 } catch (RemoteException e) {
4110 Log.e(LOG_TAG, "Removing keypair", e);
4112 keyChainConnection.close();
4114 } catch (InterruptedException e) {
4115 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4116 Thread.currentThread().interrupt();
4118 Binder.restoreCallingIdentity(id);
4124 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4125 final IBinder response) {
4126 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4127 if (!UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID)) {
4131 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4132 // If there is a profile owner, redirect to that; otherwise query the device owner.
4133 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4134 if (aliasChooser == null && caller.isSystem()) {
4135 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4136 if (deviceOwnerAdmin != null) {
4137 aliasChooser = deviceOwnerAdmin.info.getComponent();
4140 if (aliasChooser == null) {
4141 sendPrivateKeyAliasResponse(null, response);
4145 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4146 intent.setComponent(aliasChooser);
4147 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4148 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4149 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4150 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4152 final long id = mInjector.binderClearCallingIdentity();
4154 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4156 public void onReceive(Context context, Intent intent) {
4157 final String chosenAlias = getResultData();
4158 sendPrivateKeyAliasResponse(chosenAlias, response);
4160 }, null, Activity.RESULT_OK, null, null);
4162 mInjector.binderRestoreCallingIdentity(id);
4166 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4167 final IKeyChainAliasCallback keyChainAliasResponse =
4168 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4169 new AsyncTask<Void, Void, Void>() {
4171 protected Void doInBackground(Void... unused) {
4173 keyChainAliasResponse.alias(alias);
4174 } catch (Exception e) {
4175 // Catch everything (not just RemoteException): caller could throw a
4176 // RuntimeException back across processes.
4177 Log.e(LOG_TAG, "error while responding to callback", e);
4185 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4186 throws SecurityException {
4187 int userHandle = UserHandle.getCallingUserId();
4188 synchronized (this) {
4189 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4190 DevicePolicyData policy = getUserData(userHandle);
4191 policy.mDelegatedCertInstallerPackage = installerPackage;
4192 saveSettingsLocked(userHandle);
4197 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4198 int userHandle = UserHandle.getCallingUserId();
4199 synchronized (this) {
4200 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4201 DevicePolicyData policy = getUserData(userHandle);
4202 return policy.mDelegatedCertInstallerPackage;
4207 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage)
4208 throws SecurityException {
4209 synchronized (this) {
4210 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4213 final int userId = mInjector.userHandleGetCallingUserId();
4214 final long token = mInjector.binderClearCallingIdentity();
4216 ConnectivityManager connectivityManager = (ConnectivityManager)
4217 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4218 return connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage);
4220 mInjector.binderRestoreCallingIdentity(token);
4225 public String getAlwaysOnVpnPackage(ComponentName admin)
4226 throws SecurityException {
4227 synchronized (this) {
4228 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4231 final int userId = mInjector.userHandleGetCallingUserId();
4232 final long token = mInjector.binderClearCallingIdentity();
4234 ConnectivityManager connectivityManager = (ConnectivityManager)
4235 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4236 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4238 mInjector.binderRestoreCallingIdentity(token);
4242 private void wipeDataLocked(boolean wipeExtRequested, String reason) {
4243 if (wipeExtRequested) {
4244 StorageManager sm = (StorageManager) mContext.getSystemService(
4245 Context.STORAGE_SERVICE);
4246 sm.wipeAdoptableDisks();
4249 RecoverySystem.rebootWipeUserData(mContext, reason);
4250 } catch (IOException | SecurityException e) {
4251 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4256 public void wipeData(int flags) {
4260 final int userHandle = mInjector.userHandleGetCallingUserId();
4261 enforceFullCrossUsersPermission(userHandle);
4262 synchronized (this) {
4263 // This API can only be called by an active device admin,
4264 // so try to retrieve it to check that the caller is one.
4265 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4266 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4268 final String source = admin.info.getComponent().flattenToShortString();
4270 long ident = mInjector.binderClearCallingIdentity();
4272 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4273 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4274 throw new SecurityException(
4275 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4277 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4278 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4279 if (manager != null) {
4283 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4284 wipeDeviceOrUserLocked(wipeExtRequested, userHandle,
4285 "DevicePolicyManager.wipeData() from " + source);
4287 mInjector.binderRestoreCallingIdentity(ident);
4292 private void wipeDeviceOrUserLocked(boolean wipeExtRequested, final int userHandle, String reason) {
4293 if (userHandle == UserHandle.USER_SYSTEM) {
4294 wipeDataLocked(wipeExtRequested, reason);
4296 mHandler.post(new Runnable() {
4300 IActivityManager am = mInjector.getIActivityManager();
4301 if (am.getCurrentUser().id == userHandle) {
4302 am.switchUser(UserHandle.USER_SYSTEM);
4305 boolean isManagedProfile = isManagedProfile(userHandle);
4306 if (!mUserManager.removeUser(userHandle)) {
4307 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4308 } else if (isManagedProfile) {
4309 sendWipeProfileNotification();
4311 } catch (RemoteException re) {
4319 private void sendWipeProfileNotification() {
4320 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4321 Notification notification = new Notification.Builder(mContext)
4322 .setSmallIcon(android.R.drawable.stat_sys_warning)
4323 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4324 .setContentText(contentText)
4325 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4326 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4328 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4331 private void clearWipeProfileNotification() {
4332 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4336 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4340 enforceFullCrossUsersPermission(userHandle);
4341 mContext.enforceCallingOrSelfPermission(
4342 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4344 synchronized (this) {
4345 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4346 if (admin == null) {
4347 result.sendResult(null);
4350 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4351 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4352 intent.setComponent(admin.info.getComponent());
4353 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4354 null, new BroadcastReceiver() {
4356 public void onReceive(Context context, Intent intent) {
4357 result.sendResult(getResultExtras(false));
4359 }, null, Activity.RESULT_OK, null, null);
4364 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4365 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4369 enforceFullCrossUsersPermission(userHandle);
4371 // Managed Profile password can only be changed when it has a separate challenge.
4372 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4373 enforceNotManagedProfile(userHandle, "set the active password");
4376 mContext.enforceCallingOrSelfPermission(
4377 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4378 validateQualityConstant(quality);
4380 DevicePolicyData policy = getUserData(userHandle);
4382 long ident = mInjector.binderClearCallingIdentity();
4384 synchronized (this) {
4385 policy.mActivePasswordQuality = quality;
4386 policy.mActivePasswordLength = length;
4387 policy.mActivePasswordLetters = letters;
4388 policy.mActivePasswordLowerCase = lowercase;
4389 policy.mActivePasswordUpperCase = uppercase;
4390 policy.mActivePasswordNumeric = numbers;
4391 policy.mActivePasswordSymbols = symbols;
4392 policy.mActivePasswordNonLetter = nonletter;
4393 policy.mFailedPasswordAttempts = 0;
4394 saveSettingsLocked(userHandle);
4395 updatePasswordExpirationsLocked(userHandle);
4396 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
4398 // Send a broadcast to each profile using this password as its primary unlock.
4399 sendAdminCommandForLockscreenPoliciesLocked(
4400 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4401 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
4404 mInjector.binderRestoreCallingIdentity(ident);
4409 * Called any time the device password is updated. Resets all password expiration clocks.
4411 private void updatePasswordExpirationsLocked(int userHandle) {
4412 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4413 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4414 userHandle, /* parent */ false);
4415 final int N = admins.size();
4416 for (int i = 0; i < N; i++) {
4417 ActiveAdmin admin = admins.get(i);
4418 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4419 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4420 long timeout = admin.passwordExpirationTimeout;
4421 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4422 admin.passwordExpirationDate = expiration;
4425 for (int affectedUserId : affectedUserIds) {
4426 saveSettingsLocked(affectedUserId);
4431 public void reportFailedPasswordAttempt(int userHandle) {
4432 enforceFullCrossUsersPermission(userHandle);
4433 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4434 enforceNotManagedProfile(userHandle,
4435 "report failed password attempt if separate profile challenge is not in place");
4437 mContext.enforceCallingOrSelfPermission(
4438 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4440 final long ident = mInjector.binderClearCallingIdentity();
4442 boolean wipeData = false;
4444 synchronized (this) {
4445 DevicePolicyData policy = getUserData(userHandle);
4446 policy.mFailedPasswordAttempts++;
4447 saveSettingsLocked(userHandle);
4449 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4450 userHandle, /* parent */ false);
4451 int max = strictestAdmin != null
4452 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4453 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4454 // Wipe the user/profile associated with the policy that was violated. This
4455 // is not necessarily calling user: if the policy that fired was from a
4456 // managed profile rather than the main user profile, we wipe former only.
4458 identifier = strictestAdmin.getUserHandle().getIdentifier();
4461 sendAdminCommandForLockscreenPoliciesLocked(
4462 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
4463 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4467 // Call without holding lock.
4468 wipeDeviceOrUserLocked(false, identifier,
4469 "reportFailedPasswordAttempt()");
4472 mInjector.binderRestoreCallingIdentity(ident);
4475 if (SecurityLog.isLoggingEnabled()) {
4476 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0);
4481 public void reportSuccessfulPasswordAttempt(int userHandle) {
4482 enforceFullCrossUsersPermission(userHandle);
4483 mContext.enforceCallingOrSelfPermission(
4484 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4486 synchronized (this) {
4487 DevicePolicyData policy = getUserData(userHandle);
4488 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
4489 long ident = mInjector.binderClearCallingIdentity();
4491 policy.mFailedPasswordAttempts = 0;
4492 policy.mPasswordOwner = -1;
4493 saveSettingsLocked(userHandle);
4495 sendAdminCommandForLockscreenPoliciesLocked(
4496 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
4497 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4500 mInjector.binderRestoreCallingIdentity(ident);
4505 if (SecurityLog.isLoggingEnabled()) {
4506 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1);
4511 public void reportKeyguardDismissed() {
4512 mContext.enforceCallingOrSelfPermission(
4513 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4514 if (SecurityLog.isLoggingEnabled()) {
4515 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
4520 public void reportKeyguardSecured() {
4521 mContext.enforceCallingOrSelfPermission(
4522 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4523 if (SecurityLog.isLoggingEnabled()) {
4524 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
4529 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
4530 String exclusionList) {
4534 synchronized(this) {
4535 Preconditions.checkNotNull(who, "ComponentName is null");
4537 // Only check if system user has set global proxy. We don't allow other users to set it.
4538 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4539 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4540 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
4542 // Scan through active admins and find if anyone has already
4543 // set the global proxy.
4544 Set<ComponentName> compSet = policy.mAdminMap.keySet();
4545 for (ComponentName component : compSet) {
4546 ActiveAdmin ap = policy.mAdminMap.get(component);
4547 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
4548 // Another admin already sets the global proxy
4549 // Return it to the caller.
4554 // If the user is not system, don't set the global proxy. Fail silently.
4555 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
4556 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
4557 + UserHandle.getCallingUserId() + " is not permitted.");
4560 if (proxySpec == null) {
4561 admin.specifiesGlobalProxy = false;
4562 admin.globalProxySpec = null;
4563 admin.globalProxyExclusionList = null;
4566 admin.specifiesGlobalProxy = true;
4567 admin.globalProxySpec = proxySpec;
4568 admin.globalProxyExclusionList = exclusionList;
4571 // Reset the global proxy accordingly
4572 // Do this using system permissions, as apps cannot write to secure settings
4573 long origId = mInjector.binderClearCallingIdentity();
4575 resetGlobalProxyLocked(policy);
4577 mInjector.binderRestoreCallingIdentity(origId);
4584 public ComponentName getGlobalProxyAdmin(int userHandle) {
4588 enforceFullCrossUsersPermission(userHandle);
4589 synchronized(this) {
4590 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4591 // Scan through active admins and find if anyone has already
4592 // set the global proxy.
4593 final int N = policy.mAdminList.size();
4594 for (int i = 0; i < N; i++) {
4595 ActiveAdmin ap = policy.mAdminList.get(i);
4596 if (ap.specifiesGlobalProxy) {
4597 // Device admin sets the global proxy
4598 // Return it to the caller.
4599 return ap.info.getComponent();
4603 // No device admin sets the global proxy.
4608 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
4609 synchronized (this) {
4610 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4612 long token = mInjector.binderClearCallingIdentity();
4614 ConnectivityManager connectivityManager = (ConnectivityManager)
4615 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4616 connectivityManager.setGlobalProxy(proxyInfo);
4618 mInjector.binderRestoreCallingIdentity(token);
4622 private void resetGlobalProxyLocked(DevicePolicyData policy) {
4623 final int N = policy.mAdminList.size();
4624 for (int i = 0; i < N; i++) {
4625 ActiveAdmin ap = policy.mAdminList.get(i);
4626 if (ap.specifiesGlobalProxy) {
4627 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
4631 // No device admins defining global proxies - reset global proxy settings to none
4632 saveGlobalProxyLocked(null, null);
4635 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
4636 if (exclusionList == null) {
4639 if (proxySpec == null) {
4642 // Remove white spaces
4643 proxySpec = proxySpec.trim();
4644 String data[] = proxySpec.split(":");
4645 int proxyPort = 8080;
4646 if (data.length > 1) {
4648 proxyPort = Integer.parseInt(data[1]);
4649 } catch (NumberFormatException e) {}
4651 exclusionList = exclusionList.trim();
4653 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
4654 if (!proxyProperties.isValid()) {
4655 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
4658 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
4659 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
4660 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
4665 * Set the storage encryption request for a single admin. Returns the new total request
4666 * status (for all admins).
4669 public int setStorageEncryption(ComponentName who, boolean encrypt) {
4671 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4673 Preconditions.checkNotNull(who, "ComponentName is null");
4674 final int userHandle = UserHandle.getCallingUserId();
4675 synchronized (this) {
4676 // Check for permissions
4677 // Only system user can set storage encryption
4678 if (userHandle != UserHandle.USER_SYSTEM) {
4679 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
4680 + UserHandle.getCallingUserId() + " is not permitted.");
4684 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4685 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
4687 // Quick exit: If the filesystem does not support encryption, we can exit early.
4688 if (!isEncryptionSupported()) {
4689 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4692 // (1) Record the value for the admin so it's sticky
4693 if (ap.encryptionRequested != encrypt) {
4694 ap.encryptionRequested = encrypt;
4695 saveSettingsLocked(userHandle);
4698 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4699 // (2) Compute "max" for all admins
4700 boolean newRequested = false;
4701 final int N = policy.mAdminList.size();
4702 for (int i = 0; i < N; i++) {
4703 newRequested |= policy.mAdminList.get(i).encryptionRequested;
4706 // Notify OS of new request
4707 setEncryptionRequested(newRequested);
4709 // Return the new global request status
4711 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
4712 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
4717 * Get the current storage encryption request status for a given admin, or aggregate of all
4721 public boolean getStorageEncryption(ComponentName who, int userHandle) {
4725 enforceFullCrossUsersPermission(userHandle);
4726 synchronized (this) {
4727 // Check for permissions if a particular caller is specified
4729 // When checking for a single caller, status is based on caller's request
4730 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
4731 return ap != null ? ap.encryptionRequested : false;
4734 // If no particular caller is specified, return the aggregate set of requests.
4735 // This is short circuited by returning true on the first hit.
4736 DevicePolicyData policy = getUserData(userHandle);
4737 final int N = policy.mAdminList.size();
4738 for (int i = 0; i < N; i++) {
4739 if (policy.mAdminList.get(i).encryptionRequested) {
4748 * Get the current encryption status of the device.
4751 public int getStorageEncryptionStatus(int userHandle) {
4753 // Ok to return current status.
4755 enforceFullCrossUsersPermission(userHandle);
4756 return getEncryptionStatus();
4760 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
4762 private boolean isEncryptionSupported() {
4763 // Note, this can be implemented as
4764 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4765 // But is provided as a separate internal method if there's a faster way to do a
4766 // simple check for supported-or-not.
4767 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4771 * Hook to low-levels: Reporting the current status of encryption.
4772 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
4773 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
4774 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, or
4775 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
4777 private int getEncryptionStatus() {
4778 String status = mInjector.systemPropertiesGet("ro.crypto.state", "unsupported");
4779 if ("encrypted".equalsIgnoreCase(status)) {
4780 final long token = mInjector.binderClearCallingIdentity();
4782 return LockPatternUtils.isDeviceEncrypted()
4783 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
4784 : DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
4786 mInjector.binderRestoreCallingIdentity(token);
4788 } else if ("unencrypted".equalsIgnoreCase(status)) {
4789 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
4791 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4796 * Hook to low-levels: If needed, record the new admin setting for encryption.
4798 private void setEncryptionRequested(boolean encrypt) {
4803 * Set whether the screen capture is disabled for the user managed by the specified admin.
4806 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
4810 Preconditions.checkNotNull(who, "ComponentName is null");
4811 final int userHandle = UserHandle.getCallingUserId();
4812 synchronized (this) {
4813 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4814 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4815 if (ap.disableScreenCapture != disabled) {
4816 ap.disableScreenCapture = disabled;
4817 saveSettingsLocked(userHandle);
4818 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
4824 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
4825 * active admin (if given admin is null).
4828 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
4832 synchronized (this) {
4834 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4835 return (admin != null) ? admin.disableScreenCapture : false;
4838 DevicePolicyData policy = getUserData(userHandle);
4839 final int N = policy.mAdminList.size();
4840 for (int i = 0; i < N; i++) {
4841 ActiveAdmin admin = policy.mAdminList.get(i);
4842 if (admin.disableScreenCapture) {
4850 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
4851 final boolean disabled) {
4852 mHandler.post(new Runnable() {
4856 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
4857 } catch (RemoteException e) {
4858 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
4865 * Set whether auto time is required by the specified admin (must be device owner).
4868 public void setAutoTimeRequired(ComponentName who, boolean required) {
4872 Preconditions.checkNotNull(who, "ComponentName is null");
4873 final int userHandle = UserHandle.getCallingUserId();
4874 synchronized (this) {
4875 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4876 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4877 if (admin.requireAutoTime != required) {
4878 admin.requireAutoTime = required;
4879 saveSettingsLocked(userHandle);
4883 // Turn AUTO_TIME on in settings if it is required
4885 long ident = mInjector.binderClearCallingIdentity();
4887 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
4889 mInjector.binderRestoreCallingIdentity(ident);
4895 * Returns whether or not auto time is required by the device owner.
4898 public boolean getAutoTimeRequired() {
4902 synchronized (this) {
4903 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
4904 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
4909 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
4913 Preconditions.checkNotNull(who, "ComponentName is null");
4914 boolean removeAllUsers = false;
4915 synchronized (this) {
4916 final ActiveAdmin deviceOwner =
4917 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4918 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
4919 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
4920 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4921 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
4922 removeAllUsers = forceEphemeralUsers;
4925 if (removeAllUsers) {
4926 long identitity = mInjector.binderClearCallingIdentity();
4928 mUserManagerInternal.removeAllUsers();
4930 mInjector.binderRestoreCallingIdentity(identitity);
4936 public boolean getForceEphemeralUsers(ComponentName who) {
4940 Preconditions.checkNotNull(who, "ComponentName is null");
4941 synchronized (this) {
4942 final ActiveAdmin deviceOwner =
4943 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4944 return deviceOwner.forceEphemeralUsers;
4948 private boolean isDeviceOwnerManagedSingleUserDevice() {
4949 synchronized (this) {
4950 if (!mOwners.hasDeviceOwner()) {
4954 final long callingIdentity = mInjector.binderClearCallingIdentity();
4956 if (mInjector.userManagerIsSplitSystemUser()) {
4957 // In split system user mode, only allow the case where the device owner is managing
4958 // the only non-system user of the device
4959 return (mUserManager.getUserCount() == 2
4960 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
4962 return mUserManager.getUserCount() == 1;
4965 mInjector.binderRestoreCallingIdentity(callingIdentity);
4969 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
4970 synchronized (this) {
4971 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4973 if (!isDeviceOwnerManagedSingleUserDevice()) {
4974 throw new SecurityException(
4975 "There should only be one user, managed by Device Owner");
4980 public boolean requestBugreport(ComponentName who) {
4984 Preconditions.checkNotNull(who, "ComponentName is null");
4985 ensureDeviceOwnerManagingSingleUser(who);
4987 if (mRemoteBugreportServiceIsActive.get()
4988 || (getDeviceOwnerRemoteBugreportUri() != null)) {
4989 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
4993 final long callingIdentity = mInjector.binderClearCallingIdentity();
4995 ActivityManagerNative.getDefault().requestBugReport(
4996 ActivityManager.BUGREPORT_OPTION_REMOTE);
4998 mRemoteBugreportServiceIsActive.set(true);
4999 mRemoteBugreportSharingAccepted.set(false);
5000 registerRemoteBugreportReceivers();
5001 mInjector.getNotificationManager().notify(
5002 LOG_TAG, RemoteBugreportUtils.REMOTE_BUGREPORT_CONSENT_NOTIFICATION_ID,
5003 RemoteBugreportUtils.buildRemoteBugreportConsentNotification(mContext));
5004 mInjector.getNotificationManager().notify(
5005 LOG_TAG, RemoteBugreportUtils.REMOTE_BUGREPORT_IN_PROGRESS_NOTIFICATION_ID,
5006 RemoteBugreportUtils.buildRemoteBugreportInProgressNotification(mContext,
5007 /* canCancelBugReport */ true));
5008 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5009 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5011 } catch (RemoteException re) {
5012 // should never happen
5013 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5016 mInjector.binderRestoreCallingIdentity(callingIdentity);
5020 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5021 Intent intent = new Intent(action);
5022 intent.setComponent(mOwners.getDeviceOwnerComponent());
5023 if (extras != null) {
5024 intent.putExtras(extras);
5026 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5029 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5030 return mOwners.getDeviceOwnerRemoteBugreportUri();
5033 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5034 String bugreportHash) {
5035 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5038 private void registerRemoteBugreportReceivers() {
5040 IntentFilter filterFinished = new IntentFilter(
5041 RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_DISPATCH,
5042 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5043 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5044 } catch (IntentFilter.MalformedMimeTypeException e) {
5045 // should never happen, as setting a constant
5046 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5048 IntentFilter filterConsent = new IntentFilter();
5049 filterConsent.addAction(RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_DECLINED);
5050 filterConsent.addAction(RemoteBugreportUtils.ACTION_REMOTE_BUGREPORT_SHARING_ACCEPTED);
5051 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5054 private void onBugreportFinished(Intent intent) {
5055 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5056 mRemoteBugreportServiceIsActive.set(false);
5057 mInjector.getNotificationManager().cancel(LOG_TAG,
5058 RemoteBugreportUtils.REMOTE_BUGREPORT_IN_PROGRESS_NOTIFICATION_ID);
5059 Uri bugreportUri = intent.getData();
5060 String bugreportUriString = null;
5061 if (bugreportUri != null) {
5062 bugreportUriString = bugreportUri.toString();
5064 String bugreportHash = intent.getStringExtra(
5065 RemoteBugreportUtils.EXTRA_REMOTE_BUGREPORT_HASH);
5066 if (mRemoteBugreportSharingAccepted.get()) {
5067 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5069 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5071 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5074 private void onBugreportFailed() {
5075 mRemoteBugreportServiceIsActive.set(false);
5076 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5077 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5078 mRemoteBugreportSharingAccepted.set(false);
5079 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5080 mInjector.getNotificationManager().cancel(LOG_TAG,
5081 RemoteBugreportUtils.REMOTE_BUGREPORT_CONSENT_NOTIFICATION_ID);
5082 mInjector.getNotificationManager().cancel(LOG_TAG,
5083 RemoteBugreportUtils.REMOTE_BUGREPORT_IN_PROGRESS_NOTIFICATION_ID);
5084 Bundle extras = new Bundle();
5085 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5086 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5087 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5088 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5089 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5092 private void onBugreportSharingAccepted() {
5093 mRemoteBugreportSharingAccepted.set(true);
5094 String bugreportUriString = null;
5095 String bugreportHash = null;
5096 synchronized (this) {
5097 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5098 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5100 if (bugreportUriString != null) {
5101 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5102 } else if (mRemoteBugreportServiceIsActive.get()) {
5103 mInjector.getNotificationManager().notify(LOG_TAG,
5104 RemoteBugreportUtils.REMOTE_BUGREPORT_IN_PROGRESS_NOTIFICATION_ID,
5105 RemoteBugreportUtils.buildRemoteBugreportInProgressNotification(mContext,
5106 /* canCancelBugReport */ false));
5110 private void onBugreportSharingDeclined() {
5111 if (mRemoteBugreportServiceIsActive.get()) {
5112 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5113 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5114 mRemoteBugreportServiceIsActive.set(false);
5115 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5116 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5118 mRemoteBugreportSharingAccepted.set(false);
5119 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5120 mInjector.getNotificationManager().cancel(LOG_TAG,
5121 RemoteBugreportUtils.REMOTE_BUGREPORT_IN_PROGRESS_NOTIFICATION_ID);
5122 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5125 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5126 String bugreportHash) {
5127 ParcelFileDescriptor pfd = null;
5129 if (bugreportUriString == null) {
5130 throw new FileNotFoundException();
5132 Uri bugreportUri = Uri.parse(bugreportUriString);
5133 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5135 synchronized (this) {
5136 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5137 intent.setComponent(mOwners.getDeviceOwnerComponent());
5138 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5139 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5140 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
5141 bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5142 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5144 } catch (FileNotFoundException e) {
5145 Bundle extras = new Bundle();
5146 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5147 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5148 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5154 } catch (IOException ex) {
5157 mRemoteBugreportSharingAccepted.set(false);
5158 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5163 * Disables all device cameras according to the specified admin.
5166 public void setCameraDisabled(ComponentName who, boolean disabled) {
5170 Preconditions.checkNotNull(who, "ComponentName is null");
5171 final int userHandle = mInjector.userHandleGetCallingUserId();
5172 synchronized (this) {
5173 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5174 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5175 if (ap.disableCamera != disabled) {
5176 ap.disableCamera = disabled;
5177 saveSettingsLocked(userHandle);
5180 // Tell the user manager that the restrictions have changed.
5181 pushUserRestrictions(userHandle);
5185 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5189 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5190 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5193 private boolean getCameraDisabled(ComponentName who, int userHandle,
5194 boolean mergeDeviceOwnerRestriction) {
5198 synchronized (this) {
5200 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5201 return (admin != null) ? admin.disableCamera : false;
5203 // First, see if DO has set it. If so, it's device-wide.
5204 if (mergeDeviceOwnerRestriction) {
5205 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5206 if (deviceOwner != null && deviceOwner.disableCamera) {
5211 // Then check each device admin on the user.
5212 DevicePolicyData policy = getUserData(userHandle);
5213 // Determine whether or not the device camera is disabled for any active admins.
5214 final int N = policy.mAdminList.size();
5215 for (int i = 0; i < N; i++) {
5216 ActiveAdmin admin = policy.mAdminList.get(i);
5217 if (admin.disableCamera) {
5226 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5230 Preconditions.checkNotNull(who, "ComponentName is null");
5231 final int userHandle = mInjector.userHandleGetCallingUserId();
5232 if (isManagedProfile(userHandle)) {
5234 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5235 } else if (isSeparateProfileChallengeEnabled(userHandle)){
5236 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_PROFILE;
5238 which = which & PROFILE_KEYGUARD_FEATURES;
5241 synchronized (this) {
5242 ActiveAdmin ap = getActiveAdminForCallerLocked(
5243 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5244 if (ap.disabledKeyguardFeatures != which) {
5245 ap.disabledKeyguardFeatures = which;
5246 saveSettingsLocked(userHandle);
5252 * Gets the disabled state for features in keyguard for the given admin,
5253 * or the aggregate of all active admins if who is null.
5256 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5260 enforceFullCrossUsersPermission(userHandle);
5261 final long ident = mInjector.binderClearCallingIdentity();
5263 synchronized (this) {
5265 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5266 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5269 final List<ActiveAdmin> admins;
5270 if (!parent && isManagedProfile(userHandle)) {
5271 // If we are being asked about a managed profile, just return keyguard features
5272 // disabled by admins in the profile.
5273 admins = getUserDataUnchecked(userHandle).mAdminList;
5275 // Otherwise return those set by admins in the user and its profiles.
5276 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5279 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5280 final int N = admins.size();
5281 for (int i = 0; i < N; i++) {
5282 ActiveAdmin admin = admins.get(i);
5283 int userId = admin.getUserHandle().getIdentifier();
5284 if (userId == userHandle || !isManagedProfile(userHandle)) {
5285 // If we are being asked explicitly about this user
5286 // return all disabled features even if its a managed profile.
5287 which |= admin.disabledKeyguardFeatures;
5289 // Otherwise a managed profile is only allowed to disable
5290 // some features on the parent user.
5291 which |= (admin.disabledKeyguardFeatures
5292 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5298 mInjector.binderRestoreCallingIdentity(ident);
5303 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5307 Preconditions.checkNotNull(who, "ComponentName is null");
5308 Preconditions.checkNotNull(packageList, "packageList is null");
5309 final int userHandle = UserHandle.getCallingUserId();
5310 synchronized (this) {
5311 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5312 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5313 admin.keepUninstalledPackages = packageList;
5314 saveSettingsLocked(userHandle);
5315 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5320 public List<String> getKeepUninstalledPackages(ComponentName who) {
5321 Preconditions.checkNotNull(who, "ComponentName is null");
5325 // TODO In split system user mode, allow apps on user 0 to query the list
5326 synchronized (this) {
5327 // Check if this is the device owner who is calling
5328 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5329 return getKeepUninstalledPackagesLocked();
5333 private List<String> getKeepUninstalledPackagesLocked() {
5334 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5335 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5339 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5344 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5345 throw new IllegalArgumentException("Invalid component " + admin
5346 + " for device owner");
5348 synchronized (this) {
5349 enforceCanSetDeviceOwnerLocked(userId);
5351 // Shutting down backup manager service permanently.
5352 long ident = mInjector.binderClearCallingIdentity();
5354 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5355 } catch (RemoteException e) {
5356 throw new IllegalStateException("Failed deactivating backup service.", e);
5358 mInjector.binderRestoreCallingIdentity(ident);
5361 mOwners.setDeviceOwner(admin, ownerName, userId);
5362 mOwners.writeDeviceOwner();
5363 updateDeviceOwnerLocked();
5364 setDeviceOwnerSystemPropertyLocked();
5365 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5367 ident = mInjector.binderClearCallingIdentity();
5369 // TODO Send to system too?
5370 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5372 mInjector.binderRestoreCallingIdentity(ident);
5378 public boolean isDeviceOwner(ComponentName who, int userId) {
5379 synchronized (this) {
5380 return mOwners.hasDeviceOwner()
5381 && mOwners.getDeviceOwnerUserId() == userId
5382 && mOwners.getDeviceOwnerComponent().equals(who);
5386 public boolean isProfileOwner(ComponentName who, int userId) {
5387 final ComponentName profileOwner = getProfileOwner(userId);
5388 return who != null && who.equals(profileOwner);
5392 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5396 if (!callingUserOnly) {
5397 enforceManageUsers();
5399 synchronized (this) {
5400 if (!mOwners.hasDeviceOwner()) {
5403 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
5404 mOwners.getDeviceOwnerUserId()) {
5407 return mOwners.getDeviceOwnerComponent();
5412 public int getDeviceOwnerUserId() {
5414 return UserHandle.USER_NULL;
5416 enforceManageUsers();
5417 synchronized (this) {
5418 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
5423 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
5427 public String getDeviceOwnerName() {
5431 enforceManageUsers();
5432 synchronized (this) {
5433 if (!mOwners.hasDeviceOwner()) {
5436 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
5437 // Should setDeviceOwner/ProfileOwner still take a name?
5438 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
5439 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
5443 // Returns the active device owner or null if there is no device owner.
5445 ActiveAdmin getDeviceOwnerAdminLocked() {
5446 ComponentName component = mOwners.getDeviceOwnerComponent();
5447 if (component == null) {
5451 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
5452 final int n = policy.mAdminList.size();
5453 for (int i = 0; i < n; i++) {
5454 ActiveAdmin admin = policy.mAdminList.get(i);
5455 if (component.equals(admin.info.getComponent())) {
5459 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
5464 public void clearDeviceOwner(String packageName) {
5465 Preconditions.checkNotNull(packageName, "packageName is null");
5466 final int callingUid = mInjector.binderGetCallingUid();
5468 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName, 0);
5469 if (uid != callingUid) {
5470 throw new SecurityException("Invalid packageName");
5472 } catch (NameNotFoundException e) {
5473 throw new SecurityException(e);
5475 synchronized (this) {
5476 if (!mOwners.hasDeviceOwner()
5477 || !mOwners.getDeviceOwnerComponent().getPackageName().equals(packageName)
5478 || (mOwners.getDeviceOwnerUserId() != UserHandle.getUserId(callingUid))) {
5479 throw new SecurityException(
5480 "clearDeviceOwner can only be called by the device owner");
5483 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
5484 if (admin != null) {
5485 admin.disableCamera = false;
5486 admin.userRestrictions = null;
5487 admin.forceEphemeralUsers = false;
5488 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
5491 clearUserPoliciesLocked(new UserHandle(UserHandle.USER_SYSTEM));
5493 mOwners.clearDeviceOwner();
5494 mOwners.writeDeviceOwner();
5495 updateDeviceOwnerLocked();
5496 disableDeviceLoggingIfNotCompliant();
5497 // Reactivate backup service.
5498 long ident = mInjector.binderClearCallingIdentity();
5500 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
5501 } catch (RemoteException e) {
5502 throw new IllegalStateException("Failed reactivating backup service.", e);
5504 mInjector.binderRestoreCallingIdentity(ident);
5510 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
5515 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
5516 throw new IllegalArgumentException("Component " + who
5517 + " not installed for userId:" + userHandle);
5519 synchronized (this) {
5520 enforceCanSetProfileOwnerLocked(userHandle);
5521 mOwners.setProfileOwner(who, ownerName, userHandle);
5522 mOwners.writeProfileOwner(userHandle);
5528 public void clearProfileOwner(ComponentName who) {
5532 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
5533 final int userId = callingUser.getIdentifier();
5534 enforceNotManagedProfile(userId, "clear profile owner");
5535 // Check if this is the profile owner who is calling
5536 final ActiveAdmin admin =
5537 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5538 synchronized (this) {
5539 admin.disableCamera = false;
5540 admin.userRestrictions = null;
5541 clearUserPoliciesLocked(callingUser);
5542 mOwners.removeProfileOwner(userId);
5543 mOwners.writeProfileOwner(userId);
5548 public boolean setDeviceOwnerLockScreenInfo(ComponentName who, String info) {
5549 Preconditions.checkNotNull(who, "ComponentName is null");
5554 synchronized (this) {
5555 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5556 long token = mInjector.binderClearCallingIdentity();
5558 mLockPatternUtils.setDeviceOwnerInfo(info);
5560 mInjector.binderRestoreCallingIdentity(token);
5567 public String getDeviceOwnerLockScreenInfo() {
5568 return mLockPatternUtils.getDeviceOwnerInfo();
5571 private void clearUserPoliciesLocked(UserHandle userHandle) {
5572 int userId = userHandle.getIdentifier();
5573 // Reset some of the user-specific policies
5574 DevicePolicyData policy = getUserData(userId);
5575 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
5576 policy.mDelegatedCertInstallerPackage = null;
5577 policy.mApplicationRestrictionsManagingPackage = null;
5578 policy.mStatusBarDisabled = false;
5579 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
5580 saveSettingsLocked(userId);
5582 final long ident = mInjector.binderClearCallingIdentity();
5584 mIPackageManager.updatePermissionFlagsForAllApps(
5585 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
5586 0 /* flagValues */, userHandle.getIdentifier());
5587 pushUserRestrictions(userHandle.getIdentifier());
5588 } catch (RemoteException re) {
5590 mInjector.binderRestoreCallingIdentity(ident);
5595 public boolean hasUserSetupCompleted() {
5596 return hasUserSetupCompleted(UserHandle.getCallingUserId());
5599 private boolean hasUserSetupCompleted(int userHandle) {
5603 return getUserData(userHandle).mUserSetupComplete;
5607 public int getUserProvisioningState() {
5609 return DevicePolicyManager.STATE_USER_UNMANAGED;
5611 int userHandle = mInjector.userHandleGetCallingUserId();
5612 return getUserProvisioningState(userHandle);
5615 private int getUserProvisioningState(int userHandle) {
5616 return getUserData(userHandle).mUserProvisioningState;
5620 public void setUserProvisioningState(int newState, int userHandle) {
5625 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
5626 && getManagedUserId(userHandle) == -1) {
5627 // No managed device, user or profile, so setting provisioning state makes no sense.
5628 throw new IllegalStateException("Not allowed to change provisioning state unless a "
5629 + "device or profile owner is set.");
5632 synchronized (this) {
5633 boolean transitionCheckNeeded = true;
5635 // Calling identity/permission checks.
5636 final int callingUid = mInjector.binderGetCallingUid();
5637 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
5638 // ADB shell can only move directly from un-managed to finalized as part of directly
5639 // setting profile-owner or device-owner.
5640 if (getUserProvisioningState(userHandle) !=
5641 DevicePolicyManager.STATE_USER_UNMANAGED
5642 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
5643 throw new IllegalStateException("Not allowed to change provisioning state "
5644 + "unless current provisioning state is unmanaged, and new state is "
5647 transitionCheckNeeded = false;
5649 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
5650 mContext.enforceCallingOrSelfPermission(
5651 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
5654 final DevicePolicyData policyData = getUserData(userHandle);
5655 if (transitionCheckNeeded) {
5656 // Optional state transition check for non-ADB case.
5657 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
5659 policyData.mUserProvisioningState = newState;
5660 saveSettingsLocked(userHandle);
5664 private void checkUserProvisioningStateTransition(int currentState, int newState) {
5665 // Valid transitions for normal use-cases.
5666 switch (currentState) {
5667 case DevicePolicyManager.STATE_USER_UNMANAGED:
5668 // Can move to any state from unmanaged (except itself as an edge case)..
5669 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
5673 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
5674 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
5675 // Can only move to finalized from these states.
5676 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
5680 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
5681 // Current user has a managed-profile, but current user is not managed, so
5682 // rather than moving to finalized state, go back to unmanaged once
5683 // profile provisioning is complete.
5684 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
5688 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
5689 // Cannot transition out of finalized.
5693 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
5694 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
5695 + "from state [" + currentState + "]");
5699 public void setProfileEnabled(ComponentName who) {
5703 Preconditions.checkNotNull(who, "ComponentName is null");
5704 final int userHandle = UserHandle.getCallingUserId();
5705 synchronized (this) {
5706 // Check if this is the profile owner who is calling
5707 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5708 int userId = UserHandle.getCallingUserId();
5710 long id = mInjector.binderClearCallingIdentity();
5712 mUserManager.setUserEnabled(userId);
5713 UserInfo parent = mUserManager.getProfileParent(userId);
5714 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
5715 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle));
5716 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
5717 Intent.FLAG_RECEIVER_FOREGROUND);
5718 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
5720 mInjector.binderRestoreCallingIdentity(id);
5726 public void setProfileName(ComponentName who, String profileName) {
5727 Preconditions.checkNotNull(who, "ComponentName is null");
5728 int userId = UserHandle.getCallingUserId();
5729 // Check if this is the profile owner (includes device owner).
5730 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5732 long id = mInjector.binderClearCallingIdentity();
5734 mUserManager.setUserName(userId, profileName);
5736 mInjector.binderRestoreCallingIdentity(id);
5741 public ComponentName getProfileOwner(int userHandle) {
5746 synchronized (this) {
5747 return mOwners.getProfileOwnerComponent(userHandle);
5751 // Returns the active profile owner for this user or null if the current user has no
5754 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
5755 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
5756 if (profileOwner == null) {
5759 DevicePolicyData policy = getUserData(userHandle);
5760 final int n = policy.mAdminList.size();
5761 for (int i = 0; i < n; i++) {
5762 ActiveAdmin admin = policy.mAdminList.get(i);
5763 if (profileOwner.equals(admin.info.getComponent())) {
5771 public String getProfileOwnerName(int userHandle) {
5775 enforceManageUsers();
5776 ComponentName profileOwner = getProfileOwner(userHandle);
5777 if (profileOwner == null) {
5780 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
5784 * Canonical name for a given package.
5786 private String getApplicationLabel(String packageName, int userHandle) {
5787 long token = mInjector.binderClearCallingIdentity();
5789 final Context userContext;
5791 UserHandle handle = new UserHandle(userHandle);
5792 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
5793 } catch (PackageManager.NameNotFoundException nnfe) {
5794 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
5797 ApplicationInfo appInfo = userContext.getApplicationInfo();
5798 CharSequence result = null;
5799 if (appInfo != null) {
5800 PackageManager pm = userContext.getPackageManager();
5801 result = pm.getApplicationLabel(appInfo);
5803 return result != null ? result.toString() : null;
5805 mInjector.binderRestoreCallingIdentity(token);
5810 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
5812 * The profile owner can only be set before the user setup phase has completed,
5815 * - adb if there are not accounts.
5817 private void enforceCanSetProfileOwnerLocked(int userHandle) {
5818 UserInfo info = mUserManager.getUserInfo(userHandle);
5820 // User doesn't exist.
5821 throw new IllegalArgumentException(
5822 "Attempted to set profile owner for invalid userId: " + userHandle);
5824 if (info.isGuest()) {
5825 throw new IllegalStateException("Cannot set a profile owner on a guest");
5827 if (mOwners.hasProfileOwner(userHandle)) {
5828 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
5829 + "is already set.");
5831 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
5832 throw new IllegalStateException("Trying to set the profile owner, but the user "
5833 + "already has a device owner.");
5835 int callingUid = mInjector.binderGetCallingUid();
5836 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
5837 if (hasUserSetupCompleted(userHandle) &&
5838 AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) {
5839 throw new IllegalStateException("Not allowed to set the profile owner because "
5840 + "there are already some accounts on the profile");
5844 mContext.enforceCallingOrSelfPermission(
5845 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
5846 if (hasUserSetupCompleted(userHandle)
5847 && !UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)) {
5848 throw new IllegalStateException("Cannot set the profile owner on a user which is "
5849 + "already set-up");
5854 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
5856 * The device owner can only be set before the setup phase of the primary user has completed,
5857 * except for adb if no accounts or additional users are present on the device.
5859 private void enforceCanSetDeviceOwnerLocked(int userId) {
5860 if (mOwners.hasDeviceOwner()) {
5861 throw new IllegalStateException("Trying to set the device owner, but device owner "
5862 + "is already set.");
5864 if (mOwners.hasProfileOwner(userId)) {
5865 throw new IllegalStateException("Trying to set the device owner, but the user already "
5866 + "has a profile owner.");
5868 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
5869 throw new IllegalStateException("User not running: " + userId);
5872 int callingUid = mInjector.binderGetCallingUid();
5873 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
5874 if (!hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
5877 // STOPSHIP Do proper check in split user mode
5878 if (!mInjector.userManagerIsSplitSystemUser()) {
5879 if (mUserManager.getUserCount() > 1) {
5880 throw new IllegalStateException(
5881 "Not allowed to set the device owner because there "
5882 + "are already several users on the device");
5884 if (AccountManager.get(mContext).getAccounts().length > 0) {
5885 throw new IllegalStateException(
5886 "Not allowed to set the device owner because there "
5887 + "are already some accounts on the device");
5892 // STOPSHIP check the caller UID with userId
5894 mContext.enforceCallingOrSelfPermission(
5895 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
5896 // STOPSHIP Do proper check in split user mode
5897 if (!mInjector.userManagerIsSplitSystemUser()) {
5898 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
5899 throw new IllegalStateException("Cannot set the device owner if the device is "
5900 + "already set-up");
5905 private void enforceManageUsers() {
5906 final int callingUid = mInjector.binderGetCallingUid();
5907 if (!(UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
5908 || callingUid == Process.ROOT_UID)) {
5909 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
5913 private void enforceFullCrossUsersPermission(int userHandle) {
5914 enforceSystemUserOrPermission(userHandle,
5915 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
5918 private void enforceCrossUsersPermission(int userHandle) {
5919 enforceSystemUserOrPermission(userHandle,
5920 android.Manifest.permission.INTERACT_ACROSS_USERS);
5923 private void enforceSystemUserOrPermission(int userHandle, String permission) {
5924 if (userHandle < 0) {
5925 throw new IllegalArgumentException("Invalid userId " + userHandle);
5927 final int callingUid = mInjector.binderGetCallingUid();
5928 if (userHandle == UserHandle.getUserId(callingUid)) {
5931 if (!(UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
5932 || callingUid == Process.ROOT_UID)) {
5933 mContext.enforceCallingOrSelfPermission(permission,
5934 "Must be system or have " + permission + " permission");
5938 private void enforceManagedProfile(int userHandle, String message) {
5939 if(!isManagedProfile(userHandle)) {
5940 throw new SecurityException("You can not " + message + " outside a managed profile.");
5944 private void enforceNotManagedProfile(int userHandle, String message) {
5945 if(isManagedProfile(userHandle)) {
5946 throw new SecurityException("You can not " + message + " for a managed profile.");
5950 private int getProfileParentId(int userHandle) {
5951 final long ident = mInjector.binderClearCallingIdentity();
5953 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
5954 return parentUser != null ? parentUser.id : userHandle;
5956 mInjector.binderRestoreCallingIdentity(ident);
5960 private int getCredentialOwner(int userHandle, boolean parent) {
5961 final long ident = mInjector.binderClearCallingIdentity();
5964 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
5965 if (parentProfile != null) {
5966 userHandle = parentProfile.id;
5969 return mUserManager.getCredentialOwnerProfile(userHandle);
5971 mInjector.binderRestoreCallingIdentity(ident);
5975 private boolean isManagedProfile(int userHandle) {
5976 long ident = mInjector.binderClearCallingIdentity();
5978 return mUserManager.getUserInfo(userHandle).isManagedProfile();
5980 mInjector.binderRestoreCallingIdentity(ident);
5984 private void enableIfNecessary(String packageName, int userId) {
5986 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
5987 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
5989 if (ai.enabledSetting
5990 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
5991 mIPackageManager.setApplicationEnabledSetting(packageName,
5992 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
5993 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
5995 } catch (RemoteException e) {
6000 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6001 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6002 != PackageManager.PERMISSION_GRANTED) {
6004 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6005 + mInjector.binderGetCallingPid()
6006 + ", uid=" + mInjector.binderGetCallingUid());
6010 synchronized (this) {
6011 pw.println("Current Device Policy Manager state:");
6012 mOwners.dump(" ", pw);
6013 int userCount = mUserData.size();
6014 for (int u = 0; u < userCount; u++) {
6015 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6017 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6018 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6019 final int N = policy.mAdminList.size();
6020 for (int i=0; i<N; i++) {
6021 ActiveAdmin ap = policy.mAdminList.get(i);
6023 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6028 if (!policy.mRemovingAdmins.isEmpty()) {
6029 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6030 + policy.mRemovingAdmins);
6034 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6040 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6041 ComponentName activity) {
6042 Preconditions.checkNotNull(who, "ComponentName is null");
6043 final int userHandle = UserHandle.getCallingUserId();
6044 synchronized (this) {
6045 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6047 long id = mInjector.binderClearCallingIdentity();
6049 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6050 } catch (RemoteException re) {
6053 mInjector.binderRestoreCallingIdentity(id);
6059 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6060 Preconditions.checkNotNull(who, "ComponentName is null");
6061 final int userHandle = UserHandle.getCallingUserId();
6062 synchronized (this) {
6063 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6065 long id = mInjector.binderClearCallingIdentity();
6067 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6068 } catch (RemoteException re) {
6071 mInjector.binderRestoreCallingIdentity(id);
6077 public void setApplicationRestrictionsManagingPackage(ComponentName admin, String packageName) {
6078 final int userHandle = mInjector.userHandleGetCallingUserId();
6079 synchronized (this) {
6080 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6081 DevicePolicyData policy = getUserData(userHandle);
6082 policy.mApplicationRestrictionsManagingPackage = packageName;
6083 saveSettingsLocked(userHandle);
6088 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6089 final int userHandle = mInjector.userHandleGetCallingUserId();
6090 synchronized (this) {
6091 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6092 DevicePolicyData policy = getUserData(userHandle);
6093 return policy.mApplicationRestrictionsManagingPackage;
6098 public boolean isCallerApplicationRestrictionsManagingPackage() {
6099 final int callingUid = mInjector.binderGetCallingUid();
6100 final int userHandle = UserHandle.getUserId(callingUid);
6101 synchronized (this) {
6102 final DevicePolicyData policy = getUserData(userHandle);
6103 if (policy.mApplicationRestrictionsManagingPackage == null) {
6108 int uid = mContext.getPackageManager().getPackageUidAsUser(
6109 policy.mApplicationRestrictionsManagingPackage, userHandle);
6110 return uid == callingUid;
6111 } catch (NameNotFoundException e) {
6117 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6119 synchronized (this) {
6120 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6122 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6123 throw new SecurityException(
6124 "No admin component given, and caller cannot manage application restrictions "
6125 + "for other apps.");
6130 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6131 enforceCanManageApplicationRestrictions(who);
6133 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6134 final long id = mInjector.binderClearCallingIdentity();
6136 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6138 mInjector.binderRestoreCallingIdentity(id);
6143 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6144 PersistableBundle args) {
6148 Preconditions.checkNotNull(admin, "admin is null");
6149 Preconditions.checkNotNull(agent, "agent is null");
6150 final int userHandle = UserHandle.getCallingUserId();
6151 enforceNotManagedProfile(userHandle, "set trust agent configuration");
6152 synchronized (this) {
6153 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6154 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
6155 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6156 saveSettingsLocked(userHandle);
6161 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6162 ComponentName agent, int userHandle) {
6166 Preconditions.checkNotNull(agent, "agent null");
6167 enforceFullCrossUsersPermission(userHandle);
6169 synchronized (this) {
6170 final String componentName = agent.flattenToString();
6171 if (admin != null) {
6172 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle);
6173 if (ap == null) return null;
6174 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6175 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6176 List<PersistableBundle> result = new ArrayList<PersistableBundle>();
6177 result.add(trustAgentInfo.options);
6181 // Return strictest policy for this user and profiles that are visible from this user.
6182 final List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
6183 List<PersistableBundle> result = null;
6185 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6186 // of the options. If any admin doesn't have options, discard options for the rest
6188 boolean allAdminsHaveOptions = true;
6189 for (UserInfo userInfo : profiles) {
6190 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
6191 final int N = policy.mAdminList.size();
6192 for (int i=0; i < N; i++) {
6193 final ActiveAdmin active = policy.mAdminList.get(i);
6194 final boolean disablesTrust = (active.disabledKeyguardFeatures
6195 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6196 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6197 if (info != null && info.options != null && !info.options.isEmpty()) {
6198 if (disablesTrust) {
6199 if (result == null) {
6200 result = new ArrayList<PersistableBundle>();
6202 result.add(info.options);
6204 Log.w(LOG_TAG, "Ignoring admin " + active.info
6205 + " because it has trust options but doesn't declare "
6206 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6208 } else if (disablesTrust) {
6209 allAdminsHaveOptions = false;
6214 return allAdminsHaveOptions ? result : null;
6219 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6220 Preconditions.checkNotNull(who, "ComponentName is null");
6221 synchronized (this) {
6222 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6224 int userHandle = UserHandle.getCallingUserId();
6225 DevicePolicyData userData = getUserData(userHandle);
6226 userData.mRestrictionsProvider = permissionProvider;
6227 saveSettingsLocked(userHandle);
6232 public ComponentName getRestrictionsProvider(int userHandle) {
6233 synchronized (this) {
6234 if (!UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID)) {
6235 throw new SecurityException("Only the system can query the permission provider");
6237 DevicePolicyData userData = getUserData(userHandle);
6238 return userData != null ? userData.mRestrictionsProvider : null;
6243 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6244 Preconditions.checkNotNull(who, "ComponentName is null");
6245 int callingUserId = UserHandle.getCallingUserId();
6246 synchronized (this) {
6247 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6249 long id = mInjector.binderClearCallingIdentity();
6251 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6252 if (parent == null) {
6253 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6257 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6258 mIPackageManager.addCrossProfileIntentFilter(
6259 filter, who.getPackageName(), callingUserId, parent.id, 0);
6261 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6262 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6263 parent.id, callingUserId, 0);
6265 } catch (RemoteException re) {
6268 mInjector.binderRestoreCallingIdentity(id);
6274 public void clearCrossProfileIntentFilters(ComponentName who) {
6275 Preconditions.checkNotNull(who, "ComponentName is null");
6276 int callingUserId = UserHandle.getCallingUserId();
6277 synchronized (this) {
6278 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6279 long id = mInjector.binderClearCallingIdentity();
6281 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6282 if (parent == null) {
6283 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6287 // Removing those that go from the managed profile to the parent.
6288 mIPackageManager.clearCrossProfileIntentFilters(
6289 callingUserId, who.getPackageName());
6290 // And those that go from the parent to the managed profile.
6291 // If we want to support multiple managed profiles, we will have to only remove
6292 // those that have callingUserId as their target.
6293 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6294 } catch (RemoteException re) {
6297 mInjector.binderRestoreCallingIdentity(id);
6303 * @return true if all packages in enabledPackages are either in the list
6304 * permittedList or are a system app.
6306 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6307 List<String> permittedList) {
6308 int userIdToCheck = UserHandle.getCallingUserId();
6309 long id = mInjector.binderClearCallingIdentity();
6311 // If we have an enabled packages list for a managed profile the packages
6312 // we should check are installed for the parent user.
6313 UserInfo user = mUserManager.getUserInfo(userIdToCheck);
6314 if (user.isManagedProfile()) {
6315 userIdToCheck = user.profileGroupId;
6318 for (String enabledPackage : enabledPackages) {
6319 boolean systemService = false;
6321 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
6322 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
6323 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6324 } catch (RemoteException e) {
6325 Log.i(LOG_TAG, "Can't talk to package managed", e);
6327 if (!systemService && !permittedList.contains(enabledPackage)) {
6332 mInjector.binderRestoreCallingIdentity(id);
6337 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
6338 // Not using AccessibilityManager.getInstance because that guesses
6339 // at the user you require based on callingUid and caches for a given
6341 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
6342 IAccessibilityManager service = iBinder == null
6343 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
6344 return new AccessibilityManager(mContext, service, userId);
6348 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
6352 Preconditions.checkNotNull(who, "ComponentName is null");
6354 if (packageList != null) {
6355 int userId = UserHandle.getCallingUserId();
6356 List<AccessibilityServiceInfo> enabledServices = null;
6357 long id = mInjector.binderClearCallingIdentity();
6359 UserInfo user = mUserManager.getUserInfo(userId);
6360 if (user.isManagedProfile()) {
6361 userId = user.profileGroupId;
6363 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
6364 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
6365 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
6367 mInjector.binderRestoreCallingIdentity(id);
6370 if (enabledServices != null) {
6371 List<String> enabledPackages = new ArrayList<String>();
6372 for (AccessibilityServiceInfo service : enabledServices) {
6373 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
6375 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
6376 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
6377 + "because it contains already enabled accesibility services.");
6383 synchronized (this) {
6384 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6385 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6386 admin.permittedAccessiblityServices = packageList;
6387 saveSettingsLocked(UserHandle.getCallingUserId());
6393 public List getPermittedAccessibilityServices(ComponentName who) {
6397 Preconditions.checkNotNull(who, "ComponentName is null");
6399 synchronized (this) {
6400 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6401 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6402 return admin.permittedAccessiblityServices;
6407 public List getPermittedAccessibilityServicesForUser(int userId) {
6411 synchronized (this) {
6412 List<String> result = null;
6413 // If we have multiple profiles we return the intersection of the
6414 // permitted lists. This can happen in cases where we have a device
6415 // and profile owner.
6416 List<UserInfo> profiles = mUserManager.getProfiles(userId);
6417 final int PROFILES_SIZE = profiles.size();
6418 for (int i = 0; i < PROFILES_SIZE; ++i) {
6419 // Just loop though all admins, only device or profiles
6420 // owners can have permitted lists set.
6421 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
6422 final int N = policy.mAdminList.size();
6423 for (int j = 0; j < N; j++) {
6424 ActiveAdmin admin = policy.mAdminList.get(j);
6425 List<String> fromAdmin = admin.permittedAccessiblityServices;
6426 if (fromAdmin != null) {
6427 if (result == null) {
6428 result = new ArrayList<String>(fromAdmin);
6430 result.retainAll(fromAdmin);
6436 // If we have a permitted list add all system accessibility services.
6437 if (result != null) {
6438 long id = mInjector.binderClearCallingIdentity();
6440 UserInfo user = mUserManager.getUserInfo(userId);
6441 if (user.isManagedProfile()) {
6442 userId = user.profileGroupId;
6444 AccessibilityManager accessibilityManager =
6445 getAccessibilityManagerForUser(userId);
6446 List<AccessibilityServiceInfo> installedServices =
6447 accessibilityManager.getInstalledAccessibilityServiceList();
6449 if (installedServices != null) {
6450 for (AccessibilityServiceInfo service : installedServices) {
6451 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
6452 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
6453 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6454 result.add(serviceInfo.packageName);
6459 mInjector.binderRestoreCallingIdentity(id);
6467 private boolean checkCallerIsCurrentUserOrProfile() {
6468 int callingUserId = UserHandle.getCallingUserId();
6469 long token = mInjector.binderClearCallingIdentity();
6471 UserInfo currentUser;
6472 UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
6474 currentUser = mInjector.getIActivityManager().getCurrentUser();
6475 } catch (RemoteException e) {
6476 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
6480 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
6481 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
6482 + "of a user that isn't the foreground user.");
6485 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
6486 Slog.e(LOG_TAG, "Cannot set permitted input methods "
6487 + "of a user that isn't the foreground user.");
6491 mInjector.binderRestoreCallingIdentity(token);
6497 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
6501 Preconditions.checkNotNull(who, "ComponentName is null");
6503 // TODO When InputMethodManager supports per user calls remove
6504 // this restriction.
6505 if (!checkCallerIsCurrentUserOrProfile()) {
6509 if (packageList != null) {
6510 // InputMethodManager fetches input methods for current user.
6511 // So this can only be set when calling user is the current user
6512 // or parent is current user in case of managed profiles.
6513 InputMethodManager inputMethodManager =
6514 mContext.getSystemService(InputMethodManager.class);
6515 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
6517 if (enabledImes != null) {
6518 List<String> enabledPackages = new ArrayList<String>();
6519 for (InputMethodInfo ime : enabledImes) {
6520 enabledPackages.add(ime.getPackageName());
6522 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
6523 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
6524 + "because it contains already enabled input method.");
6530 synchronized (this) {
6531 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6532 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6533 admin.permittedInputMethods = packageList;
6534 saveSettingsLocked(UserHandle.getCallingUserId());
6540 public List getPermittedInputMethods(ComponentName who) {
6544 Preconditions.checkNotNull(who, "ComponentName is null");
6546 synchronized (this) {
6547 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6548 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6549 return admin.permittedInputMethods;
6554 public List getPermittedInputMethodsForCurrentUser() {
6555 UserInfo currentUser;
6557 currentUser = mInjector.getIActivityManager().getCurrentUser();
6558 } catch (RemoteException e) {
6559 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
6560 // Activity managed is dead, just allow all IMEs
6564 int userId = currentUser.id;
6565 synchronized (this) {
6566 List<String> result = null;
6567 // If we have multiple profiles we return the intersection of the
6568 // permitted lists. This can happen in cases where we have a device
6569 // and profile owner.
6570 List<UserInfo> profiles = mUserManager.getProfiles(userId);
6571 final int PROFILES_SIZE = profiles.size();
6572 for (int i = 0; i < PROFILES_SIZE; ++i) {
6573 // Just loop though all admins, only device or profiles
6574 // owners can have permitted lists set.
6575 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
6576 final int N = policy.mAdminList.size();
6577 for (int j = 0; j < N; j++) {
6578 ActiveAdmin admin = policy.mAdminList.get(j);
6579 List<String> fromAdmin = admin.permittedInputMethods;
6580 if (fromAdmin != null) {
6581 if (result == null) {
6582 result = new ArrayList<String>(fromAdmin);
6584 result.retainAll(fromAdmin);
6590 // If we have a permitted list add all system input methods.
6591 if (result != null) {
6592 InputMethodManager inputMethodManager =
6593 mContext.getSystemService(InputMethodManager.class);
6594 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
6595 long id = mInjector.binderClearCallingIdentity();
6598 for (InputMethodInfo ime : imes) {
6599 ServiceInfo serviceInfo = ime.getServiceInfo();
6600 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
6601 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6602 result.add(serviceInfo.packageName);
6607 mInjector.binderRestoreCallingIdentity(id);
6615 public UserHandle createUser(ComponentName who, String name) {
6616 Preconditions.checkNotNull(who, "ComponentName is null");
6617 synchronized (this) {
6618 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6620 long id = mInjector.binderClearCallingIdentity();
6622 UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */);
6623 if (userInfo != null) {
6624 return userInfo.getUserHandle();
6628 mInjector.binderRestoreCallingIdentity(id);
6634 public UserHandle createAndInitializeUser(ComponentName who, String name,
6635 String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) {
6636 UserHandle user = createUser(who, name);
6640 long id = mInjector.binderClearCallingIdentity();
6642 String profileOwnerPkg = profileOwnerComponent.getPackageName();
6644 final int userHandle = user.getIdentifier();
6646 // Install the profile owner if not present.
6647 if (!mIPackageManager.isPackageAvailable(profileOwnerPkg, userHandle)) {
6648 mIPackageManager.installExistingPackageAsUser(profileOwnerPkg, userHandle);
6651 // Start user in background.
6652 mInjector.getIActivityManager().startUserInBackground(userHandle);
6653 } catch (RemoteException e) {
6654 Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e);
6657 setActiveAdmin(profileOwnerComponent, true, userHandle, adminExtras);
6658 setProfileOwner(profileOwnerComponent, ownerName, userHandle);
6661 mInjector.binderRestoreCallingIdentity(id);
6665 private void sendAdminEnabledBroadcastLocked(int userHandle) {
6666 DevicePolicyData policyData = getUserData(userHandle);
6667 if (policyData.mAdminBroadcastPending) {
6668 // Send the initialization data to profile owner and delete the data
6669 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
6670 if (admin != null) {
6671 PersistableBundle initBundle = policyData.mInitBundle;
6672 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
6673 initBundle == null ? null : new Bundle(initBundle), null);
6675 policyData.mInitBundle = null;
6676 policyData.mAdminBroadcastPending = false;
6677 saveSettingsLocked(userHandle);
6682 public UserHandle createAndManageUser(ComponentName admin, String name,
6683 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
6684 Preconditions.checkNotNull(admin, "admin is null");
6685 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
6686 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
6687 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
6688 + admin + " are not in the same package");
6691 UserHandle user = null;
6692 synchronized (this) {
6693 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6695 final long id = mInjector.binderClearCallingIdentity();
6697 int userInfoFlags = 0;
6698 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
6699 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
6701 UserInfo userInfo = mUserManager.createUser(name, userInfoFlags);
6702 if (userInfo != null) {
6703 user = userInfo.getUserHandle();
6706 mInjector.binderRestoreCallingIdentity(id);
6713 final long id = mInjector.binderClearCallingIdentity();
6715 final String adminPkg = admin.getPackageName();
6717 final int userHandle = user.getIdentifier();
6719 // Install the profile owner if not present.
6720 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
6721 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
6723 } catch (RemoteException e) {
6724 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
6725 + "removing created user", e);
6726 mUserManager.removeUser(user.getIdentifier());
6730 setActiveAdmin(profileOwner, true, userHandle);
6731 // User is not started yet, the broadcast by setActiveAdmin will not be received.
6732 // So we store adminExtras for broadcasting when the user starts for first time.
6733 synchronized(this) {
6734 DevicePolicyData policyData = getUserData(userHandle);
6735 policyData.mInitBundle = adminExtras;
6736 policyData.mAdminBroadcastPending = true;
6737 saveSettingsLocked(userHandle);
6739 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
6740 setProfileOwner(profileOwner, ownerName, userHandle);
6742 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
6743 Settings.Secure.putIntForUser(mContext.getContentResolver(),
6744 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
6749 mInjector.binderRestoreCallingIdentity(id);
6754 public boolean removeUser(ComponentName who, UserHandle userHandle) {
6755 Preconditions.checkNotNull(who, "ComponentName is null");
6756 synchronized (this) {
6757 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6759 long id = mInjector.binderClearCallingIdentity();
6761 return mUserManager.removeUser(userHandle.getIdentifier());
6763 mInjector.binderRestoreCallingIdentity(id);
6769 public boolean switchUser(ComponentName who, UserHandle userHandle) {
6770 Preconditions.checkNotNull(who, "ComponentName is null");
6771 synchronized (this) {
6772 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6774 long id = mInjector.binderClearCallingIdentity();
6776 int userId = UserHandle.USER_SYSTEM;
6777 if (userHandle != null) {
6778 userId = userHandle.getIdentifier();
6780 return mInjector.getIActivityManager().switchUser(userId);
6781 } catch (RemoteException e) {
6782 Log.e(LOG_TAG, "Couldn't switch user", e);
6785 mInjector.binderRestoreCallingIdentity(id);
6791 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
6792 enforceCanManageApplicationRestrictions(who);
6794 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6795 final long id = mInjector.binderClearCallingIdentity();
6797 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
6798 // if no restrictions were saved, mUserManager.getApplicationRestrictions
6799 // returns null, but DPM method should return an empty Bundle as per JavaDoc
6800 return bundle != null ? bundle : Bundle.EMPTY;
6802 mInjector.binderRestoreCallingIdentity(id);
6807 public boolean setPackageSuspended(ComponentName who, String packageName,
6808 boolean suspended) {
6809 Preconditions.checkNotNull(who, "ComponentName is null");
6810 int callingUserId = UserHandle.getCallingUserId();
6811 synchronized (this) {
6812 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6814 long id = mInjector.binderClearCallingIdentity();
6816 return mIPackageManager.setPackageSuspendedAsUser(
6817 packageName, suspended, callingUserId);
6818 } catch (RemoteException re) {
6819 // Shouldn't happen.
6820 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
6822 mInjector.binderRestoreCallingIdentity(id);
6829 public boolean getPackageSuspended(ComponentName who, String packageName) {
6830 Preconditions.checkNotNull(who, "ComponentName is null");
6831 int callingUserId = UserHandle.getCallingUserId();
6832 synchronized (this) {
6833 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6835 long id = mInjector.binderClearCallingIdentity();
6837 ApplicationInfo appInfo = mIPackageManager.getApplicationInfo(
6838 packageName, 0, callingUserId);
6839 return appInfo != null &&
6840 (appInfo.flags & ApplicationInfo.FLAG_SUSPENDED) != 0;
6841 } catch (RemoteException re) {
6842 // Shouldn't happen.
6843 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
6845 mInjector.binderRestoreCallingIdentity(id);
6852 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
6853 Preconditions.checkNotNull(who, "ComponentName is null");
6854 final int userHandle = mInjector.userHandleGetCallingUserId();
6855 synchronized (this) {
6856 ActiveAdmin activeAdmin =
6857 getActiveAdminForCallerLocked(who,
6858 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6859 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
6860 if (isDeviceOwner) {
6861 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
6862 throw new SecurityException("Device owner cannot set user restriction " + key);
6864 } else { // profile owner
6865 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
6866 throw new SecurityException("Profile owner cannot set user restriction " + key);
6870 // Save the restriction to ActiveAdmin.
6871 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
6872 saveSettingsLocked(userHandle);
6874 pushUserRestrictions(userHandle);
6876 sendChangedNotification(userHandle);
6880 private void pushUserRestrictions(int userId) {
6881 synchronized (this) {
6882 final Bundle global;
6883 final Bundle local = new Bundle();
6884 if (mOwners.isDeviceOwnerUserId(userId)) {
6885 global = new Bundle();
6887 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6888 if (deviceOwner == null) {
6889 return; // Shouldn't happen.
6892 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
6894 // DO can disable camera globally.
6895 if (deviceOwner.disableCamera) {
6896 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
6901 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
6902 if (profileOwner != null) {
6903 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
6906 // Also merge in *local* camera restriction.
6907 if (getCameraDisabled(/* who= */ null,
6908 userId, /* mergeDeviceOwnerRestriction= */ false)) {
6909 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
6911 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
6916 public Bundle getUserRestrictions(ComponentName who, int userHandle) {
6917 Preconditions.checkNotNull(who, "ComponentName is null");
6918 enforceFullCrossUsersPermission(userHandle);
6919 synchronized (this) {
6920 ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(who, userHandle);
6921 if (activeAdmin == null) {
6922 throw new SecurityException("No active admin: " + activeAdmin);
6924 if (activeAdmin.getUid() != mInjector.binderGetCallingUid()) {
6925 mContext.enforceCallingOrSelfPermission(
6926 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
6927 "Calling uid " + mInjector.binderGetCallingUid() + " neither owns the admin"
6928 + " " + who + " nor has MANAGE_PROFILE_AND_DEVICE_OWNERS permission");
6930 return activeAdmin.userRestrictions;
6935 public boolean setApplicationHidden(ComponentName who, String packageName,
6937 Preconditions.checkNotNull(who, "ComponentName is null");
6938 int callingUserId = UserHandle.getCallingUserId();
6939 synchronized (this) {
6940 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6942 long id = mInjector.binderClearCallingIdentity();
6944 return mIPackageManager.setApplicationHiddenSettingAsUser(
6945 packageName, hidden, callingUserId);
6946 } catch (RemoteException re) {
6948 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
6950 mInjector.binderRestoreCallingIdentity(id);
6957 public boolean isApplicationHidden(ComponentName who, String packageName) {
6958 Preconditions.checkNotNull(who, "ComponentName is null");
6959 int callingUserId = UserHandle.getCallingUserId();
6960 synchronized (this) {
6961 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6963 long id = mInjector.binderClearCallingIdentity();
6965 return mIPackageManager.getApplicationHiddenSettingAsUser(
6966 packageName, callingUserId);
6967 } catch (RemoteException re) {
6969 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
6971 mInjector.binderRestoreCallingIdentity(id);
6978 public void enableSystemApp(ComponentName who, String packageName) {
6979 Preconditions.checkNotNull(who, "ComponentName is null");
6980 synchronized (this) {
6981 // This API can only be called by an active device admin,
6982 // so try to retrieve it to check that the caller is one.
6983 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6985 int userId = UserHandle.getCallingUserId();
6986 long id = mInjector.binderClearCallingIdentity();
6990 Slog.v(LOG_TAG, "installing " + packageName + " for "
6994 int parentUserId = getProfileParentId(userId);
6995 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
6996 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7000 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7002 } catch (RemoteException re) {
7004 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7006 mInjector.binderRestoreCallingIdentity(id);
7012 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7013 Preconditions.checkNotNull(who, "ComponentName is null");
7014 synchronized (this) {
7015 // This API can only be called by an active device admin,
7016 // so try to retrieve it to check that the caller is one.
7017 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7019 int userId = UserHandle.getCallingUserId();
7020 long id = mInjector.binderClearCallingIdentity();
7023 int parentUserId = getProfileParentId(userId);
7024 List<ResolveInfo> activitiesToEnable = mIPackageManager.queryIntentActivities(
7026 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7031 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7033 int numberOfAppsInstalled = 0;
7034 if (activitiesToEnable != null) {
7035 for (ResolveInfo info : activitiesToEnable) {
7036 if (info.activityInfo != null) {
7037 String packageName = info.activityInfo.packageName;
7038 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7039 numberOfAppsInstalled++;
7040 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7042 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7048 return numberOfAppsInstalled;
7049 } catch (RemoteException e) {
7051 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7054 mInjector.binderRestoreCallingIdentity(id);
7059 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7060 throws RemoteException {
7061 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7063 if (appInfo == null) {
7064 throw new IllegalArgumentException("The application " + packageName +
7065 " is not present on this device");
7067 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7071 public void setAccountManagementDisabled(ComponentName who, String accountType,
7076 Preconditions.checkNotNull(who, "ComponentName is null");
7077 synchronized (this) {
7078 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7079 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7081 ap.accountTypesWithManagementDisabled.add(accountType);
7083 ap.accountTypesWithManagementDisabled.remove(accountType);
7085 saveSettingsLocked(UserHandle.getCallingUserId());
7090 public String[] getAccountTypesWithManagementDisabled() {
7091 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7095 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7096 enforceFullCrossUsersPermission(userId);
7100 synchronized (this) {
7101 DevicePolicyData policy = getUserData(userId);
7102 final int N = policy.mAdminList.size();
7103 ArraySet<String> resultSet = new ArraySet<>();
7104 for (int i = 0; i < N; i++) {
7105 ActiveAdmin admin = policy.mAdminList.get(i);
7106 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7108 return resultSet.toArray(new String[resultSet.size()]);
7113 public void setUninstallBlocked(ComponentName who, String packageName,
7114 boolean uninstallBlocked) {
7115 Preconditions.checkNotNull(who, "ComponentName is null");
7116 final int userId = UserHandle.getCallingUserId();
7117 synchronized (this) {
7118 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7120 long id = mInjector.binderClearCallingIdentity();
7122 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7123 } catch (RemoteException re) {
7124 // Shouldn't happen.
7125 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7127 mInjector.binderRestoreCallingIdentity(id);
7133 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7134 // This function should return true if and only if the package is blocked by
7135 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7136 // when the package is a system app, or when it is an active device admin.
7137 final int userId = UserHandle.getCallingUserId();
7139 synchronized (this) {
7141 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7144 long id = mInjector.binderClearCallingIdentity();
7146 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7147 } catch (RemoteException re) {
7148 // Shouldn't happen.
7149 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7151 mInjector.binderRestoreCallingIdentity(id);
7158 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7162 Preconditions.checkNotNull(who, "ComponentName is null");
7163 synchronized (this) {
7164 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7165 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7166 if (admin.disableCallerId != disabled) {
7167 admin.disableCallerId = disabled;
7168 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7174 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7178 Preconditions.checkNotNull(who, "ComponentName is null");
7179 synchronized (this) {
7180 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7181 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7182 return admin.disableCallerId;
7187 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7188 enforceCrossUsersPermission(userId);
7189 synchronized (this) {
7190 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7191 return (admin != null) ? admin.disableCallerId : false;
7196 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7200 Preconditions.checkNotNull(who, "ComponentName is null");
7201 synchronized (this) {
7202 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7203 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7204 if (admin.disableContactsSearch != disabled) {
7205 admin.disableContactsSearch = disabled;
7206 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7212 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7216 Preconditions.checkNotNull(who, "ComponentName is null");
7217 synchronized (this) {
7218 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7219 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7220 return admin.disableContactsSearch;
7225 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7226 enforceCrossUsersPermission(userId);
7227 synchronized (this) {
7228 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7229 return (admin != null) ? admin.disableContactsSearch : false;
7234 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7235 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7236 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7237 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7238 final int callingUserId = UserHandle.getCallingUserId();
7240 final long ident = mInjector.binderClearCallingIdentity();
7242 synchronized (this) {
7243 final int managedUserId = getManagedUserId(callingUserId);
7244 if (managedUserId < 0) {
7247 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7250 "Cross-profile contacts access disabled for user " + managedUserId);
7254 ContactsInternal.startQuickContactWithErrorToastForUser(
7255 mContext, intent, new UserHandle(managedUserId));
7258 mInjector.binderRestoreCallingIdentity(ident);
7263 * @return true if cross-profile QuickContact is disabled
7265 private boolean isCrossProfileQuickContactDisabled(int userId) {
7266 return getCrossProfileCallerIdDisabledForUser(userId)
7267 && getCrossProfileContactsSearchDisabledForUser(userId);
7271 * @return the user ID of the managed user that is linked to the current user, if any.
7274 public int getManagedUserId(int callingUserId) {
7276 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7279 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7280 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7281 continue; // Caller user self, or not a managed profile. Skip.
7284 Log.v(LOG_TAG, "Managed user=" + ui.id);
7289 Log.v(LOG_TAG, "Managed user not found.");
7295 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7299 Preconditions.checkNotNull(who, "ComponentName is null");
7300 synchronized (this) {
7301 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7302 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7303 if (admin.disableBluetoothContactSharing != disabled) {
7304 admin.disableBluetoothContactSharing = disabled;
7305 saveSettingsLocked(UserHandle.getCallingUserId());
7311 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
7315 Preconditions.checkNotNull(who, "ComponentName is null");
7316 synchronized (this) {
7317 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7318 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7319 return admin.disableBluetoothContactSharing;
7324 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
7325 // TODO: Should there be a check to make sure this relationship is
7326 // within a profile group?
7327 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
7328 synchronized (this) {
7329 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7330 return (admin != null) ? admin.disableBluetoothContactSharing : false;
7335 * Sets which packages may enter lock task mode.
7337 * This function can only be called by the device owner.
7338 * @param packages The list of packages allowed to enter lock task mode.
7341 public void setLockTaskPackages(ComponentName who, String[] packages)
7342 throws SecurityException {
7343 Preconditions.checkNotNull(who, "ComponentName is null");
7344 synchronized (this) {
7345 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7347 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
7348 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
7352 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
7353 DevicePolicyData policy = getUserData(userHandle);
7354 policy.mLockTaskPackages = packages;
7356 // Store the settings persistently.
7357 saveSettingsLocked(userHandle);
7358 updateLockTaskPackagesLocked(packages, userHandle);
7362 * This function returns the list of components allowed to start the task lock mode.
7365 public String[] getLockTaskPackages(ComponentName who) {
7366 Preconditions.checkNotNull(who, "ComponentName is null");
7367 synchronized (this) {
7368 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7369 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
7370 final List<String> packages = getLockTaskPackagesLocked(userHandle);
7371 return packages.toArray(new String[packages.size()]);
7375 private List<String> getLockTaskPackagesLocked(int userHandle) {
7376 final DevicePolicyData policy = getUserData(userHandle);
7377 return policy.mLockTaskPackages;
7381 * This function lets the caller know whether the given package is allowed to start the
7383 * @param pkg The package to check
7386 public boolean isLockTaskPermitted(String pkg) {
7387 // Get current user's devicepolicy
7388 int uid = mInjector.binderGetCallingUid();
7389 int userHandle = UserHandle.getUserId(uid);
7390 DevicePolicyData policy = getUserData(userHandle);
7391 synchronized (this) {
7392 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
7393 String lockTaskPackage = policy.mLockTaskPackages.get(i);
7395 // If the given package equals one of the packages stored our list,
7396 // we allow this package to start lock task mode.
7397 if (lockTaskPackage.equals(pkg)) {
7406 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
7407 if (!UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID)) {
7408 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
7410 synchronized (this) {
7411 final DevicePolicyData policy = getUserData(userHandle);
7412 Bundle adminExtras = new Bundle();
7413 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
7414 for (ActiveAdmin admin : policy.mAdminList) {
7415 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
7416 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
7417 if (ownsDevice || ownsProfile) {
7419 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
7422 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
7430 public void setGlobalSetting(ComponentName who, String setting, String value) {
7431 Preconditions.checkNotNull(who, "ComponentName is null");
7433 synchronized (this) {
7434 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7436 // Some settings are no supported any more. However we do not want to throw a
7437 // SecurityException to avoid breaking apps.
7438 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
7439 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
7443 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
7444 throw new SecurityException(String.format(
7445 "Permission denial: device owners cannot update %1$s", setting));
7448 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
7449 // ignore if it contradicts an existing policy
7450 long timeMs = getMaximumTimeToLock(
7451 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
7452 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
7457 long id = mInjector.binderClearCallingIdentity();
7459 mInjector.settingsGlobalPutString(setting, value);
7461 mInjector.binderRestoreCallingIdentity(id);
7467 public void setSecureSetting(ComponentName who, String setting, String value) {
7468 Preconditions.checkNotNull(who, "ComponentName is null");
7469 int callingUserId = mInjector.userHandleGetCallingUserId();
7471 synchronized (this) {
7472 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7474 if (isDeviceOwner(who, callingUserId)) {
7475 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
7476 throw new SecurityException(String.format(
7477 "Permission denial: Device owners cannot update %1$s", setting));
7479 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
7480 throw new SecurityException(String.format(
7481 "Permission denial: Profile owners cannot update %1$s", setting));
7484 long id = mInjector.binderClearCallingIdentity();
7486 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
7488 mInjector.binderRestoreCallingIdentity(id);
7494 public void setMasterVolumeMuted(ComponentName who, boolean on) {
7495 Preconditions.checkNotNull(who, "ComponentName is null");
7496 synchronized (this) {
7497 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7498 int userId = UserHandle.getCallingUserId();
7499 long identity = mInjector.binderClearCallingIdentity();
7501 IAudioService iAudioService = IAudioService.Stub.asInterface(
7502 ServiceManager.getService(Context.AUDIO_SERVICE));
7503 iAudioService.setMasterMute(on, 0, mContext.getPackageName(), userId);
7504 } catch (RemoteException re) {
7505 Slog.e(LOG_TAG, "Failed to setMasterMute", re);
7507 mInjector.binderRestoreCallingIdentity(identity);
7513 public boolean isMasterVolumeMuted(ComponentName who) {
7514 Preconditions.checkNotNull(who, "ComponentName is null");
7515 synchronized (this) {
7516 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7518 AudioManager audioManager =
7519 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
7520 return audioManager.isMasterMute();
7525 public void setUserIcon(ComponentName who, Bitmap icon) {
7526 synchronized (this) {
7527 Preconditions.checkNotNull(who, "ComponentName is null");
7528 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7530 int userId = UserHandle.getCallingUserId();
7531 long id = mInjector.binderClearCallingIdentity();
7533 mUserManagerInternal.setUserIcon(userId, icon);
7535 mInjector.binderRestoreCallingIdentity(id);
7541 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
7542 Preconditions.checkNotNull(who, "ComponentName is null");
7543 synchronized (this) {
7544 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7546 final int userId = UserHandle.getCallingUserId();
7548 long ident = mInjector.binderClearCallingIdentity();
7550 // disallow disabling the keyguard if a password is currently set
7551 if (disabled && mLockPatternUtils.isSecure(userId)) {
7554 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
7556 mInjector.binderRestoreCallingIdentity(ident);
7562 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
7563 int userId = UserHandle.getCallingUserId();
7564 synchronized (this) {
7565 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7566 DevicePolicyData policy = getUserData(userId);
7567 if (policy.mStatusBarDisabled != disabled) {
7568 if (!setStatusBarDisabledInternal(disabled, userId)) {
7571 policy.mStatusBarDisabled = disabled;
7572 saveSettingsLocked(userId);
7578 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
7579 long ident = mInjector.binderClearCallingIdentity();
7581 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
7582 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
7583 if (statusBarService != null) {
7584 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
7585 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
7586 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
7587 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
7590 } catch (RemoteException e) {
7591 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
7593 mInjector.binderRestoreCallingIdentity(ident);
7599 * We need to update the internal state of whether a user has completed setup once. After
7600 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
7601 * as we don't trust any apps that might try to reset it.
7603 * Unfortunately, we don't know which user's setup state was changed, so we write all of
7606 void updateUserSetupComplete() {
7607 List<UserInfo> users = mUserManager.getUsers(true);
7608 final int N = users.size();
7609 for (int i = 0; i < N; i++) {
7610 int userHandle = users.get(i).id;
7611 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
7613 DevicePolicyData policy = getUserData(userHandle);
7614 if (!policy.mUserSetupComplete) {
7615 policy.mUserSetupComplete = true;
7616 synchronized (this) {
7617 saveSettingsLocked(userHandle);
7624 private class SetupContentObserver extends ContentObserver {
7626 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
7627 Settings.Secure.USER_SETUP_COMPLETE);
7628 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
7629 Settings.Global.DEVICE_PROVISIONED);
7631 public SetupContentObserver(Handler handler) {
7635 void register(ContentResolver resolver) {
7636 resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
7637 resolver.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
7641 public void onChange(boolean selfChange, Uri uri) {
7642 if (mUserSetupComplete.equals(uri)) {
7643 updateUserSetupComplete();
7644 } else if (mDeviceProvisioned.equals(uri)) {
7645 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
7646 // is delayed until device is marked as provisioned.
7647 setDeviceOwnerSystemPropertyLocked();
7653 final class LocalService extends DevicePolicyManagerInternal {
7654 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
7657 public List<String> getCrossProfileWidgetProviders(int profileId) {
7658 synchronized (DevicePolicyManagerService.this) {
7659 if (mOwners == null) {
7660 return Collections.emptyList();
7662 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
7663 if (ownerComponent == null) {
7664 return Collections.emptyList();
7667 DevicePolicyData policy = getUserDataUnchecked(profileId);
7668 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
7670 if (admin == null || admin.crossProfileWidgetProviders == null
7671 || admin.crossProfileWidgetProviders.isEmpty()) {
7672 return Collections.emptyList();
7675 return admin.crossProfileWidgetProviders;
7680 public void addOnCrossProfileWidgetProvidersChangeListener(
7681 OnCrossProfileWidgetProvidersChangeListener listener) {
7682 synchronized (DevicePolicyManagerService.this) {
7683 if (mWidgetProviderListeners == null) {
7684 mWidgetProviderListeners = new ArrayList<>();
7686 if (!mWidgetProviderListeners.contains(listener)) {
7687 mWidgetProviderListeners.add(listener);
7693 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
7694 synchronized(DevicePolicyManagerService.this) {
7695 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
7699 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
7700 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
7701 synchronized (DevicePolicyManagerService.this) {
7702 listeners = new ArrayList<>(mWidgetProviderListeners);
7704 final int listenerCount = listeners.size();
7705 for (int i = 0; i < listenerCount; i++) {
7706 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
7707 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
7713 * Returns true if specified admin is allowed to limit passwords and has a
7714 * {@code passwordQuality} of at least {@code minPasswordQuality}
7716 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
7717 if (admin.passwordQuality < minPasswordQuality) {
7720 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
7724 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
7725 if (policy != null && !policy.isValid()) {
7726 throw new IllegalArgumentException("Invalid system update policy.");
7728 synchronized (this) {
7729 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7730 if (policy == null) {
7731 mOwners.clearSystemUpdatePolicy();
7733 mOwners.setSystemUpdatePolicy(policy);
7735 mOwners.writeDeviceOwner();
7737 mContext.sendBroadcastAsUser(
7738 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
7743 public SystemUpdatePolicy getSystemUpdatePolicy() {
7744 synchronized (this) {
7745 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
7746 if (policy != null && !policy.isValid()) {
7747 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
7755 * Checks if the caller of the method is the device owner app.
7757 * @param callerUid UID of the caller.
7758 * @return true if the caller is the device owner app
7761 boolean isCallerDeviceOwner(int callerUid) {
7762 synchronized (this) {
7763 if (!mOwners.hasDeviceOwner()) {
7766 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
7769 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
7771 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
7773 for (String pkg : pkgs) {
7774 if (deviceOwnerPackageName.equals(pkg)) {
7784 public void notifyPendingSystemUpdate(long updateReceivedTime) {
7785 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
7786 "Only the system update service can broadcast update information");
7788 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
7789 Slog.w(LOG_TAG, "Only the system update service in the system user " +
7790 "can broadcast update information.");
7793 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
7794 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
7795 updateReceivedTime);
7797 synchronized (this) {
7798 final String deviceOwnerPackage =
7799 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
7801 if (deviceOwnerPackage == null) {
7804 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
7806 ActivityInfo[] receivers = null;
7808 receivers = mContext.getPackageManager().getPackageInfo(
7809 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
7810 } catch (NameNotFoundException e) {
7811 Log.e(LOG_TAG, "Cannot find device owner package", e);
7813 if (receivers != null) {
7814 long ident = mInjector.binderClearCallingIdentity();
7816 for (int i = 0; i < receivers.length; i++) {
7817 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
7818 intent.setComponent(new ComponentName(deviceOwnerPackage,
7819 receivers[i].name));
7820 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
7824 mInjector.binderRestoreCallingIdentity(ident);
7831 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
7832 int userId = UserHandle.getCallingUserId();
7833 synchronized (this) {
7834 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7835 DevicePolicyData userPolicy = getUserData(userId);
7836 if (userPolicy.mPermissionPolicy != policy) {
7837 userPolicy.mPermissionPolicy = policy;
7838 saveSettingsLocked(userId);
7844 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
7845 int userId = UserHandle.getCallingUserId();
7846 synchronized (this) {
7847 DevicePolicyData userPolicy = getUserData(userId);
7848 return userPolicy.mPermissionPolicy;
7853 public boolean setPermissionGrantState(ComponentName admin, String packageName,
7854 String permission, int grantState) throws RemoteException {
7855 UserHandle user = mInjector.binderGetCallingUserHandle();
7856 synchronized (this) {
7857 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7858 long ident = mInjector.binderClearCallingIdentity();
7860 if (getTargetSdk(packageName, user.getIdentifier())
7861 < android.os.Build.VERSION_CODES.M) {
7864 final PackageManager packageManager = mContext.getPackageManager();
7865 switch (grantState) {
7866 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
7867 packageManager.grantRuntimePermission(packageName, permission, user);
7868 packageManager.updatePermissionFlags(permission, packageName,
7869 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
7870 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
7873 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
7874 packageManager.revokeRuntimePermission(packageName,
7876 packageManager.updatePermissionFlags(permission, packageName,
7877 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
7878 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
7881 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
7882 packageManager.updatePermissionFlags(permission, packageName,
7883 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
7887 } catch (SecurityException se) {
7890 mInjector.binderRestoreCallingIdentity(ident);
7896 public int getPermissionGrantState(ComponentName admin, String packageName,
7897 String permission) throws RemoteException {
7898 PackageManager packageManager = mContext.getPackageManager();
7900 UserHandle user = mInjector.binderGetCallingUserHandle();
7901 synchronized (this) {
7902 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7903 long ident = mInjector.binderClearCallingIdentity();
7905 int granted = mIPackageManager.checkPermission(permission,
7906 packageName, user.getIdentifier());
7907 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
7908 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
7909 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
7910 // Not controlled by policy
7911 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
7913 // Policy controlled so return result based on permission grant state
7914 return granted == PackageManager.PERMISSION_GRANTED
7915 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
7916 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
7919 mInjector.binderRestoreCallingIdentity(ident);
7924 boolean isPackageInstalledForUser(String packageName, int userHandle) {
7926 PackageInfo pi = mIPackageManager.getPackageInfo(packageName, 0, userHandle);
7927 return (pi != null) && (pi.applicationInfo.flags != 0);
7928 } catch (RemoteException re) {
7929 throw new RuntimeException("Package manager has died", re);
7934 public boolean isProvisioningAllowed(String action) {
7935 final int callingUserId = mInjector.userHandleGetCallingUserId();
7936 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
7937 if (!hasFeatureManagedUsers()) {
7940 synchronized (this) {
7941 if (mOwners.hasDeviceOwner()) {
7942 if (!mInjector.userManagerIsSplitSystemUser()) {
7943 // Only split-system-user systems support managed-profiles in combination with
7947 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
7948 // Only system device-owner supports managed-profiles. Non-system device-owner
7952 if (callingUserId == UserHandle.USER_SYSTEM) {
7953 // Managed-profiles cannot be setup on the system user, only regular users.
7958 if (getProfileOwner(callingUserId) != null) {
7959 // Managed user cannot have a managed profile.
7962 final long ident = mInjector.binderClearCallingIdentity();
7964 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
7968 mInjector.binderRestoreCallingIdentity(ident);
7971 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
7972 return isDeviceOwnerProvisioningAllowed(callingUserId);
7973 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
7974 if (!hasFeatureManagedUsers()) {
7977 if (!mInjector.userManagerIsSplitSystemUser()) {
7978 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
7981 if (callingUserId == UserHandle.USER_SYSTEM) {
7982 // System user cannot be a managed user.
7985 if (hasUserSetupCompleted(callingUserId)) {
7989 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
7990 if (!mInjector.userManagerIsSplitSystemUser()) {
7991 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
7994 return isDeviceOwnerProvisioningAllowed(callingUserId);
7996 throw new IllegalArgumentException("Unknown provisioning action " + action);
7999 private boolean isDeviceOwnerProvisioningAllowed(int callingUserId) {
8000 synchronized (this) {
8001 if (mOwners.hasDeviceOwner()) {
8005 if (getProfileOwner(callingUserId) != null) {
8008 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
8011 if (callingUserId != UserHandle.USER_SYSTEM) {
8012 // Device owner provisioning can only be initiated from system user.
8018 private boolean hasFeatureManagedUsers() {
8020 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS);
8021 } catch (RemoteException e) {
8027 public String getWifiMacAddress() {
8028 // Make sure caller has DO.
8029 synchronized (this) {
8030 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8033 final long ident = mInjector.binderClearCallingIdentity();
8035 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8036 if (wifiInfo == null) {
8039 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8041 mInjector.binderRestoreCallingIdentity(ident);
8046 * Returns the target sdk version number that the given packageName was built for
8047 * in the given user.
8049 private int getTargetSdk(String packageName, int userId) throws RemoteException {
8050 final ApplicationInfo ai = mIPackageManager
8051 .getApplicationInfo(packageName, 0, userId);
8052 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8053 return targetSdkVersion;
8057 public boolean isManagedProfile(ComponentName admin) {
8058 synchronized (this) {
8059 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8061 final int callingUserId = mInjector.userHandleGetCallingUserId();
8062 final UserInfo user;
8063 long ident = mInjector.binderClearCallingIdentity();
8065 user = mUserManager.getUserInfo(callingUserId);
8067 mInjector.binderRestoreCallingIdentity(ident);
8069 return user != null && user.isManagedProfile();
8073 public boolean isSystemOnlyUser(ComponentName admin) {
8074 synchronized (this) {
8075 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8077 final int callingUserId = mInjector.userHandleGetCallingUserId();
8078 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8082 public void reboot(ComponentName admin) {
8083 Preconditions.checkNotNull(admin);
8084 // Make sure caller has DO.
8085 synchronized (this) {
8086 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8088 long ident = mInjector.binderClearCallingIdentity();
8090 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8092 mInjector.binderRestoreCallingIdentity(ident);
8097 public void setShortSupportMessage(@NonNull ComponentName who, String message) {
8101 Preconditions.checkNotNull(who, "ComponentName is null");
8102 final int userHandle = mInjector.userHandleGetCallingUserId();
8103 synchronized (this) {
8104 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8105 mInjector.binderGetCallingUid());
8106 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8107 admin.shortSupportMessage = message;
8108 saveSettingsLocked(userHandle);
8114 public String getShortSupportMessage(@NonNull ComponentName who) {
8118 Preconditions.checkNotNull(who, "ComponentName is null");
8119 synchronized (this) {
8120 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8121 mInjector.binderGetCallingUid());
8122 return admin.shortSupportMessage;
8127 public void setLongSupportMessage(@NonNull ComponentName who, String message) {
8131 Preconditions.checkNotNull(who, "ComponentName is null");
8132 final int userHandle = mInjector.userHandleGetCallingUserId();
8133 synchronized (this) {
8134 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8135 mInjector.binderGetCallingUid());
8136 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8137 admin.longSupportMessage = message;
8138 saveSettingsLocked(userHandle);
8144 public String getLongSupportMessage(@NonNull ComponentName who) {
8148 Preconditions.checkNotNull(who, "ComponentName is null");
8149 synchronized (this) {
8150 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8151 mInjector.binderGetCallingUid());
8152 return admin.longSupportMessage;
8157 public String getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8161 Preconditions.checkNotNull(who, "ComponentName is null");
8162 if (!UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID)) {
8163 throw new SecurityException("Only the system can query support message for user");
8165 synchronized (this) {
8166 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8167 if (admin != null) {
8168 return admin.shortSupportMessage;
8175 public String getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8179 Preconditions.checkNotNull(who, "ComponentName is null");
8180 if (!UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID)) {
8181 throw new SecurityException("Only the system can query support message for user");
8183 synchronized (this) {
8184 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8185 if (admin != null) {
8186 return admin.longSupportMessage;
8193 public void setOrganizationColor(@NonNull ComponentName who, int color) {
8197 Preconditions.checkNotNull(who, "ComponentName is null");
8198 final int userHandle = mInjector.userHandleGetCallingUserId();
8199 enforceManagedProfile(userHandle, "set organization color");
8200 synchronized (this) {
8201 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8202 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8203 admin.organizationColor = color;
8204 saveSettingsLocked(userHandle);
8209 public int getOrganizationColor(@NonNull ComponentName who) {
8211 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8213 Preconditions.checkNotNull(who, "ComponentName is null");
8214 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
8215 synchronized (this) {
8216 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8217 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8218 return admin.organizationColor;
8223 public int getOrganizationColorForUser(int userHandle) {
8225 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8227 enforceFullCrossUsersPermission(userHandle);
8228 enforceManagedProfile(userHandle, "get organization color");
8229 synchronized (this) {
8230 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8231 return (profileOwner != null)
8232 ? profileOwner.organizationColor
8233 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
8238 public void setOrganizationName(@NonNull ComponentName who, String text) {
8242 Preconditions.checkNotNull(who, "ComponentName is null");
8243 final int userHandle = mInjector.userHandleGetCallingUserId();
8244 enforceManagedProfile(userHandle, "set organization name");
8245 synchronized (this) {
8246 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8247 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8248 if (!TextUtils.equals(admin.organizationName, text)) {
8249 admin.organizationName = TextUtils.nullIfEmpty(text);
8250 saveSettingsLocked(userHandle);
8256 public String getOrganizationName(@NonNull ComponentName who) {
8260 Preconditions.checkNotNull(who, "ComponentName is null");
8261 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
8262 synchronized(this) {
8263 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8264 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8265 return admin.organizationName;
8270 public String getOrganizationNameForUser(int userHandle) {
8274 enforceFullCrossUsersPermission(userHandle);
8275 enforceManagedProfile(userHandle, "get organization name");
8276 synchronized (this) {
8277 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8278 return (profileOwner != null)
8279 ? profileOwner.organizationName
8285 public void setAffiliationIds(ComponentName admin, List<String> ids) {
8286 final Set<String> affiliationIds = new ArraySet<String>(ids);
8287 final int callingUserId = mInjector.userHandleGetCallingUserId();
8289 synchronized (this) {
8290 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8291 getUserData(callingUserId).mAffiliationIds = affiliationIds;
8292 saveSettingsLocked(callingUserId);
8293 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
8294 // Affiliation ids specified by the device owner are additionally stored in
8295 // UserHandle.USER_SYSTEM's DevicePolicyData.
8296 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
8297 saveSettingsLocked(UserHandle.USER_SYSTEM);
8303 public boolean isAffiliatedUser() {
8304 final int callingUserId = mInjector.userHandleGetCallingUserId();
8306 synchronized (this) {
8307 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
8308 // The user that the DO is installed on is always affiliated.
8311 final ComponentName profileOwner = getProfileOwner(callingUserId);
8312 if (profileOwner == null
8313 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
8316 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
8317 final Set<String> deviceAffiliationIds =
8318 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
8319 for (String id : userAffiliationIds) {
8320 if (deviceAffiliationIds.contains(id)) {
8328 private void disableDeviceLoggingIfNotCompliant() {
8329 if (!isDeviceOwnerManagedSingleUserDevice()) {
8330 mInjector.securityLogSetLoggingEnabledProperty(false);
8331 Slog.w(LOG_TAG, "Device logging turned off as it's no longer a single user device.");
8336 public void setDeviceLoggingEnabled(ComponentName admin, boolean enabled) {
8337 Preconditions.checkNotNull(admin);
8338 ensureDeviceOwnerManagingSingleUser(admin);
8340 synchronized (this) {
8341 mInjector.securityLogSetLoggingEnabledProperty(enabled);
8343 mSecurityLogMonitor.start();
8345 mSecurityLogMonitor.stop();
8351 public boolean getDeviceLoggingEnabled(ComponentName admin) {
8352 Preconditions.checkNotNull(admin);
8353 synchronized (this) {
8354 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8355 return SecurityLog.getLoggingEnabledProperty();
8360 public ParceledListSlice<SecurityEvent> retrievePreviousDeviceLogs(ComponentName admin) {
8361 Preconditions.checkNotNull(admin);
8362 ensureDeviceOwnerManagingSingleUser(admin);
8364 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
8366 SecurityLog.readPreviousEvents(output);
8367 return new ParceledListSlice<SecurityEvent>(output);
8368 } catch (IOException e) {
8369 Slog.w(LOG_TAG, "Fail to read previous events" , e);
8370 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
8375 public ParceledListSlice<SecurityEvent> retrieveDeviceLogs(ComponentName admin) {
8376 Preconditions.checkNotNull(admin);
8377 ensureDeviceOwnerManagingSingleUser(admin);
8379 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
8380 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;