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 android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
25 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
27 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
28 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
29 import static org.xmlpull.v1.XmlPullParser.END_TAG;
30 import static org.xmlpull.v1.XmlPullParser.TEXT;
32 import android.Manifest.permission;
33 import android.accessibilityservice.AccessibilityServiceInfo;
34 import android.accounts.AccountManager;
35 import android.annotation.IntDef;
36 import android.annotation.NonNull;
37 import android.annotation.Nullable;
38 import android.annotation.UserIdInt;
39 import android.app.Activity;
40 import android.app.ActivityManager;
41 import android.app.ActivityManagerNative;
42 import android.app.AlarmManager;
43 import android.app.AppGlobals;
44 import android.app.IActivityManager;
45 import android.app.Notification;
46 import android.app.NotificationManager;
47 import android.app.PendingIntent;
48 import android.app.StatusBarManager;
49 import android.app.admin.DeviceAdminInfo;
50 import android.app.admin.DeviceAdminReceiver;
51 import android.app.admin.DevicePolicyManager;
52 import android.app.admin.DevicePolicyManagerInternal;
53 import android.app.admin.IDevicePolicyManager;
54 import android.app.admin.SecurityLog;
55 import android.app.admin.SecurityLog.SecurityEvent;
56 import android.app.admin.SystemUpdatePolicy;
57 import android.app.backup.IBackupManager;
58 import android.content.BroadcastReceiver;
59 import android.content.ComponentName;
60 import android.content.ContentResolver;
61 import android.content.Context;
62 import android.content.Intent;
63 import android.content.IntentFilter;
64 import android.content.pm.ActivityInfo;
65 import android.content.pm.ApplicationInfo;
66 import android.content.pm.IPackageManager;
67 import android.content.pm.PackageInfo;
68 import android.content.pm.PackageManager;
69 import android.content.pm.PackageManager.NameNotFoundException;
70 import android.content.pm.PackageManagerInternal;
71 import android.content.pm.ParceledListSlice;
72 import android.content.pm.ResolveInfo;
73 import android.content.pm.ServiceInfo;
74 import android.content.pm.UserInfo;
75 import android.database.ContentObserver;
76 import android.graphics.Bitmap;
77 import android.graphics.Color;
78 import android.media.AudioManager;
79 import android.media.IAudioService;
80 import android.net.ConnectivityManager;
81 import android.net.ProxyInfo;
82 import android.net.Uri;
83 import android.net.wifi.WifiInfo;
84 import android.net.wifi.WifiManager;
85 import android.os.AsyncTask;
86 import android.os.Binder;
87 import android.os.Build;
88 import android.os.Build.VERSION_CODES;
89 import android.os.Bundle;
90 import android.os.Environment;
91 import android.os.FileUtils;
92 import android.os.Handler;
93 import android.os.IBinder;
94 import android.os.Looper;
95 import android.os.ParcelFileDescriptor;
96 import android.os.PersistableBundle;
97 import android.os.PowerManager;
98 import android.os.PowerManagerInternal;
99 import android.os.Process;
100 import android.os.RecoverySystem;
101 import android.os.RemoteCallback;
102 import android.os.RemoteException;
103 import android.os.ServiceManager;
104 import android.os.SystemClock;
105 import android.os.SystemProperties;
106 import android.os.UserHandle;
107 import android.os.UserManager;
108 import android.os.UserManagerInternal;
109 import android.os.storage.StorageManager;
110 import android.provider.ContactsContract.QuickContact;
111 import android.provider.ContactsInternal;
112 import android.provider.Settings;
113 import android.security.Credentials;
114 import android.security.IKeyChainAliasCallback;
115 import android.security.IKeyChainService;
116 import android.security.KeyChain;
117 import android.security.KeyChain.KeyChainConnection;
118 import android.service.persistentdata.PersistentDataBlockManager;
119 import android.telephony.TelephonyManager;
120 import android.text.TextUtils;
121 import android.util.ArrayMap;
122 import android.util.ArraySet;
123 import android.util.Log;
124 import android.util.Pair;
125 import android.util.Slog;
126 import android.util.SparseArray;
127 import android.util.Xml;
128 import android.view.IWindowManager;
129 import android.view.accessibility.AccessibilityManager;
130 import android.view.accessibility.IAccessibilityManager;
131 import android.view.inputmethod.InputMethodInfo;
132 import android.view.inputmethod.InputMethodManager;
134 import com.android.internal.R;
135 import com.android.internal.annotations.VisibleForTesting;
136 import com.android.internal.statusbar.IStatusBarService;
137 import com.android.internal.util.FastXmlSerializer;
138 import com.android.internal.util.JournaledFile;
139 import com.android.internal.util.Preconditions;
140 import com.android.internal.util.XmlUtils;
141 import com.android.internal.widget.LockPatternUtils;
142 import com.android.server.LocalServices;
143 import com.android.server.SystemService;
144 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
145 import com.android.server.pm.UserRestrictionsUtils;
146 import com.google.android.collect.Sets;
148 import org.xmlpull.v1.XmlPullParser;
149 import org.xmlpull.v1.XmlPullParserException;
150 import org.xmlpull.v1.XmlSerializer;
152 import java.io.ByteArrayInputStream;
154 import java.io.FileDescriptor;
155 import java.io.FileInputStream;
156 import java.io.FileNotFoundException;
157 import java.io.FileOutputStream;
158 import java.io.IOException;
159 import java.io.PrintWriter;
160 import java.lang.annotation.Retention;
161 import java.lang.annotation.RetentionPolicy;
162 import java.nio.charset.StandardCharsets;
163 import java.security.cert.CertificateException;
164 import java.security.cert.CertificateFactory;
165 import java.security.cert.X509Certificate;
166 import java.text.DateFormat;
167 import java.util.ArrayList;
168 import java.util.Arrays;
169 import java.util.Collections;
170 import java.util.Date;
171 import java.util.List;
172 import java.util.Map.Entry;
173 import java.util.Set;
174 import java.util.concurrent.atomic.AtomicBoolean;
177 * Implementation of the device policy APIs.
179 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
181 private static final String LOG_TAG = "DevicePolicyManagerService";
183 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
185 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
187 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
189 private static final String TAG_STATUS_BAR = "statusbar";
191 private static final String ATTR_DISABLED = "disabled";
193 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
194 "do-not-ask-credentials-on-boot";
196 private static final String TAG_AFFILIATION_ID = "affiliation-id";
198 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
200 private static final String ATTR_VALUE = "value";
202 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
204 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
206 private static final long MS_PER_DAY = 86400 * 1000;
208 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
210 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
211 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
213 private static final int MONITORING_CERT_NOTIFICATION_ID = R.string.ssl_ca_cert_warning;
214 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
216 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
217 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
218 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
219 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
221 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
222 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
223 = "application-restrictions-manager";
226 * System property whose value is either "true" or "false", indicating whether
228 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
230 private static final int STATUS_BAR_DISABLE_MASK =
231 StatusBarManager.DISABLE_EXPAND |
232 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
233 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
234 StatusBarManager.DISABLE_SEARCH;
236 private static final int STATUS_BAR_DISABLE2_MASK =
237 StatusBarManager.DISABLE2_QUICK_SETTINGS;
239 private static final Set<String> SECURE_SETTINGS_WHITELIST;
240 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
241 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
242 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
244 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
245 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
246 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
247 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
249 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
250 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
251 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
253 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
254 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
255 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
256 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
257 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
258 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
259 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
260 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
261 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
263 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
264 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
265 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
266 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
267 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
268 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
272 * Keyguard features that when set on a managed profile that doesn't have its own challenge will
273 * affect the profile's parent user. These can also be set on the managed profile's parent DPM
276 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
277 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
278 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
281 * Keyguard features that when set on a profile affect the profile content or challenge only.
282 * These cannot be set on the managed profile's parent DPM instance
284 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
285 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
287 /** Keyguard features that are allowed to be set on a managed profile */
288 private static final int PROFILE_KEYGUARD_FEATURES =
289 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
291 private static final int CODE_OK = 0;
292 private static final int CODE_HAS_DEVICE_OWNER = 1;
293 private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
294 private static final int CODE_USER_NOT_RUNNING = 3;
295 private static final int CODE_USER_SETUP_COMPLETED = 4;
296 private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
297 private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
298 private static final int CODE_NOT_SYSTEM_USER = 7;
300 @Retention(RetentionPolicy.SOURCE)
301 @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
302 CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
303 private @interface DeviceOwnerPreConditionCode {}
305 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
307 final Context mContext;
308 final Injector mInjector;
309 final IPackageManager mIPackageManager;
310 final UserManager mUserManager;
311 final UserManagerInternal mUserManagerInternal;
312 final TelephonyManager mTelephonyManager;
313 private final LockPatternUtils mLockPatternUtils;
316 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
317 * is requested for user u.
319 private final Set<Pair<String, Integer>> mPackagesToRemove =
320 new ArraySet<Pair<String, Integer>>();
322 final LocalService mLocalService;
324 // Stores and loads state on device and profile owners.
326 final Owners mOwners;
328 private final Binder mToken = new Binder();
331 * Whether or not device admin feature is supported. If it isn't return defaults for all
336 private final SecurityLogMonitor mSecurityLogMonitor;
338 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
339 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
341 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
344 if(mRemoteBugreportServiceIsActive.get()) {
350 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
353 public void onReceive(Context context, Intent intent) {
354 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
355 && mRemoteBugreportServiceIsActive.get()) {
356 onBugreportFinished(intent);
361 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
364 public void onReceive(Context context, Intent intent) {
365 String action = intent.getAction();
366 mInjector.getNotificationManager().cancel(LOG_TAG,
367 RemoteBugreportUtils.NOTIFICATION_ID);
368 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
369 onBugreportSharingAccepted();
370 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
371 onBugreportSharingDeclined();
373 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
377 public static final class Lifecycle extends SystemService {
378 private DevicePolicyManagerService mService;
380 public Lifecycle(Context context) {
382 mService = new DevicePolicyManagerService(context);
386 public void onStart() {
387 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
391 public void onBootPhase(int phase) {
392 mService.systemReady(phase);
396 public void onStartUser(int userHandle) {
397 mService.onStartUser(userHandle);
401 public static class DevicePolicyData {
402 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
403 int mActivePasswordLength = 0;
404 int mActivePasswordUpperCase = 0;
405 int mActivePasswordLowerCase = 0;
406 int mActivePasswordLetters = 0;
407 int mActivePasswordNumeric = 0;
408 int mActivePasswordSymbols = 0;
409 int mActivePasswordNonLetter = 0;
410 int mFailedPasswordAttempts = 0;
413 int mPasswordOwner = -1;
414 long mLastMaximumTimeToLock = -1;
415 boolean mUserSetupComplete = false;
416 int mUserProvisioningState;
417 int mPermissionPolicy;
419 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
420 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
421 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
423 // This is the list of component allowed to start lock task mode.
424 List<String> mLockTaskPackages = new ArrayList<>();
426 boolean mStatusBarDisabled = false;
428 ComponentName mRestrictionsProvider;
430 String mDelegatedCertInstallerPackage;
432 boolean doNotAskCredentialsOnBoot = false;
434 String mApplicationRestrictionsManagingPackage;
436 Set<String> mAffiliationIds = new ArraySet<>();
438 // Used for initialization of users created by createAndManageUsers.
439 boolean mAdminBroadcastPending = false;
440 PersistableBundle mInitBundle = null;
442 public DevicePolicyData(int userHandle) {
443 mUserHandle = userHandle;
447 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
449 final Handler mHandler;
451 BroadcastReceiver mReceiver = new BroadcastReceiver() {
453 public void onReceive(Context context, Intent intent) {
454 final String action = intent.getAction();
455 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
458 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
459 && userHandle == mOwners.getDeviceOwnerUserId()
460 && getDeviceOwnerRemoteBugreportUri() != null) {
461 IntentFilter filterConsent = new IntentFilter();
462 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
463 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
464 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
465 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
466 RemoteBugreportUtils.NOTIFICATION_ID,
467 RemoteBugreportUtils.buildNotification(mContext,
468 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
471 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
472 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
474 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
475 + action + " for user " + userHandle);
477 mHandler.post(new Runnable() {
480 handlePasswordExpirationNotification(userHandle);
484 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
485 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
486 new MonitoringCertNotificationTask().execute(intent);
488 if (Intent.ACTION_USER_ADDED.equals(action)) {
489 disableSecurityLoggingIfNotCompliant();
490 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
491 disableSecurityLoggingIfNotCompliant();
492 removeUserData(userHandle);
493 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
494 synchronized (DevicePolicyManagerService.this) {
495 // Reset the policy data
496 mUserData.remove(userHandle);
497 sendAdminEnabledBroadcastLocked(userHandle);
499 handlePackagesChanged(null /* check all admins */, userHandle);
500 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
501 handlePackagesChanged(null /* check all admins */, userHandle);
502 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
503 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
504 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
505 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
506 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
507 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
508 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
509 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
510 clearWipeProfileNotification();
515 static class ActiveAdmin {
516 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
517 private static final String TAG_DISABLE_CAMERA = "disable-camera";
518 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
519 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
520 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
521 = "disable-bt-contacts-sharing";
522 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
523 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
524 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
525 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
526 private static final String TAG_ACCOUNT_TYPE = "account-type";
527 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
528 = "permitted-accessiblity-services";
529 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
530 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
531 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
532 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
533 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
534 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
535 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
536 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
537 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
538 private static final String TAG_PERMITTED_IMES = "permitted-imes";
539 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
540 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
541 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
542 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
543 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
544 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
545 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
546 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
547 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
548 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
549 private static final String ATTR_VALUE = "value";
550 private static final String TAG_PASSWORD_QUALITY = "password-quality";
551 private static final String TAG_POLICIES = "policies";
552 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
553 "cross-profile-widget-providers";
554 private static final String TAG_PROVIDER = "provider";
555 private static final String TAG_PACKAGE_LIST_ITEM = "item";
556 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
557 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
558 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
559 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
560 private static final String TAG_PARENT_ADMIN = "parent-admin";
561 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
562 private static final String TAG_ORGANIZATION_NAME = "organization-name";
564 final DeviceAdminInfo info;
566 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
568 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
569 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
571 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
572 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
574 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
575 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
577 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
578 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
580 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
581 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
583 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
584 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
586 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
587 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
589 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
590 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
592 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
593 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
595 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
596 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
598 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
599 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
601 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
602 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
604 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
606 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
608 boolean encryptionRequested = false;
609 boolean disableCamera = false;
610 boolean disableCallerId = false;
611 boolean disableContactsSearch = false;
612 boolean disableBluetoothContactSharing = true;
613 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
614 boolean requireAutoTime = false; // Can only be set by a device owner.
615 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
617 ActiveAdmin parentAdmin;
618 final boolean isParent;
620 static class TrustAgentInfo {
621 public PersistableBundle options;
622 TrustAgentInfo(PersistableBundle bundle) {
627 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
629 // The list of permitted accessibility services package namesas set by a profile
630 // or device owner. Null means all accessibility services are allowed, empty means
631 // none except system services are allowed.
632 List<String> permittedAccessiblityServices;
634 // The list of permitted input methods package names as set by a profile or device owner.
635 // Null means all input methods are allowed, empty means none except system imes are
637 List<String> permittedInputMethods;
639 // List of package names to keep cached.
640 List<String> keepUninstalledPackages;
642 // TODO: review implementation decisions with frameworks team
643 boolean specifiesGlobalProxy = false;
644 String globalProxySpec = null;
645 String globalProxyExclusionList = null;
647 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
649 List<String> crossProfileWidgetProviders;
651 Bundle userRestrictions;
653 // Support text provided by the admin to display to the user.
654 String shortSupportMessage = null;
655 String longSupportMessage = null;
657 // Background color of confirm credentials screen. Default: teal.
658 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
659 int organizationColor = DEF_ORGANIZATION_COLOR;
661 // Default title of confirm credentials screen
662 String organizationName = null;
664 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
669 ActiveAdmin getParentActiveAdmin() {
670 Preconditions.checkState(!isParent);
672 if (parentAdmin == null) {
673 parentAdmin = new ActiveAdmin(info, /* parent */ true);
678 boolean hasParentActiveAdmin() {
679 return parentAdmin != null;
682 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
684 public UserHandle getUserHandle() {
685 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
688 void writeToXml(XmlSerializer out)
689 throws IllegalArgumentException, IllegalStateException, IOException {
690 out.startTag(null, TAG_POLICIES);
691 info.writePoliciesToXml(out);
692 out.endTag(null, TAG_POLICIES);
693 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
694 out.startTag(null, TAG_PASSWORD_QUALITY);
695 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
696 out.endTag(null, TAG_PASSWORD_QUALITY);
697 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
698 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
699 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
700 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
702 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
703 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
704 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
705 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
707 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
708 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
709 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
710 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
712 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
713 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
714 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
715 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
717 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
718 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
719 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
720 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
722 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
723 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
724 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
725 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
727 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
728 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
729 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
730 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
732 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
733 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
734 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
735 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
738 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
739 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
740 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
741 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
743 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
744 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
745 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
746 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
748 if (specifiesGlobalProxy) {
749 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
750 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
751 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
752 if (globalProxySpec != null) {
753 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
754 out.attribute(null, ATTR_VALUE, globalProxySpec);
755 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
757 if (globalProxyExclusionList != null) {
758 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
759 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
760 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
763 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
764 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
765 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
766 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
768 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
769 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
770 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
771 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
773 if (encryptionRequested) {
774 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
775 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
776 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
779 out.startTag(null, TAG_DISABLE_CAMERA);
780 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
781 out.endTag(null, TAG_DISABLE_CAMERA);
783 if (disableCallerId) {
784 out.startTag(null, TAG_DISABLE_CALLER_ID);
785 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
786 out.endTag(null, TAG_DISABLE_CALLER_ID);
788 if (disableContactsSearch) {
789 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
790 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
791 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
793 if (!disableBluetoothContactSharing) {
794 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
795 out.attribute(null, ATTR_VALUE,
796 Boolean.toString(disableBluetoothContactSharing));
797 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
799 if (disableScreenCapture) {
800 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
801 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
802 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
804 if (requireAutoTime) {
805 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
806 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
807 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
809 if (forceEphemeralUsers) {
810 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
811 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
812 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
814 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
815 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
816 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
817 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
819 if (!accountTypesWithManagementDisabled.isEmpty()) {
820 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
821 for (String ac : accountTypesWithManagementDisabled) {
822 out.startTag(null, TAG_ACCOUNT_TYPE);
823 out.attribute(null, ATTR_VALUE, ac);
824 out.endTag(null, TAG_ACCOUNT_TYPE);
826 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
828 if (!trustAgentInfos.isEmpty()) {
829 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
830 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
831 for (Entry<String, TrustAgentInfo> entry : set) {
832 TrustAgentInfo trustAgentInfo = entry.getValue();
833 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
834 out.attribute(null, ATTR_VALUE, entry.getKey());
835 if (trustAgentInfo.options != null) {
836 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
838 trustAgentInfo.options.saveToXml(out);
839 } catch (XmlPullParserException e) {
840 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
842 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
844 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
846 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
848 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
849 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
850 final int providerCount = crossProfileWidgetProviders.size();
851 for (int i = 0; i < providerCount; i++) {
852 String provider = crossProfileWidgetProviders.get(i);
853 out.startTag(null, TAG_PROVIDER);
854 out.attribute(null, ATTR_VALUE, provider);
855 out.endTag(null, TAG_PROVIDER);
857 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
859 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
860 permittedAccessiblityServices);
861 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
862 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
863 if (hasUserRestrictions()) {
864 UserRestrictionsUtils.writeRestrictions(
865 out, userRestrictions, TAG_USER_RESTRICTIONS);
867 if (!TextUtils.isEmpty(shortSupportMessage)) {
868 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
869 out.text(shortSupportMessage);
870 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
872 if (!TextUtils.isEmpty(longSupportMessage)) {
873 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
874 out.text(longSupportMessage);
875 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
877 if (parentAdmin != null) {
878 out.startTag(null, TAG_PARENT_ADMIN);
879 parentAdmin.writeToXml(out);
880 out.endTag(null, TAG_PARENT_ADMIN);
882 if (organizationColor != DEF_ORGANIZATION_COLOR) {
883 out.startTag(null, TAG_ORGANIZATION_COLOR);
884 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
885 out.endTag(null, TAG_ORGANIZATION_COLOR);
887 if (organizationName != null) {
888 out.startTag(null, TAG_ORGANIZATION_NAME);
889 out.text(organizationName);
890 out.endTag(null, TAG_ORGANIZATION_NAME);
894 void writePackageListToXml(XmlSerializer out, String outerTag,
895 List<String> packageList)
896 throws IllegalArgumentException, IllegalStateException, IOException {
897 if (packageList == null) {
901 out.startTag(null, outerTag);
902 for (String packageName : packageList) {
903 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
904 out.attribute(null, ATTR_VALUE, packageName);
905 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
907 out.endTag(null, outerTag);
910 void readFromXml(XmlPullParser parser)
911 throws XmlPullParserException, IOException {
912 int outerDepth = parser.getDepth();
914 while ((type=parser.next()) != END_DOCUMENT
915 && (type != END_TAG || parser.getDepth() > outerDepth)) {
916 if (type == END_TAG || type == TEXT) {
919 String tag = parser.getName();
920 if (TAG_POLICIES.equals(tag)) {
921 info.readPoliciesFromXml(parser);
922 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
923 passwordQuality = Integer.parseInt(
924 parser.getAttributeValue(null, ATTR_VALUE));
925 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
926 minimumPasswordLength = Integer.parseInt(
927 parser.getAttributeValue(null, ATTR_VALUE));
928 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
929 passwordHistoryLength = Integer.parseInt(
930 parser.getAttributeValue(null, ATTR_VALUE));
931 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
932 minimumPasswordUpperCase = Integer.parseInt(
933 parser.getAttributeValue(null, ATTR_VALUE));
934 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
935 minimumPasswordLowerCase = Integer.parseInt(
936 parser.getAttributeValue(null, ATTR_VALUE));
937 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
938 minimumPasswordLetters = Integer.parseInt(
939 parser.getAttributeValue(null, ATTR_VALUE));
940 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
941 minimumPasswordNumeric = Integer.parseInt(
942 parser.getAttributeValue(null, ATTR_VALUE));
943 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
944 minimumPasswordSymbols = Integer.parseInt(
945 parser.getAttributeValue(null, ATTR_VALUE));
946 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
947 minimumPasswordNonLetter = Integer.parseInt(
948 parser.getAttributeValue(null, ATTR_VALUE));
949 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
950 maximumTimeToUnlock = Long.parseLong(
951 parser.getAttributeValue(null, ATTR_VALUE));
952 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
953 maximumFailedPasswordsForWipe = Integer.parseInt(
954 parser.getAttributeValue(null, ATTR_VALUE));
955 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
956 specifiesGlobalProxy = Boolean.parseBoolean(
957 parser.getAttributeValue(null, ATTR_VALUE));
958 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
960 parser.getAttributeValue(null, ATTR_VALUE);
961 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
962 globalProxyExclusionList =
963 parser.getAttributeValue(null, ATTR_VALUE);
964 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
965 passwordExpirationTimeout = Long.parseLong(
966 parser.getAttributeValue(null, ATTR_VALUE));
967 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
968 passwordExpirationDate = Long.parseLong(
969 parser.getAttributeValue(null, ATTR_VALUE));
970 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
971 encryptionRequested = Boolean.parseBoolean(
972 parser.getAttributeValue(null, ATTR_VALUE));
973 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
974 disableCamera = Boolean.parseBoolean(
975 parser.getAttributeValue(null, ATTR_VALUE));
976 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
977 disableCallerId = Boolean.parseBoolean(
978 parser.getAttributeValue(null, ATTR_VALUE));
979 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
980 disableContactsSearch = Boolean.parseBoolean(
981 parser.getAttributeValue(null, ATTR_VALUE));
982 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
983 disableBluetoothContactSharing = Boolean.parseBoolean(parser
984 .getAttributeValue(null, ATTR_VALUE));
985 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
986 disableScreenCapture = Boolean.parseBoolean(
987 parser.getAttributeValue(null, ATTR_VALUE));
988 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
989 requireAutoTime = Boolean.parseBoolean(
990 parser.getAttributeValue(null, ATTR_VALUE));
991 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
992 forceEphemeralUsers = Boolean.parseBoolean(
993 parser.getAttributeValue(null, ATTR_VALUE));
994 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
995 disabledKeyguardFeatures = Integer.parseInt(
996 parser.getAttributeValue(null, ATTR_VALUE));
997 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
998 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
999 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1000 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1001 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1002 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
1003 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1004 permittedAccessiblityServices = readPackageList(parser, tag);
1005 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1006 permittedInputMethods = readPackageList(parser, tag);
1007 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1008 keepUninstalledPackages = readPackageList(parser, tag);
1009 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1010 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
1011 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1012 type = parser.next();
1013 if (type == XmlPullParser.TEXT) {
1014 shortSupportMessage = parser.getText();
1016 Log.w(LOG_TAG, "Missing text when loading short support message");
1018 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1019 type = parser.next();
1020 if (type == XmlPullParser.TEXT) {
1021 longSupportMessage = parser.getText();
1023 Log.w(LOG_TAG, "Missing text when loading long support message");
1025 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1026 Preconditions.checkState(!isParent);
1028 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1029 parentAdmin.readFromXml(parser);
1030 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1031 organizationColor = Integer.parseInt(
1032 parser.getAttributeValue(null, ATTR_VALUE));
1033 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1034 type = parser.next();
1035 if (type == XmlPullParser.TEXT) {
1036 organizationName = parser.getText();
1038 Log.w(LOG_TAG, "Missing text when loading organization name");
1041 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1042 XmlUtils.skipCurrentTag(parser);
1047 private List<String> readPackageList(XmlPullParser parser,
1048 String tag) throws XmlPullParserException, IOException {
1049 List<String> result = new ArrayList<String>();
1050 int outerDepth = parser.getDepth();
1052 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1053 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1054 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1057 String outerTag = parser.getName();
1058 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1059 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1060 if (packageName != null) {
1061 result.add(packageName);
1063 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1066 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1072 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1073 throws XmlPullParserException, IOException {
1074 int outerDepthDAM = parser.getDepth();
1076 Set<String> result = new ArraySet<>();
1077 while ((typeDAM=parser.next()) != END_DOCUMENT
1078 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1079 if (typeDAM == END_TAG || typeDAM == TEXT) {
1082 String tagDAM = parser.getName();
1083 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1084 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1086 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1092 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1093 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1094 int outerDepthDAM = parser.getDepth();
1096 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1097 while ((typeDAM=parser.next()) != END_DOCUMENT
1098 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1099 if (typeDAM == END_TAG || typeDAM == TEXT) {
1102 String tagDAM = parser.getName();
1103 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1104 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1105 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1106 result.put(component, trustAgentInfo);
1108 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1114 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1115 throws XmlPullParserException, IOException {
1116 int outerDepthDAM = parser.getDepth();
1118 TrustAgentInfo result = new TrustAgentInfo(null);
1119 while ((typeDAM=parser.next()) != END_DOCUMENT
1120 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1121 if (typeDAM == END_TAG || typeDAM == TEXT) {
1124 String tagDAM = parser.getName();
1125 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1126 PersistableBundle bundle = new PersistableBundle();
1127 bundle.restoreFromXml(parser);
1128 result.options = bundle;
1130 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1136 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1137 throws XmlPullParserException, IOException {
1138 int outerDepthDAM = parser.getDepth();
1140 ArrayList<String> result = null;
1141 while ((typeDAM=parser.next()) != END_DOCUMENT
1142 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1143 if (typeDAM == END_TAG || typeDAM == TEXT) {
1146 String tagDAM = parser.getName();
1147 if (TAG_PROVIDER.equals(tagDAM)) {
1148 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1149 if (result == null) {
1150 result = new ArrayList<>();
1152 result.add(provider);
1154 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1160 boolean hasUserRestrictions() {
1161 return userRestrictions != null && userRestrictions.size() > 0;
1164 Bundle ensureUserRestrictions() {
1165 if (userRestrictions == null) {
1166 userRestrictions = new Bundle();
1168 return userRestrictions;
1171 void dump(String prefix, PrintWriter pw) {
1172 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1173 pw.print(prefix); pw.println("policies:");
1174 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1176 for (int i=0; i<pols.size(); i++) {
1177 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1180 pw.print(prefix); pw.print("passwordQuality=0x");
1181 pw.println(Integer.toHexString(passwordQuality));
1182 pw.print(prefix); pw.print("minimumPasswordLength=");
1183 pw.println(minimumPasswordLength);
1184 pw.print(prefix); pw.print("passwordHistoryLength=");
1185 pw.println(passwordHistoryLength);
1186 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1187 pw.println(minimumPasswordUpperCase);
1188 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1189 pw.println(minimumPasswordLowerCase);
1190 pw.print(prefix); pw.print("minimumPasswordLetters=");
1191 pw.println(minimumPasswordLetters);
1192 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1193 pw.println(minimumPasswordNumeric);
1194 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1195 pw.println(minimumPasswordSymbols);
1196 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1197 pw.println(minimumPasswordNonLetter);
1198 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1199 pw.println(maximumTimeToUnlock);
1200 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1201 pw.println(maximumFailedPasswordsForWipe);
1202 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1203 pw.println(specifiesGlobalProxy);
1204 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1205 pw.println(passwordExpirationTimeout);
1206 pw.print(prefix); pw.print("passwordExpirationDate=");
1207 pw.println(passwordExpirationDate);
1208 if (globalProxySpec != null) {
1209 pw.print(prefix); pw.print("globalProxySpec=");
1210 pw.println(globalProxySpec);
1212 if (globalProxyExclusionList != null) {
1213 pw.print(prefix); pw.print("globalProxyEclusionList=");
1214 pw.println(globalProxyExclusionList);
1216 pw.print(prefix); pw.print("encryptionRequested=");
1217 pw.println(encryptionRequested);
1218 pw.print(prefix); pw.print("disableCamera=");
1219 pw.println(disableCamera);
1220 pw.print(prefix); pw.print("disableCallerId=");
1221 pw.println(disableCallerId);
1222 pw.print(prefix); pw.print("disableContactsSearch=");
1223 pw.println(disableContactsSearch);
1224 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1225 pw.println(disableBluetoothContactSharing);
1226 pw.print(prefix); pw.print("disableScreenCapture=");
1227 pw.println(disableScreenCapture);
1228 pw.print(prefix); pw.print("requireAutoTime=");
1229 pw.println(requireAutoTime);
1230 pw.print(prefix); pw.print("forceEphemeralUsers=");
1231 pw.println(forceEphemeralUsers);
1232 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1233 pw.println(disabledKeyguardFeatures);
1234 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1235 pw.println(crossProfileWidgetProviders);
1236 if (permittedAccessiblityServices != null) {
1237 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1238 pw.println(permittedAccessiblityServices);
1240 if (permittedInputMethods != null) {
1241 pw.print(prefix); pw.print("permittedInputMethods=");
1242 pw.println(permittedInputMethods);
1244 if (keepUninstalledPackages != null) {
1245 pw.print(prefix); pw.print("keepUninstalledPackages=");
1246 pw.println(keepUninstalledPackages);
1248 pw.print(prefix); pw.print("organizationColor=");
1249 pw.println(organizationColor);
1250 if (organizationName != null) {
1251 pw.print(prefix); pw.print("organizationName=");
1252 pw.println(organizationName);
1254 pw.print(prefix); pw.println("userRestrictions:");
1255 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1256 pw.print(prefix); pw.print("isParent=");
1257 pw.println(isParent);
1258 if (parentAdmin != null) {
1259 pw.print(prefix); pw.println("parentAdmin:");
1260 parentAdmin.dump(prefix + " ", pw);
1265 private void handlePackagesChanged(String packageName, int userHandle) {
1266 boolean removed = false;
1267 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1268 DevicePolicyData policy = getUserData(userHandle);
1269 synchronized (this) {
1270 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1271 ActiveAdmin aa = policy.mAdminList.get(i);
1273 // If we're checking all packages or if the specific one we're checking matches,
1274 // then check if the package and receiver still exist.
1275 final String adminPackage = aa.info.getPackageName();
1276 if (packageName == null || packageName.equals(adminPackage)) {
1277 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1278 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1279 PackageManager.MATCH_DIRECT_BOOT_AWARE
1280 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1281 userHandle) == null) {
1283 policy.mAdminList.remove(i);
1284 policy.mAdminMap.remove(aa.info.getComponent());
1287 } catch (RemoteException re) {
1292 validatePasswordOwnerLocked(policy);
1293 saveSettingsLocked(policy.mUserHandle);
1296 // Check if delegated cert installer or app restrictions managing packages are removed.
1297 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1298 policy.mDelegatedCertInstallerPackage = null;
1299 saveSettingsLocked(policy.mUserHandle);
1301 if (isRemovedPackage(
1302 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1303 policy.mApplicationRestrictionsManagingPackage = null;
1304 saveSettingsLocked(policy.mUserHandle);
1308 // The removed admin might have disabled camera, so update user restrictions.
1309 pushUserRestrictions(userHandle);
1313 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1315 return targetPackage != null
1316 && (changedPackage == null || changedPackage.equals(targetPackage))
1317 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1318 } catch (RemoteException e) {
1326 * Unit test will subclass it to inject mocks.
1329 static class Injector {
1331 private final Context mContext;
1333 Injector(Context context) {
1337 Owners newOwners() {
1338 return new Owners(mContext, getUserManager(), getUserManagerInternal());
1341 UserManager getUserManager() {
1342 return UserManager.get(mContext);
1345 UserManagerInternal getUserManagerInternal() {
1346 return LocalServices.getService(UserManagerInternal.class);
1349 PackageManagerInternal getPackageManagerInternal() {
1350 return LocalServices.getService(PackageManagerInternal.class);
1353 NotificationManager getNotificationManager() {
1354 return mContext.getSystemService(NotificationManager.class);
1357 PowerManagerInternal getPowerManagerInternal() {
1358 return LocalServices.getService(PowerManagerInternal.class);
1361 TelephonyManager getTelephonyManager() {
1362 return TelephonyManager.from(mContext);
1365 IWindowManager getIWindowManager() {
1366 return IWindowManager.Stub
1367 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1370 IActivityManager getIActivityManager() {
1371 return ActivityManagerNative.getDefault();
1374 IPackageManager getIPackageManager() {
1375 return AppGlobals.getPackageManager();
1378 IBackupManager getIBackupManager() {
1379 return IBackupManager.Stub.asInterface(
1380 ServiceManager.getService(Context.BACKUP_SERVICE));
1383 IAudioService getIAudioService() {
1384 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1387 LockPatternUtils newLockPatternUtils() {
1388 return new LockPatternUtils(mContext);
1391 boolean storageManagerIsFileBasedEncryptionEnabled() {
1392 return StorageManager.isFileEncryptedNativeOnly();
1395 boolean storageManagerIsNonDefaultBlockEncrypted() {
1396 return StorageManager.isNonDefaultBlockEncrypted();
1399 boolean storageManagerIsEncrypted() {
1400 return StorageManager.isEncrypted();
1403 boolean storageManagerIsEncryptable() {
1404 return StorageManager.isEncryptable();
1407 Looper getMyLooper() {
1408 return Looper.myLooper();
1411 WifiManager getWifiManager() {
1412 return mContext.getSystemService(WifiManager.class);
1415 long binderClearCallingIdentity() {
1416 return Binder.clearCallingIdentity();
1419 void binderRestoreCallingIdentity(long token) {
1420 Binder.restoreCallingIdentity(token);
1423 int binderGetCallingUid() {
1424 return Binder.getCallingUid();
1427 int binderGetCallingPid() {
1428 return Binder.getCallingPid();
1431 UserHandle binderGetCallingUserHandle() {
1432 return Binder.getCallingUserHandle();
1435 boolean binderIsCallingUidMyUid() {
1436 return getCallingUid() == Process.myUid();
1439 final int userHandleGetCallingUserId() {
1440 return UserHandle.getUserId(binderGetCallingUid());
1443 File environmentGetUserSystemDirectory(int userId) {
1444 return Environment.getUserSystemDirectory(userId);
1447 void powerManagerGoToSleep(long time, int reason, int flags) {
1448 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1451 void powerManagerReboot(String reason) {
1452 mContext.getSystemService(PowerManager.class).reboot(reason);
1455 boolean systemPropertiesGetBoolean(String key, boolean def) {
1456 return SystemProperties.getBoolean(key, def);
1459 long systemPropertiesGetLong(String key, long def) {
1460 return SystemProperties.getLong(key, def);
1463 String systemPropertiesGet(String key, String def) {
1464 return SystemProperties.get(key, def);
1467 String systemPropertiesGet(String key) {
1468 return SystemProperties.get(key);
1471 void systemPropertiesSet(String key, String value) {
1472 SystemProperties.set(key, value);
1475 boolean userManagerIsSplitSystemUser() {
1476 return UserManager.isSplitSystemUser();
1479 String getDevicePolicyFilePathForSystemUser() {
1480 return "/data/system/";
1483 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1484 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1485 name, def, userHandle);
1488 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1489 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1490 name, value, userHandle);
1493 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1494 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1495 name, value, userHandle);
1498 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1499 Settings.Global.putStringForUser(mContext.getContentResolver(),
1500 name, value, userHandle);
1503 void settingsSecurePutInt(String name, int value) {
1504 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1507 int settingsGlobalGetInt(String name, int def) {
1508 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1511 void settingsGlobalPutInt(String name, int value) {
1512 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1515 void settingsSecurePutString(String name, String value) {
1516 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1519 void settingsGlobalPutString(String name, String value) {
1520 Settings.Global.putString(mContext.getContentResolver(), name, value);
1523 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1524 SecurityLog.setLoggingEnabledProperty(enabled);
1527 boolean securityLogGetLoggingEnabledProperty() {
1528 return SecurityLog.getLoggingEnabledProperty();
1531 boolean securityLogIsLoggingEnabled() {
1532 return SecurityLog.isLoggingEnabled();
1537 * Instantiates the service.
1539 public DevicePolicyManagerService(Context context) {
1540 this(new Injector(context));
1544 DevicePolicyManagerService(Injector injector) {
1545 mInjector = injector;
1546 mContext = Preconditions.checkNotNull(injector.mContext);
1547 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1548 mOwners = Preconditions.checkNotNull(injector.newOwners());
1550 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1551 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1552 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1553 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1555 mLocalService = new LocalService();
1556 mLockPatternUtils = injector.newLockPatternUtils();
1558 mSecurityLogMonitor = new SecurityLogMonitor(this);
1560 mHasFeature = mContext.getPackageManager()
1561 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1563 // Skip the rest of the initialization
1566 IntentFilter filter = new IntentFilter();
1567 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1568 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1569 filter.addAction(Intent.ACTION_USER_ADDED);
1570 filter.addAction(Intent.ACTION_USER_REMOVED);
1571 filter.addAction(Intent.ACTION_USER_STARTED);
1572 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1573 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1574 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1575 filter = new IntentFilter();
1576 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1577 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1578 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1579 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1580 filter.addDataScheme("package");
1581 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1582 filter = new IntentFilter();
1583 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1584 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1586 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1590 * Creates and loads the policy data from xml.
1591 * @param userHandle the user for whom to load the policy data
1595 DevicePolicyData getUserData(int userHandle) {
1596 synchronized (this) {
1597 DevicePolicyData policy = mUserData.get(userHandle);
1598 if (policy == null) {
1599 policy = new DevicePolicyData(userHandle);
1600 mUserData.append(userHandle, policy);
1601 loadSettingsLocked(policy, userHandle);
1608 * Creates and loads the policy data from xml for data that is shared between
1609 * various profiles of a user. In contrast to {@link #getUserData(int)}
1610 * it allows access to data of users other than the calling user.
1612 * This function should only be used for shared data, e.g. everything regarding
1613 * passwords and should be removed once multiple screen locks are present.
1614 * @param userHandle the user for whom to load the policy data
1617 DevicePolicyData getUserDataUnchecked(int userHandle) {
1618 long ident = mInjector.binderClearCallingIdentity();
1620 return getUserData(userHandle);
1622 mInjector.binderRestoreCallingIdentity(ident);
1626 void removeUserData(int userHandle) {
1627 synchronized (this) {
1628 if (userHandle == UserHandle.USER_SYSTEM) {
1629 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1632 mOwners.removeProfileOwner(userHandle);
1633 mOwners.writeProfileOwner(userHandle);
1635 DevicePolicyData policy = mUserData.get(userHandle);
1636 if (policy != null) {
1637 mUserData.remove(userHandle);
1639 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1640 DEVICE_POLICIES_XML);
1641 policyFile.delete();
1642 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1644 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1648 synchronized (this) {
1650 setDeviceOwnerSystemPropertyLocked();
1651 findOwnerComponentIfNecessaryLocked();
1652 migrateUserRestrictionsIfNecessaryLocked();
1654 // TODO PO may not have a class name either due to b/17652534. Address that too.
1656 updateDeviceOwnerLocked();
1660 private void setDeviceOwnerSystemPropertyLocked() {
1661 // Device owner may still be provisioned, do not set the read-only system property yet.
1662 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1665 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1666 // always false at this point.
1667 if (StorageManager.inCryptKeeperBounce()) {
1671 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1672 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1674 if (mOwners.hasDeviceOwner()) {
1675 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1676 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1677 disableSecurityLoggingIfNotCompliant();
1678 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1679 mSecurityLogMonitor.start();
1682 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1683 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1688 private void findOwnerComponentIfNecessaryLocked() {
1689 if (!mOwners.hasDeviceOwner()) {
1692 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1694 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1695 return; // Already a full component name.
1698 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1699 doComponentName.getPackageName(),
1700 mOwners.getDeviceOwnerUserId());
1701 if (doComponent == null) {
1702 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1704 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1706 mOwners.getDeviceOwnerName(),
1707 mOwners.getDeviceOwnerUserId(),
1708 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1709 mOwners.writeDeviceOwner();
1711 Log.v(LOG_TAG, "Device owner component filled in");
1717 * We didn't use to persist user restrictions for each owners but only persisted in user
1720 private void migrateUserRestrictionsIfNecessaryLocked() {
1721 boolean migrated = false;
1722 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1723 // except for the "system controlled" ones.
1724 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1726 Log.v(LOG_TAG, "Migrating DO user restrictions");
1730 // Migrate user 0 restrictions to DO.
1731 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1733 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1734 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1736 // Push DO user restrictions to user manager.
1737 pushUserRestrictions(UserHandle.USER_SYSTEM);
1739 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1744 // The following restrictions can be set on secondary users by the device owner, so we
1745 // assume they're not from the PO.
1746 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1747 UserManager.DISALLOW_OUTGOING_CALLS,
1748 UserManager.DISALLOW_SMS);
1750 for (UserInfo ui : mUserManager.getUsers()) {
1751 final int userId = ui.id;
1752 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1754 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1758 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1760 final Set<String> exceptionList =
1761 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1763 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1764 exceptionList, /* isDeviceOwner =*/ false);
1766 // Note if a secondary user has no PO but has a DA that disables camera, we
1767 // don't get here and won't push the camera user restriction to UserManager
1768 // here. That's okay because we'll push user restrictions anyway when a user
1769 // starts. But we still do it because we want to let user manager persist
1771 pushUserRestrictions(userId);
1773 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1776 if (VERBOSE_LOG && migrated) {
1777 Log.v(LOG_TAG, "User restrictions migrated.");
1781 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1782 Set<String> exceptionList, boolean isDeviceOwner) {
1783 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1784 user.getIdentifier());
1786 final Bundle newBaseRestrictions = new Bundle();
1787 final Bundle newOwnerRestrictions = new Bundle();
1789 for (String key : origRestrictions.keySet()) {
1790 if (!origRestrictions.getBoolean(key)) {
1793 final boolean canOwnerChange = isDeviceOwner
1794 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1795 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1797 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1798 newBaseRestrictions.putBoolean(key, true);
1800 newOwnerRestrictions.putBoolean(key, true);
1805 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1806 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1807 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1809 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1810 newBaseRestrictions);
1812 if (admin != null) {
1813 admin.ensureUserRestrictions().clear();
1814 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1816 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1818 saveSettingsLocked(user.getIdentifier());
1821 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1822 final DevicePolicyData policy = getUserData(userId);
1823 final int n = policy.mAdminList.size();
1824 ComponentName found = null;
1826 for (int i = 0; i < n; i++) {
1827 final ActiveAdmin admin = policy.mAdminList.get(i);
1828 if (packageName.equals(admin.info.getPackageName())) {
1831 found = admin.info.getComponent();
1837 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1843 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1844 * reminders. Clears alarm if no expirations are configured.
1846 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1847 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1848 final long now = System.currentTimeMillis();
1849 final long timeToExpire = expiration - now;
1850 final long alarmTime;
1851 if (expiration == 0) {
1852 // No expirations are currently configured: Cancel alarm.
1854 } else if (timeToExpire <= 0) {
1855 // The password has already expired: Repeat every 24 hours.
1856 alarmTime = now + MS_PER_DAY;
1858 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1859 // the expiration time.
1860 long alarmInterval = timeToExpire % MS_PER_DAY;
1861 if (alarmInterval == 0) {
1862 alarmInterval = MS_PER_DAY;
1864 alarmTime = now + alarmInterval;
1867 long token = mInjector.binderClearCallingIdentity();
1869 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1870 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1871 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1872 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1873 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1874 UserHandle.of(affectedUserHandle));
1876 if (alarmTime != 0) {
1877 am.set(AlarmManager.RTC, alarmTime, pi);
1880 mInjector.binderRestoreCallingIdentity(token);
1884 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1885 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1887 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1888 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1894 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
1896 enforceManagedProfile(userHandle, "call APIs on the parent profile");
1898 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1899 if (admin != null && parent) {
1900 admin = admin.getParentActiveAdmin();
1905 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1906 throws SecurityException {
1907 final int callingUid = mInjector.binderGetCallingUid();
1909 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1910 if (result != null) {
1915 final int userId = UserHandle.getUserId(callingUid);
1916 final DevicePolicyData policy = getUserData(userId);
1917 ActiveAdmin admin = policy.mAdminMap.get(who);
1918 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1919 throw new SecurityException("Admin " + admin.info.getComponent()
1920 + " does not own the device");
1922 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1923 throw new SecurityException("Admin " + admin.info.getComponent()
1924 + " does not own the profile");
1926 throw new SecurityException("Admin " + admin.info.getComponent()
1927 + " did not specify uses-policy for: "
1928 + admin.info.getTagForPolicy(reqPolicy));
1930 throw new SecurityException("No active admin owned by uid "
1931 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
1935 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
1936 throws SecurityException {
1938 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
1939 "call APIs on the parent profile");
1941 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
1942 return parent ? admin.getParentActiveAdmin() : admin;
1945 * Find the admin for the component and userId bit of the uid, then check
1946 * the admin's uid matches the uid.
1948 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
1949 final int userId = UserHandle.getUserId(uid);
1950 final DevicePolicyData policy = getUserData(userId);
1951 ActiveAdmin admin = policy.mAdminMap.get(who);
1952 if (admin == null) {
1953 throw new SecurityException("No active admin " + who);
1955 if (admin.getUid() != uid) {
1956 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1961 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
1963 // Try to find an admin which can use reqPolicy
1964 final int userId = UserHandle.getUserId(uid);
1965 final DevicePolicyData policy = getUserData(userId);
1967 ActiveAdmin admin = policy.mAdminMap.get(who);
1968 if (admin == null) {
1969 throw new SecurityException("No active admin " + who);
1971 if (admin.getUid() != uid) {
1972 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
1974 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
1978 for (ActiveAdmin admin : policy.mAdminList) {
1979 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
1990 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
1992 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
1993 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
1995 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1997 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1998 // DO always has the PO power.
1999 return ownsDevice || ownsProfile;
2001 return admin.info.usesPolicy(reqPolicy);
2005 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2006 sendAdminCommandLocked(admin, action, null);
2009 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2010 sendAdminCommandLocked(admin, action, null, result);
2014 * Send an update to one specific admin, get notified when that admin returns a result.
2016 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2017 BroadcastReceiver result) {
2018 Intent intent = new Intent(action);
2019 intent.setComponent(admin.info.getComponent());
2020 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2021 intent.putExtra("expiration", admin.passwordExpirationDate);
2023 if (adminExtras != null) {
2024 intent.putExtras(adminExtras);
2026 if (result != null) {
2027 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2028 null, result, mHandler, Activity.RESULT_OK, null, null);
2030 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2035 * Send an update to all admins of a user that enforce a specified policy.
2037 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2038 final DevicePolicyData policy = getUserData(userHandle);
2039 final int count = policy.mAdminList.size();
2041 for (int i = 0; i < count; i++) {
2042 final ActiveAdmin admin = policy.mAdminList.get(i);
2043 if (admin.info.usesPolicy(reqPolicy)) {
2044 sendAdminCommandLocked(admin, action);
2051 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2052 * enforce a specified policy.
2054 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2056 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2057 for (UserInfo ui : profiles) {
2059 sendAdminCommandLocked(action, reqPolicy, id);
2064 * Sends a broadcast to each profile that share the password unlock with the given user id.
2066 private void sendAdminCommandForLockscreenPoliciesLocked(
2067 String action, int reqPolicy, int userHandle) {
2068 if (isSeparateProfileChallengeEnabled(userHandle)) {
2069 sendAdminCommandLocked(action, reqPolicy, userHandle);
2071 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2075 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2076 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2077 if (admin != null) {
2078 getUserData(userHandle).mRemovingAdmins.add(adminReceiver);
2079 sendAdminCommandLocked(admin,
2080 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2081 new BroadcastReceiver() {
2083 public void onReceive(Context context, Intent intent) {
2084 removeAdminArtifacts(adminReceiver, userHandle);
2085 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2092 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2093 boolean throwForMissiongPermission) {
2097 enforceFullCrossUsersPermission(userHandle);
2098 ActivityInfo ai = null;
2100 ai = mIPackageManager.getReceiverInfo(adminName,
2101 PackageManager.GET_META_DATA |
2102 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2103 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2104 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2105 } catch (RemoteException e) {
2106 // shouldn't happen.
2109 throw new IllegalArgumentException("Unknown admin: " + adminName);
2112 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2113 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2114 + permission.BIND_DEVICE_ADMIN;
2115 Slog.w(LOG_TAG, message);
2116 if (throwForMissiongPermission &&
2117 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2118 throw new IllegalArgumentException(message);
2123 return new DeviceAdminInfo(mContext, ai);
2124 } catch (XmlPullParserException | IOException e) {
2125 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2131 private JournaledFile makeJournaledFile(int userHandle) {
2132 final String base = userHandle == UserHandle.USER_SYSTEM
2133 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2134 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2135 DEVICE_POLICIES_XML).getAbsolutePath();
2137 Log.v(LOG_TAG, "Opening " + base);
2139 return new JournaledFile(new File(base), new File(base + ".tmp"));
2142 private void saveSettingsLocked(int userHandle) {
2143 DevicePolicyData policy = getUserData(userHandle);
2144 JournaledFile journal = makeJournaledFile(userHandle);
2145 FileOutputStream stream = null;
2147 stream = new FileOutputStream(journal.chooseForWrite(), false);
2148 XmlSerializer out = new FastXmlSerializer();
2149 out.setOutput(stream, StandardCharsets.UTF_8.name());
2150 out.startDocument(null, true);
2152 out.startTag(null, "policies");
2153 if (policy.mRestrictionsProvider != null) {
2154 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2155 policy.mRestrictionsProvider.flattenToString());
2157 if (policy.mUserSetupComplete) {
2158 out.attribute(null, ATTR_SETUP_COMPLETE,
2159 Boolean.toString(true));
2161 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2162 out.attribute(null, ATTR_PROVISIONING_STATE,
2163 Integer.toString(policy.mUserProvisioningState));
2165 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2166 out.attribute(null, ATTR_PERMISSION_POLICY,
2167 Integer.toString(policy.mPermissionPolicy));
2169 if (policy.mDelegatedCertInstallerPackage != null) {
2170 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2171 policy.mDelegatedCertInstallerPackage);
2173 if (policy.mApplicationRestrictionsManagingPackage != null) {
2174 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2175 policy.mApplicationRestrictionsManagingPackage);
2178 final int N = policy.mAdminList.size();
2179 for (int i=0; i<N; i++) {
2180 ActiveAdmin ap = policy.mAdminList.get(i);
2182 out.startTag(null, "admin");
2183 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2185 out.endTag(null, "admin");
2189 if (policy.mPasswordOwner >= 0) {
2190 out.startTag(null, "password-owner");
2191 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2192 out.endTag(null, "password-owner");
2195 if (policy.mFailedPasswordAttempts != 0) {
2196 out.startTag(null, "failed-password-attempts");
2197 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2198 out.endTag(null, "failed-password-attempts");
2201 if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2202 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2203 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2204 || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
2205 out.startTag(null, "active-password");
2206 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2207 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2208 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2209 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2210 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2211 out.attribute(null, "numeric", Integer
2212 .toString(policy.mActivePasswordNumeric));
2213 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2214 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2215 out.endTag(null, "active-password");
2218 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2219 String component = policy.mLockTaskPackages.get(i);
2220 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2221 out.attribute(null, "name", component);
2222 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2225 if (policy.mStatusBarDisabled) {
2226 out.startTag(null, TAG_STATUS_BAR);
2227 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2228 out.endTag(null, TAG_STATUS_BAR);
2231 if (policy.doNotAskCredentialsOnBoot) {
2232 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2233 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2236 for (String id : policy.mAffiliationIds) {
2237 out.startTag(null, TAG_AFFILIATION_ID);
2238 out.attribute(null, "id", id);
2239 out.endTag(null, TAG_AFFILIATION_ID);
2242 if (policy.mAdminBroadcastPending) {
2243 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2244 out.attribute(null, ATTR_VALUE,
2245 Boolean.toString(policy.mAdminBroadcastPending));
2246 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2249 if (policy.mInitBundle != null) {
2250 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2251 policy.mInitBundle.saveToXml(out);
2252 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2255 out.endTag(null, "policies");
2259 FileUtils.sync(stream);
2262 sendChangedNotification(userHandle);
2263 } catch (XmlPullParserException | IOException e) {
2264 Slog.w(LOG_TAG, "failed writing file", e);
2266 if (stream != null) {
2269 } catch (IOException ex) {
2276 private void sendChangedNotification(int userHandle) {
2277 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2278 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2279 long ident = mInjector.binderClearCallingIdentity();
2281 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2283 mInjector.binderRestoreCallingIdentity(ident);
2287 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2288 JournaledFile journal = makeJournaledFile(userHandle);
2289 FileInputStream stream = null;
2290 File file = journal.chooseForRead();
2292 stream = new FileInputStream(file);
2293 XmlPullParser parser = Xml.newPullParser();
2294 parser.setInput(stream, StandardCharsets.UTF_8.name());
2297 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2298 && type != XmlPullParser.START_TAG) {
2300 String tag = parser.getName();
2301 if (!"policies".equals(tag)) {
2302 throw new XmlPullParserException(
2303 "Settings do not start with policies tag: found " + tag);
2306 // Extract the permission provider component name if available
2307 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2308 if (permissionProvider != null) {
2309 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2311 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2312 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2313 policy.mUserSetupComplete = true;
2315 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2316 if (!TextUtils.isEmpty(provisioningState)) {
2317 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2319 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2320 if (!TextUtils.isEmpty(permissionPolicy)) {
2321 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2323 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2324 ATTR_DELEGATED_CERT_INSTALLER);
2325 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2326 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2328 type = parser.next();
2329 int outerDepth = parser.getDepth();
2330 policy.mLockTaskPackages.clear();
2331 policy.mAdminList.clear();
2332 policy.mAdminMap.clear();
2333 policy.mAffiliationIds.clear();
2334 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2335 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2336 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2339 tag = parser.getName();
2340 if ("admin".equals(tag)) {
2341 String name = parser.getAttributeValue(null, "name");
2343 DeviceAdminInfo dai = findAdmin(
2344 ComponentName.unflattenFromString(name), userHandle,
2345 /* throwForMissionPermission= */ false);
2347 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2349 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2350 + dai.getActivityInfo().applicationInfo.uid + " for user "
2354 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2355 ap.readFromXml(parser);
2356 policy.mAdminMap.put(ap.info.getComponent(), ap);
2358 } catch (RuntimeException e) {
2359 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2361 } else if ("failed-password-attempts".equals(tag)) {
2362 policy.mFailedPasswordAttempts = Integer.parseInt(
2363 parser.getAttributeValue(null, "value"));
2364 } else if ("password-owner".equals(tag)) {
2365 policy.mPasswordOwner = Integer.parseInt(
2366 parser.getAttributeValue(null, "value"));
2367 } else if ("active-password".equals(tag)) {
2368 policy.mActivePasswordQuality = Integer.parseInt(
2369 parser.getAttributeValue(null, "quality"));
2370 policy.mActivePasswordLength = Integer.parseInt(
2371 parser.getAttributeValue(null, "length"));
2372 policy.mActivePasswordUpperCase = Integer.parseInt(
2373 parser.getAttributeValue(null, "uppercase"));
2374 policy.mActivePasswordLowerCase = Integer.parseInt(
2375 parser.getAttributeValue(null, "lowercase"));
2376 policy.mActivePasswordLetters = Integer.parseInt(
2377 parser.getAttributeValue(null, "letters"));
2378 policy.mActivePasswordNumeric = Integer.parseInt(
2379 parser.getAttributeValue(null, "numeric"));
2380 policy.mActivePasswordSymbols = Integer.parseInt(
2381 parser.getAttributeValue(null, "symbols"));
2382 policy.mActivePasswordNonLetter = Integer.parseInt(
2383 parser.getAttributeValue(null, "nonletter"));
2384 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2385 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2386 } else if (TAG_STATUS_BAR.equals(tag)) {
2387 policy.mStatusBarDisabled = Boolean.parseBoolean(
2388 parser.getAttributeValue(null, ATTR_DISABLED));
2389 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2390 policy.doNotAskCredentialsOnBoot = true;
2391 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2392 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2393 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2394 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2395 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2396 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2397 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2399 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2400 XmlUtils.skipCurrentTag(parser);
2403 } catch (FileNotFoundException e) {
2404 // Don't be noisy, this is normal if we haven't defined any policies.
2405 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2406 | IndexOutOfBoundsException e) {
2407 Slog.w(LOG_TAG, "failed parsing " + file, e);
2410 if (stream != null) {
2413 } catch (IOException e) {
2417 // Generate a list of admins from the admin map
2418 policy.mAdminList.addAll(policy.mAdminMap.values());
2420 // Validate that what we stored for the password quality matches
2421 // sufficiently what is currently set. Note that this is only
2422 // a sanity check in case the two get out of sync; this should
2423 // never normally happen.
2424 final long identity = mInjector.binderClearCallingIdentity();
2426 int actualPasswordQuality = mLockPatternUtils.getActivePasswordQuality(userHandle);
2427 if (actualPasswordQuality < policy.mActivePasswordQuality) {
2428 Slog.w(LOG_TAG, "Active password quality 0x"
2429 + Integer.toHexString(policy.mActivePasswordQuality)
2430 + " does not match actual quality 0x"
2431 + Integer.toHexString(actualPasswordQuality));
2432 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2433 policy.mActivePasswordLength = 0;
2434 policy.mActivePasswordUpperCase = 0;
2435 policy.mActivePasswordLowerCase = 0;
2436 policy.mActivePasswordLetters = 0;
2437 policy.mActivePasswordNumeric = 0;
2438 policy.mActivePasswordSymbols = 0;
2439 policy.mActivePasswordNonLetter = 0;
2442 mInjector.binderRestoreCallingIdentity(identity);
2445 validatePasswordOwnerLocked(policy);
2446 updateMaximumTimeToLockLocked(userHandle);
2447 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2448 if (policy.mStatusBarDisabled) {
2449 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2453 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2454 long ident = mInjector.binderClearCallingIdentity();
2456 mInjector.getIActivityManager()
2457 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2458 } catch (RemoteException e) {
2459 // Not gonna happen.
2461 mInjector.binderRestoreCallingIdentity(ident);
2465 private void updateDeviceOwnerLocked() {
2466 long ident = mInjector.binderClearCallingIdentity();
2468 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2469 // user id and also protect all other DAs too.
2470 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2471 if (deviceOwnerComponent != null) {
2472 mInjector.getIActivityManager()
2473 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2475 } catch (RemoteException e) {
2476 // Not gonna happen.
2478 mInjector.binderRestoreCallingIdentity(ident);
2482 static void validateQualityConstant(int quality) {
2484 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2485 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2486 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2487 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2488 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2489 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2490 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2491 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2492 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2495 throw new IllegalArgumentException("Invalid quality constant: 0x"
2496 + Integer.toHexString(quality));
2499 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2500 if (policy.mPasswordOwner >= 0) {
2501 boolean haveOwner = false;
2502 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2503 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2509 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2510 + " no longer active; disabling");
2511 policy.mPasswordOwner = -1;
2517 void systemReady(int phase) {
2522 case SystemService.PHASE_LOCK_SETTINGS_READY:
2523 onLockSettingsReady();
2525 case SystemService.PHASE_BOOT_COMPLETED:
2526 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2531 private void onLockSettingsReady() {
2532 getUserData(UserHandle.USER_SYSTEM);
2536 onStartUser(UserHandle.USER_SYSTEM);
2538 // Register an observer for watching for user setup complete.
2539 new SetupContentObserver(mHandler).register(mContext.getContentResolver());
2540 // Initialize the user setup state, to handle the upgrade case.
2541 updateUserSetupComplete();
2543 List<String> packageList;
2544 synchronized (this) {
2545 packageList = getKeepUninstalledPackagesLocked();
2547 if (packageList != null) {
2548 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2551 synchronized (this) {
2552 // push the force-ephemeral-users policy to the user manager.
2553 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2554 if (deviceOwner != null) {
2555 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2560 private void ensureDeviceOwnerUserStarted() {
2562 synchronized (this) {
2563 if (!mOwners.hasDeviceOwner()) {
2566 userId = mOwners.getDeviceOwnerUserId();
2569 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2571 if (userId != UserHandle.USER_SYSTEM) {
2573 mInjector.getIActivityManager().startUserInBackground(userId);
2575 // STOPSHIP Prevent the DO user from being killed.
2577 } catch (RemoteException e) {
2578 Slog.w(LOG_TAG, "Exception starting user", e);
2583 private void onStartUser(int userId) {
2584 updateScreenCaptureDisabledInWindowManager(userId,
2585 getScreenCaptureDisabled(null, userId));
2586 pushUserRestrictions(userId);
2589 private void cleanUpOldUsers() {
2590 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2592 Set<Integer> usersWithProfileOwners;
2593 Set<Integer> usersWithData;
2594 synchronized(this) {
2595 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2596 usersWithData = new ArraySet<>();
2597 for (int i = 0; i < mUserData.size(); i++) {
2598 usersWithData.add(mUserData.keyAt(i));
2601 List<UserInfo> allUsers = mUserManager.getUsers();
2603 Set<Integer> deletedUsers = new ArraySet<>();
2604 deletedUsers.addAll(usersWithProfileOwners);
2605 deletedUsers.addAll(usersWithData);
2606 for (UserInfo userInfo : allUsers) {
2607 deletedUsers.remove(userInfo.id);
2609 for (Integer userId : deletedUsers) {
2610 removeUserData(userId);
2614 private void handlePasswordExpirationNotification(int userHandle) {
2615 synchronized (this) {
2616 final long now = System.currentTimeMillis();
2618 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2619 userHandle, /* parent */ false);
2620 final int N = admins.size();
2621 for (int i = 0; i < N; i++) {
2622 ActiveAdmin admin = admins.get(i);
2623 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2624 && admin.passwordExpirationTimeout > 0L
2625 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2626 && admin.passwordExpirationDate > 0L) {
2627 sendAdminCommandLocked(admin,
2628 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2631 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2635 private class MonitoringCertNotificationTask extends AsyncTask<Intent, Void, Void> {
2637 protected Void doInBackground(Intent... params) {
2638 int userHandle = params[0].getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
2640 if (userHandle == UserHandle.USER_ALL) {
2641 for (UserInfo userInfo : mUserManager.getUsers()) {
2642 manageNotification(userInfo.getUserHandle());
2645 manageNotification(new UserHandle(userHandle));
2650 private void manageNotification(UserHandle userHandle) {
2651 if (!mUserManager.isUserRunning(userHandle)) {
2655 // Call out to KeyChain to check for user-added CAs
2656 boolean hasCert = false;
2658 KeyChainConnection kcs = KeyChain.bindAsUser(mContext, userHandle);
2660 if (!kcs.getService().getUserCaAliases().getList().isEmpty()) {
2663 } catch (RemoteException e) {
2664 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
2668 } catch (InterruptedException e) {
2669 Thread.currentThread().interrupt();
2670 } catch (RuntimeException | AssertionError e) {
2671 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
2674 mInjector.getNotificationManager().cancelAsUser(
2675 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2679 // Build and show a warning notification
2682 // TODO Why does it use the DO name? The cert APIs are all for PO. b/25772443
2683 final String ownerName = getDeviceOwnerName();
2684 if (isManagedProfile(userHandle.getIdentifier())) {
2685 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_administrator);
2686 smallIconId = R.drawable.stat_sys_certificate_info;
2687 } else if (ownerName != null) {
2688 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, ownerName);
2689 smallIconId = R.drawable.stat_sys_certificate_info;
2691 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2692 smallIconId = android.R.drawable.stat_sys_warning;
2695 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2696 dialogIntent.setFlags(
2697 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2698 dialogIntent.setPackage("com.android.settings");
2699 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2700 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, userHandle);
2702 final Context userContext;
2704 userContext = mContext.createPackageContextAsUser("android", 0, userHandle);
2705 } catch (PackageManager.NameNotFoundException e) {
2706 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2709 final Notification noti = new Notification.Builder(userContext)
2710 .setSmallIcon(smallIconId)
2711 .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning))
2712 .setContentText(contentText)
2713 .setContentIntent(notifyIntent)
2714 .setPriority(Notification.PRIORITY_HIGH)
2716 .setColor(mContext.getColor(
2717 com.android.internal.R.color.system_notification_accent_color))
2720 mInjector.getNotificationManager().notifyAsUser(
2721 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2726 * @param adminReceiver The admin to add
2727 * @param refreshing true = update an active admin, no error
2730 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2734 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2737 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2738 Bundle onEnableData) {
2739 mContext.enforceCallingOrSelfPermission(
2740 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2741 enforceFullCrossUsersPermission(userHandle);
2743 DevicePolicyData policy = getUserData(userHandle);
2744 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2745 /* throwForMissionPermission= */ true);
2747 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2749 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2750 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2753 synchronized (this) {
2754 long ident = mInjector.binderClearCallingIdentity();
2757 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
2758 throw new IllegalArgumentException("Admin is already added");
2760 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2761 policy.mAdminMap.put(adminReceiver, newAdmin);
2762 int replaceIndex = -1;
2763 final int N = policy.mAdminList.size();
2764 for (int i=0; i < N; i++) {
2765 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2766 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2771 if (replaceIndex == -1) {
2772 policy.mAdminList.add(newAdmin);
2773 enableIfNecessary(info.getPackageName(), userHandle);
2775 policy.mAdminList.set(replaceIndex, newAdmin);
2777 saveSettingsLocked(userHandle);
2778 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2779 onEnableData, null);
2781 mInjector.binderRestoreCallingIdentity(ident);
2787 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2791 enforceFullCrossUsersPermission(userHandle);
2792 synchronized (this) {
2793 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2798 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2802 enforceFullCrossUsersPermission(userHandle);
2803 synchronized (this) {
2804 DevicePolicyData policyData = getUserData(userHandle);
2805 return policyData.mRemovingAdmins.contains(adminReceiver);
2810 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2814 enforceFullCrossUsersPermission(userHandle);
2815 synchronized (this) {
2816 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2817 if (administrator == null) {
2818 throw new SecurityException("No active admin " + adminReceiver);
2820 return administrator.info.usesPolicy(policyId);
2825 @SuppressWarnings("unchecked")
2826 public List<ComponentName> getActiveAdmins(int userHandle) {
2828 return Collections.EMPTY_LIST;
2831 enforceFullCrossUsersPermission(userHandle);
2832 synchronized (this) {
2833 DevicePolicyData policy = getUserData(userHandle);
2834 final int N = policy.mAdminList.size();
2838 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2839 for (int i=0; i<N; i++) {
2840 res.add(policy.mAdminList.get(i).info.getComponent());
2847 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2851 enforceFullCrossUsersPermission(userHandle);
2852 synchronized (this) {
2853 DevicePolicyData policy = getUserData(userHandle);
2854 final int N = policy.mAdminList.size();
2855 for (int i=0; i<N; i++) {
2856 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2865 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
2869 enforceFullCrossUsersPermission(userHandle);
2870 enforceUserUnlocked(userHandle);
2871 synchronized (this) {
2872 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2873 if (admin == null) {
2876 // Active device/profile owners must remain active admins.
2877 if (isDeviceOwner(adminReceiver, userHandle)
2878 || isProfileOwner(adminReceiver, userHandle)) {
2879 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
2883 if (admin.getUid() != mInjector.binderGetCallingUid()) {
2884 mContext.enforceCallingOrSelfPermission(
2885 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2887 long ident = mInjector.binderClearCallingIdentity();
2889 removeActiveAdminLocked(adminReceiver, userHandle);
2891 mInjector.binderRestoreCallingIdentity(ident);
2897 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
2898 ComponentName profileOwner = getProfileOwner(userHandle);
2899 // Profile challenge is supported on N or newer release.
2900 return profileOwner != null &&
2901 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
2905 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
2909 Preconditions.checkNotNull(who, "ComponentName is null");
2910 validateQualityConstant(quality);
2912 synchronized (this) {
2913 ActiveAdmin ap = getActiveAdminForCallerLocked(
2914 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
2915 if (ap.passwordQuality != quality) {
2916 ap.passwordQuality = quality;
2917 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
2923 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
2925 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2927 enforceFullCrossUsersPermission(userHandle);
2928 synchronized (this) {
2929 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2932 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
2933 return admin != null ? admin.passwordQuality : mode;
2936 // Return the strictest policy across all participating admins.
2937 List<ActiveAdmin> admins =
2938 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
2939 final int N = admins.size();
2940 for (int i = 0; i < N; i++) {
2941 ActiveAdmin admin = admins.get(i);
2942 if (mode < admin.passwordQuality) {
2943 mode = admin.passwordQuality;
2950 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
2951 int userHandle, boolean parent) {
2952 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
2953 // If this user has a separate challenge, only return its restrictions.
2954 return getUserDataUnchecked(userHandle).mAdminList;
2956 // Return all admins for this user and the profiles that are visible from this
2957 // user that do not use a separate work challenge.
2958 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
2959 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
2960 DevicePolicyData policy = getUserData(userInfo.id);
2961 if (!isManagedProfile(userInfo.id)) {
2962 admins.addAll(policy.mAdminList);
2964 // For managed profiles, we always include the policies set on the parent
2965 // profile. Additionally, we include the ones set on the managed profile
2966 // if no separate challenge is in place.
2967 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
2968 final int N = policy.mAdminList.size();
2969 for (int i = 0; i < N; i++) {
2970 ActiveAdmin admin = policy.mAdminList.get(i);
2971 if (admin.hasParentActiveAdmin()) {
2972 admins.add(admin.getParentActiveAdmin());
2974 if (!hasSeparateChallenge) {
2984 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
2985 long ident = mInjector.binderClearCallingIdentity();
2987 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
2989 mInjector.binderRestoreCallingIdentity(ident);
2994 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
2998 Preconditions.checkNotNull(who, "ComponentName is null");
2999 synchronized (this) {
3000 ActiveAdmin ap = getActiveAdminForCallerLocked(
3001 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3002 if (ap.minimumPasswordLength != length) {
3003 ap.minimumPasswordLength = length;
3004 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3010 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3014 enforceFullCrossUsersPermission(userHandle);
3015 synchronized (this) {
3019 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3020 return admin != null ? admin.minimumPasswordLength : length;
3023 // Return the strictest policy across all participating admins.
3024 List<ActiveAdmin> admins =
3025 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3026 final int N = admins.size();
3027 for (int i = 0; i < N; i++) {
3028 ActiveAdmin admin = admins.get(i);
3029 if (length < admin.minimumPasswordLength) {
3030 length = admin.minimumPasswordLength;
3038 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3042 Preconditions.checkNotNull(who, "ComponentName is null");
3043 synchronized (this) {
3044 ActiveAdmin ap = getActiveAdminForCallerLocked(
3045 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3046 if (ap.passwordHistoryLength != length) {
3047 ap.passwordHistoryLength = length;
3048 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3054 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3058 enforceFullCrossUsersPermission(userHandle);
3059 synchronized (this) {
3063 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3064 return admin != null ? admin.passwordHistoryLength : length;
3067 // Return the strictest policy across all participating admins.
3068 List<ActiveAdmin> admins =
3069 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3070 final int N = admins.size();
3071 for (int i = 0; i < N; i++) {
3072 ActiveAdmin admin = admins.get(i);
3073 if (length < admin.passwordHistoryLength) {
3074 length = admin.passwordHistoryLength;
3083 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3087 Preconditions.checkNotNull(who, "ComponentName is null");
3088 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3089 final int userHandle = mInjector.userHandleGetCallingUserId();
3090 synchronized (this) {
3091 ActiveAdmin ap = getActiveAdminForCallerLocked(
3092 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3093 // Calling this API automatically bumps the expiration date
3094 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3095 ap.passwordExpirationDate = expiration;
3096 ap.passwordExpirationTimeout = timeout;
3098 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3099 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3100 .format(new Date(expiration)));
3102 saveSettingsLocked(userHandle);
3104 // in case this is the first one, set the alarm on the appropriate user.
3105 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3110 * Return a single admin's expiration cycle time, or the min of all cycle times.
3111 * Returns 0 if not configured.
3114 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3118 enforceFullCrossUsersPermission(userHandle);
3119 synchronized (this) {
3123 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3124 return admin != null ? admin.passwordExpirationTimeout : timeout;
3127 // Return the strictest policy across all participating admins.
3128 List<ActiveAdmin> admins =
3129 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3130 final int N = admins.size();
3131 for (int i = 0; i < N; i++) {
3132 ActiveAdmin admin = admins.get(i);
3133 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3134 && timeout > admin.passwordExpirationTimeout)) {
3135 timeout = admin.passwordExpirationTimeout;
3143 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3144 final int userId = UserHandle.getCallingUserId();
3145 List<String> changedProviders = null;
3147 synchronized (this) {
3148 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3149 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3150 if (activeAdmin.crossProfileWidgetProviders == null) {
3151 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3153 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3154 if (!providers.contains(packageName)) {
3155 providers.add(packageName);
3156 changedProviders = new ArrayList<>(providers);
3157 saveSettingsLocked(userId);
3161 if (changedProviders != null) {
3162 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3170 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3171 final int userId = UserHandle.getCallingUserId();
3172 List<String> changedProviders = null;
3174 synchronized (this) {
3175 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3176 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3177 if (activeAdmin.crossProfileWidgetProviders == null) {
3180 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3181 if (providers.remove(packageName)) {
3182 changedProviders = new ArrayList<>(providers);
3183 saveSettingsLocked(userId);
3187 if (changedProviders != null) {
3188 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3196 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3197 synchronized (this) {
3198 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3199 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3200 if (activeAdmin.crossProfileWidgetProviders == null
3201 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3204 if (mInjector.binderIsCallingUidMyUid()) {
3205 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3207 return activeAdmin.crossProfileWidgetProviders;
3213 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3214 * Returns 0 if not configured.
3216 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3220 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3221 return admin != null ? admin.passwordExpirationDate : timeout;
3224 // Return the strictest policy across all participating admins.
3225 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3226 final int N = admins.size();
3227 for (int i = 0; i < N; i++) {
3228 ActiveAdmin admin = admins.get(i);
3229 if (timeout == 0L || (admin.passwordExpirationDate != 0
3230 && timeout > admin.passwordExpirationDate)) {
3231 timeout = admin.passwordExpirationDate;
3238 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3242 enforceFullCrossUsersPermission(userHandle);
3243 synchronized (this) {
3244 return getPasswordExpirationLocked(who, userHandle, parent);
3249 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3253 Preconditions.checkNotNull(who, "ComponentName is null");
3254 synchronized (this) {
3255 ActiveAdmin ap = getActiveAdminForCallerLocked(
3256 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3257 if (ap.minimumPasswordUpperCase != length) {
3258 ap.minimumPasswordUpperCase = length;
3259 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3265 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3269 enforceFullCrossUsersPermission(userHandle);
3270 synchronized (this) {
3274 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3275 return admin != null ? admin.minimumPasswordUpperCase : length;
3278 // Return the strictest policy across all participating admins.
3279 List<ActiveAdmin> admins =
3280 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3281 final int N = admins.size();
3282 for (int i = 0; i < N; i++) {
3283 ActiveAdmin admin = admins.get(i);
3284 if (length < admin.minimumPasswordUpperCase) {
3285 length = admin.minimumPasswordUpperCase;
3293 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3294 Preconditions.checkNotNull(who, "ComponentName is null");
3295 synchronized (this) {
3296 ActiveAdmin ap = getActiveAdminForCallerLocked(
3297 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3298 if (ap.minimumPasswordLowerCase != length) {
3299 ap.minimumPasswordLowerCase = length;
3300 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3306 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3310 enforceFullCrossUsersPermission(userHandle);
3311 synchronized (this) {
3315 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3316 return admin != null ? admin.minimumPasswordLowerCase : length;
3319 // Return the strictest policy across all participating admins.
3320 List<ActiveAdmin> admins =
3321 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3322 final int N = admins.size();
3323 for (int i = 0; i < N; i++) {
3324 ActiveAdmin admin = admins.get(i);
3325 if (length < admin.minimumPasswordLowerCase) {
3326 length = admin.minimumPasswordLowerCase;
3334 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3338 Preconditions.checkNotNull(who, "ComponentName is null");
3339 synchronized (this) {
3340 ActiveAdmin ap = getActiveAdminForCallerLocked(
3341 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3342 if (ap.minimumPasswordLetters != length) {
3343 ap.minimumPasswordLetters = length;
3344 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3350 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3354 enforceFullCrossUsersPermission(userHandle);
3355 synchronized (this) {
3359 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3360 return admin != null ? admin.minimumPasswordLetters : length;
3363 // Return the strictest policy across all participating admins.
3364 List<ActiveAdmin> admins =
3365 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3366 final int N = admins.size();
3367 for (int i = 0; i < N; i++) {
3368 ActiveAdmin admin = admins.get(i);
3369 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3372 if (length < admin.minimumPasswordLetters) {
3373 length = admin.minimumPasswordLetters;
3381 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3385 Preconditions.checkNotNull(who, "ComponentName is null");
3386 synchronized (this) {
3387 ActiveAdmin ap = getActiveAdminForCallerLocked(
3388 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3389 if (ap.minimumPasswordNumeric != length) {
3390 ap.minimumPasswordNumeric = length;
3391 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3397 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3401 enforceFullCrossUsersPermission(userHandle);
3402 synchronized (this) {
3406 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3407 return admin != null ? admin.minimumPasswordNumeric : length;
3410 // Return the strictest policy across all participating admins.
3411 List<ActiveAdmin> admins =
3412 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3413 final int N = admins.size();
3414 for (int i = 0; i < N; i++) {
3415 ActiveAdmin admin = admins.get(i);
3416 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3419 if (length < admin.minimumPasswordNumeric) {
3420 length = admin.minimumPasswordNumeric;
3428 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3432 Preconditions.checkNotNull(who, "ComponentName is null");
3433 synchronized (this) {
3434 ActiveAdmin ap = getActiveAdminForCallerLocked(
3435 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3436 if (ap.minimumPasswordSymbols != length) {
3437 ap.minimumPasswordSymbols = length;
3438 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3444 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3448 enforceFullCrossUsersPermission(userHandle);
3449 synchronized (this) {
3453 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3454 return admin != null ? admin.minimumPasswordSymbols : length;
3457 // Return the strictest policy across all participating admins.
3458 List<ActiveAdmin> admins =
3459 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3460 final int N = admins.size();
3461 for (int i = 0; i < N; i++) {
3462 ActiveAdmin admin = admins.get(i);
3463 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3466 if (length < admin.minimumPasswordSymbols) {
3467 length = admin.minimumPasswordSymbols;
3475 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3479 Preconditions.checkNotNull(who, "ComponentName is null");
3480 synchronized (this) {
3481 ActiveAdmin ap = getActiveAdminForCallerLocked(
3482 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3483 if (ap.minimumPasswordNonLetter != length) {
3484 ap.minimumPasswordNonLetter = length;
3485 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3491 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3495 enforceFullCrossUsersPermission(userHandle);
3496 synchronized (this) {
3500 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3501 return admin != null ? admin.minimumPasswordNonLetter : length;
3504 // Return the strictest policy across all participating admins.
3505 List<ActiveAdmin> admins =
3506 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3507 final int N = admins.size();
3508 for (int i = 0; i < N; i++) {
3509 ActiveAdmin admin = admins.get(i);
3510 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3513 if (length < admin.minimumPasswordNonLetter) {
3514 length = admin.minimumPasswordNonLetter;
3522 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3526 enforceFullCrossUsersPermission(userHandle);
3528 synchronized (this) {
3529 // This API can only be called by an active device admin,
3530 // so try to retrieve it to check that the caller is one.
3531 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3532 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3533 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3538 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3542 enforceFullCrossUsersPermission(userHandle);
3543 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3545 synchronized (this) {
3546 int targetUser = getProfileParentId(userHandle);
3547 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3548 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3552 private boolean isActivePasswordSufficientForUserLocked(
3553 DevicePolicyData policy, int userHandle, boolean parent) {
3554 if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle, parent)
3555 || policy.mActivePasswordLength < getPasswordMinimumLength(
3556 null, userHandle, parent)) {
3559 if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3562 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3563 null, userHandle, parent)
3564 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3565 null, userHandle, parent)
3566 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3567 null, userHandle, parent)
3568 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3569 null, userHandle, parent)
3570 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3571 null, userHandle, parent)
3572 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3573 null, userHandle, parent);
3577 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3578 enforceFullCrossUsersPermission(userHandle);
3579 synchronized (this) {
3580 if (!isCallerWithSystemUid()) {
3581 // This API can only be called by an active device admin,
3582 // so try to retrieve it to check that the caller is one.
3583 getActiveAdminForCallerLocked(
3584 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3587 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3589 return policy.mFailedPasswordAttempts;
3594 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3598 Preconditions.checkNotNull(who, "ComponentName is null");
3599 synchronized (this) {
3600 // This API can only be called by an active device admin,
3601 // so try to retrieve it to check that the caller is one.
3602 getActiveAdminForCallerLocked(
3603 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3604 ActiveAdmin ap = getActiveAdminForCallerLocked(
3605 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3606 if (ap.maximumFailedPasswordsForWipe != num) {
3607 ap.maximumFailedPasswordsForWipe = num;
3608 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3614 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3618 enforceFullCrossUsersPermission(userHandle);
3619 synchronized (this) {
3620 ActiveAdmin admin = (who != null)
3621 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3622 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3623 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3628 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3630 return UserHandle.USER_NULL;
3632 enforceFullCrossUsersPermission(userHandle);
3633 synchronized (this) {
3634 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3635 userHandle, parent);
3636 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3641 * Returns the admin with the strictest policy on maximum failed passwords for:
3643 * <li>this user if it has a separate profile challenge, or
3644 * <li>this user and all profiles that don't have their own challenge otherwise.
3646 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3647 * the primary profile.
3648 * Returns {@code null} if no participating admin has that policy set.
3650 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3651 int userHandle, boolean parent) {
3653 ActiveAdmin strictestAdmin = null;
3655 // Return the strictest policy across all participating admins.
3656 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3657 final int N = admins.size();
3658 for (int i = 0; i < N; i++) {
3659 ActiveAdmin admin = admins.get(i);
3660 if (admin.maximumFailedPasswordsForWipe ==
3661 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3662 continue; // No max number of failed passwords policy set for this profile.
3665 // We always favor the primary profile if several profiles have the same value set.
3666 int userId = admin.getUserHandle().getIdentifier();
3668 count > admin.maximumFailedPasswordsForWipe ||
3669 (count == admin.maximumFailedPasswordsForWipe &&
3670 getUserInfo(userId).isPrimary())) {
3671 count = admin.maximumFailedPasswordsForWipe;
3672 strictestAdmin = admin;
3675 return strictestAdmin;
3678 private UserInfo getUserInfo(@UserIdInt int userId) {
3679 final long token = mInjector.binderClearCallingIdentity();
3681 return mUserManager.getUserInfo(userId);
3683 mInjector.binderRestoreCallingIdentity(token);
3688 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3692 final int callingUid = mInjector.binderGetCallingUid();
3693 final int userHandle = mInjector.userHandleGetCallingUserId();
3695 if (getCredentialOwner(userHandle, /* parent */ false) != userHandle) {
3696 throw new SecurityException("You can not change password for this profile because"
3697 + " it shares the password with the owner profile");
3700 String password = passwordOrNull != null ? passwordOrNull : "";
3703 synchronized (this) {
3704 // If caller has PO (or DO), it can clear the password, so see if that's the case
3706 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3707 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3708 if (admin == null) {
3709 // Otherwise, make sure the caller has any active admin with the right policy.
3710 admin = getActiveAdminForCallerLocked(null,
3711 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3714 final ComponentName adminComponent = admin.info.getComponent();
3716 // As of N, only profile owners and device owners can reset the password.
3717 if (!(isProfileOwner(adminComponent, userHandle)
3718 || isDeviceOwner(adminComponent, userHandle))) {
3719 final boolean preN = getTargetSdk(admin.info.getPackageName(), userHandle)
3720 <= android.os.Build.VERSION_CODES.M;
3721 // As of N, password resetting to empty/null is not allowed anymore.
3722 // TODO Should we allow DO/PO to set an empty password?
3723 if (TextUtils.isEmpty(password)) {
3725 throw new SecurityException("Cannot call with null password");
3727 Slog.e(LOG_TAG, "Cannot call with null password");
3731 // As of N, password cannot be changed by the admin if it is already set.
3732 if (isLockScreenSecureUnchecked(userHandle)) {
3734 throw new SecurityException("Admin cannot change current password");
3736 Slog.e(LOG_TAG, "Admin cannot change current password");
3741 quality = getPasswordQuality(null, userHandle, /* parent */ false);
3742 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
3743 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3745 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
3746 int realQuality = LockPatternUtils.computePasswordQuality(password);
3747 if (realQuality < quality
3748 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3749 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
3750 + Integer.toHexString(realQuality)
3751 + " does not meet required quality 0x"
3752 + Integer.toHexString(quality));
3755 quality = Math.max(realQuality, quality);
3757 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
3758 if (password.length() < length) {
3759 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
3760 + " does not meet required length " + length);
3763 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3770 for (int i = 0; i < password.length(); i++) {
3771 char c = password.charAt(i);
3772 if (c >= 'A' && c <= 'Z') {
3775 } else if (c >= 'a' && c <= 'z') {
3778 } else if (c >= '0' && c <= '9') {
3786 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
3787 if(letters < neededLetters) {
3788 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
3789 + " does not meet required number of letters " + neededLetters);
3792 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
3793 if (numbers < neededNumbers) {
3794 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
3795 + " does not meet required number of numerical digits "
3799 int neededLowerCase = getPasswordMinimumLowerCase(
3800 null, userHandle, /* parent */ false);
3801 if (lowercase < neededLowerCase) {
3802 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
3803 + " does not meet required number of lowercase letters "
3807 int neededUpperCase = getPasswordMinimumUpperCase(
3808 null, userHandle, /* parent */ false);
3809 if (uppercase < neededUpperCase) {
3810 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
3811 + " does not meet required number of uppercase letters "
3815 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
3816 if (symbols < neededSymbols) {
3817 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
3818 + " does not meet required number of special symbols " + neededSymbols);
3821 int neededNonLetter = getPasswordMinimumNonLetter(
3822 null, userHandle, /* parent */ false);
3823 if (nonletter < neededNonLetter) {
3824 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
3825 + " does not meet required number of non-letter characters "
3832 DevicePolicyData policy = getUserData(userHandle);
3833 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
3834 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
3838 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
3839 boolean doNotAskCredentialsOnBoot =
3840 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
3841 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
3842 setDoNotAskCredentialsOnBoot();
3845 // Don't do this with the lock held, because it is going to call
3846 // back in to the service.
3847 final long ident = mInjector.binderClearCallingIdentity();
3849 if (!TextUtils.isEmpty(password)) {
3850 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
3852 mLockPatternUtils.clearLock(userHandle);
3854 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
3856 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
3857 UserHandle.USER_ALL);
3859 synchronized (this) {
3860 int newOwner = requireEntry ? callingUid : -1;
3861 if (policy.mPasswordOwner != newOwner) {
3862 policy.mPasswordOwner = newOwner;
3863 saveSettingsLocked(userHandle);
3867 mInjector.binderRestoreCallingIdentity(ident);
3873 private boolean isLockScreenSecureUnchecked(int userId) {
3874 long ident = mInjector.binderClearCallingIdentity();
3876 return mLockPatternUtils.isSecure(userId);
3878 mInjector.binderRestoreCallingIdentity(ident);
3882 private void setDoNotAskCredentialsOnBoot() {
3883 synchronized (this) {
3884 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
3885 if (!policyData.doNotAskCredentialsOnBoot) {
3886 policyData.doNotAskCredentialsOnBoot = true;
3887 saveSettingsLocked(UserHandle.USER_SYSTEM);
3893 public boolean getDoNotAskCredentialsOnBoot() {
3894 mContext.enforceCallingOrSelfPermission(
3895 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
3896 synchronized (this) {
3897 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
3898 return policyData.doNotAskCredentialsOnBoot;
3903 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
3907 Preconditions.checkNotNull(who, "ComponentName is null");
3908 final int userHandle = mInjector.userHandleGetCallingUserId();
3909 synchronized (this) {
3910 ActiveAdmin ap = getActiveAdminForCallerLocked(
3911 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
3912 if (ap.maximumTimeToUnlock != timeMs) {
3913 ap.maximumTimeToUnlock = timeMs;
3914 saveSettingsLocked(userHandle);
3915 updateMaximumTimeToLockLocked(userHandle);
3920 void updateMaximumTimeToLockLocked(int userHandle) {
3921 // Calculate the min timeout for all profiles - including the ones with a separate
3922 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
3923 // challenge only and keep the screen on. However there is no easy way of doing that at the
3924 // moment so we set the screen off timeout regardless of whether it affects the parent user
3925 // or the profile challenge only.
3926 long timeMs = Long.MAX_VALUE;
3927 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3928 for (UserInfo userInfo : profiles) {
3929 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
3930 final int N = policy.mAdminList.size();
3931 for (int i = 0; i < N; i++) {
3932 ActiveAdmin admin = policy.mAdminList.get(i);
3933 if (admin.maximumTimeToUnlock > 0
3934 && timeMs > admin.maximumTimeToUnlock) {
3935 timeMs = admin.maximumTimeToUnlock;
3940 // We only store the last maximum time to lock on the parent profile. So if calling from a
3941 // managed profile, retrieve the policy for the parent.
3942 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
3943 if (policy.mLastMaximumTimeToLock == timeMs) {
3946 policy.mLastMaximumTimeToLock = timeMs;
3948 final long ident = mInjector.binderClearCallingIdentity();
3950 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
3951 // Make sure KEEP_SCREEN_ON is disabled, since that
3952 // would allow bypassing of the maximum time to lock.
3953 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
3956 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
3957 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
3959 mInjector.binderRestoreCallingIdentity(ident);
3964 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
3968 enforceFullCrossUsersPermission(userHandle);
3969 synchronized (this) {
3973 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3974 return admin != null ? admin.maximumTimeToUnlock : time;
3977 // Return the strictest policy across all participating admins.
3978 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
3979 userHandle, parent);
3980 final int N = admins.size();
3981 for (int i = 0; i < N; i++) {
3982 ActiveAdmin admin = admins.get(i);
3984 time = admin.maximumTimeToUnlock;
3985 } else if (admin.maximumTimeToUnlock != 0
3986 && time > admin.maximumTimeToUnlock) {
3987 time = admin.maximumTimeToUnlock;
3995 public void lockNow(boolean parent) {
3999 synchronized (this) {
4000 // This API can only be called by an active device admin,
4001 // so try to retrieve it to check that the caller is one.
4002 getActiveAdminForCallerLocked(
4003 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4005 int userToLock = mInjector.userHandleGetCallingUserId();
4007 // Unless this is a managed profile with work challenge enabled, lock all users.
4008 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4009 userToLock = UserHandle.USER_ALL;
4011 final long ident = mInjector.binderClearCallingIdentity();
4013 mLockPatternUtils.requireStrongAuth(
4014 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4015 if (userToLock == UserHandle.USER_ALL) {
4016 // Power off the display
4017 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4018 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4019 mInjector.getIWindowManager().lockNow(null);
4021 } catch (RemoteException e) {
4023 mInjector.binderRestoreCallingIdentity(ident);
4029 public void enforceCanManageCaCerts(ComponentName who) {
4031 if (!isCallerDelegatedCertInstaller()) {
4032 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4035 synchronized (this) {
4036 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4041 private void enforceCanManageInstalledKeys(ComponentName who) {
4043 if (!isCallerDelegatedCertInstaller()) {
4044 throw new SecurityException("who == null, but caller is not cert installer");
4047 synchronized (this) {
4048 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4053 private boolean isCallerDelegatedCertInstaller() {
4054 final int callingUid = mInjector.binderGetCallingUid();
4055 final int userHandle = UserHandle.getUserId(callingUid);
4056 synchronized (this) {
4057 final DevicePolicyData policy = getUserData(userHandle);
4058 if (policy.mDelegatedCertInstallerPackage == null) {
4063 int uid = mContext.getPackageManager().getPackageUidAsUser(
4064 policy.mDelegatedCertInstallerPackage, userHandle);
4065 return uid == callingUid;
4066 } catch (NameNotFoundException e) {
4073 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4074 enforceCanManageCaCerts(admin);
4078 X509Certificate cert = parseCert(certBuffer);
4079 pemCert = Credentials.convertToPem(cert);
4080 } catch (CertificateException ce) {
4081 Log.e(LOG_TAG, "Problem converting cert", ce);
4083 } catch (IOException ioe) {
4084 Log.e(LOG_TAG, "Problem reading cert", ioe);
4088 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4089 final long id = mInjector.binderClearCallingIdentity();
4091 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4093 keyChainConnection.getService().installCaCertificate(pemCert);
4095 } catch (RemoteException e) {
4096 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4098 keyChainConnection.close();
4100 } catch (InterruptedException e1) {
4101 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4102 Thread.currentThread().interrupt();
4104 mInjector.binderRestoreCallingIdentity(id);
4109 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4110 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4111 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4116 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4117 enforceCanManageCaCerts(admin);
4119 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4120 final long id = mInjector.binderClearCallingIdentity();
4122 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4124 for (int i = 0 ; i < aliases.length; i++) {
4125 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4127 } catch (RemoteException e) {
4128 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4130 keyChainConnection.close();
4132 } catch (InterruptedException ie) {
4133 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4134 Thread.currentThread().interrupt();
4136 mInjector.binderRestoreCallingIdentity(id);
4141 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, String alias,
4142 boolean requestAccess) {
4143 enforceCanManageInstalledKeys(who);
4145 final int callingUid = mInjector.binderGetCallingUid();
4146 final long id = mInjector.binderClearCallingIdentity();
4148 final KeyChainConnection keyChainConnection =
4149 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4151 IKeyChainService keyChain = keyChainConnection.getService();
4152 if (!keyChain.installKeyPair(privKey, cert, alias)) {
4155 if (requestAccess) {
4156 keyChain.setGrant(callingUid, alias, true);
4159 } catch (RemoteException e) {
4160 Log.e(LOG_TAG, "Installing certificate", e);
4162 keyChainConnection.close();
4164 } catch (InterruptedException e) {
4165 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4166 Thread.currentThread().interrupt();
4168 mInjector.binderRestoreCallingIdentity(id);
4174 public boolean removeKeyPair(ComponentName who, String alias) {
4175 enforceCanManageInstalledKeys(who);
4177 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4178 final long id = Binder.clearCallingIdentity();
4180 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4182 IKeyChainService keyChain = keyChainConnection.getService();
4183 return keyChain.removeKeyPair(alias);
4184 } catch (RemoteException e) {
4185 Log.e(LOG_TAG, "Removing keypair", e);
4187 keyChainConnection.close();
4189 } catch (InterruptedException e) {
4190 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4191 Thread.currentThread().interrupt();
4193 Binder.restoreCallingIdentity(id);
4199 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4200 final IBinder response) {
4201 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4202 if (!isCallerWithSystemUid()) {
4206 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4207 // If there is a profile owner, redirect to that; otherwise query the device owner.
4208 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4209 if (aliasChooser == null && caller.isSystem()) {
4210 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4211 if (deviceOwnerAdmin != null) {
4212 aliasChooser = deviceOwnerAdmin.info.getComponent();
4215 if (aliasChooser == null) {
4216 sendPrivateKeyAliasResponse(null, response);
4220 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4221 intent.setComponent(aliasChooser);
4222 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4223 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4224 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4225 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4227 final long id = mInjector.binderClearCallingIdentity();
4229 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4231 public void onReceive(Context context, Intent intent) {
4232 final String chosenAlias = getResultData();
4233 sendPrivateKeyAliasResponse(chosenAlias, response);
4235 }, null, Activity.RESULT_OK, null, null);
4237 mInjector.binderRestoreCallingIdentity(id);
4241 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4242 final IKeyChainAliasCallback keyChainAliasResponse =
4243 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4244 new AsyncTask<Void, Void, Void>() {
4246 protected Void doInBackground(Void... unused) {
4248 keyChainAliasResponse.alias(alias);
4249 } catch (Exception e) {
4250 // Catch everything (not just RemoteException): caller could throw a
4251 // RuntimeException back across processes.
4252 Log.e(LOG_TAG, "error while responding to callback", e);
4260 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4261 throws SecurityException {
4262 int userHandle = UserHandle.getCallingUserId();
4263 synchronized (this) {
4264 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4265 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4266 if (installerPackage != null &&
4267 !isPackageInstalledForUser(installerPackage, userHandle)) {
4268 throw new IllegalArgumentException("Package " + installerPackage
4269 + " is not installed on the current user");
4272 DevicePolicyData policy = getUserData(userHandle);
4273 policy.mDelegatedCertInstallerPackage = installerPackage;
4274 saveSettingsLocked(userHandle);
4279 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4280 int userHandle = UserHandle.getCallingUserId();
4281 synchronized (this) {
4282 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4283 DevicePolicyData policy = getUserData(userHandle);
4284 return policy.mDelegatedCertInstallerPackage;
4289 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage)
4290 throws SecurityException {
4291 synchronized (this) {
4292 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4295 final int userId = mInjector.userHandleGetCallingUserId();
4296 final long token = mInjector.binderClearCallingIdentity();
4298 ConnectivityManager connectivityManager = (ConnectivityManager)
4299 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4300 return connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage);
4302 mInjector.binderRestoreCallingIdentity(token);
4307 public String getAlwaysOnVpnPackage(ComponentName admin)
4308 throws SecurityException {
4309 synchronized (this) {
4310 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4313 final int userId = mInjector.userHandleGetCallingUserId();
4314 final long token = mInjector.binderClearCallingIdentity();
4316 ConnectivityManager connectivityManager = (ConnectivityManager)
4317 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4318 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4320 mInjector.binderRestoreCallingIdentity(token);
4324 private void wipeDataLocked(boolean wipeExtRequested, String reason) {
4325 if (wipeExtRequested) {
4326 StorageManager sm = (StorageManager) mContext.getSystemService(
4327 Context.STORAGE_SERVICE);
4328 sm.wipeAdoptableDisks();
4331 RecoverySystem.rebootWipeUserData(mContext, reason);
4332 } catch (IOException | SecurityException e) {
4333 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4338 public void wipeData(int flags) {
4342 final int userHandle = mInjector.userHandleGetCallingUserId();
4343 enforceFullCrossUsersPermission(userHandle);
4344 synchronized (this) {
4345 // This API can only be called by an active device admin,
4346 // so try to retrieve it to check that the caller is one.
4347 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4348 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4350 final String source = admin.info.getComponent().flattenToShortString();
4352 long ident = mInjector.binderClearCallingIdentity();
4354 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4355 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4356 throw new SecurityException(
4357 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4359 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4360 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4361 if (manager != null) {
4365 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4366 wipeDeviceOrUserLocked(wipeExtRequested, userHandle,
4367 "DevicePolicyManager.wipeData() from " + source);
4369 mInjector.binderRestoreCallingIdentity(ident);
4374 private void wipeDeviceOrUserLocked(boolean wipeExtRequested, final int userHandle, String reason) {
4375 if (userHandle == UserHandle.USER_SYSTEM) {
4376 wipeDataLocked(wipeExtRequested, reason);
4378 mHandler.post(new Runnable() {
4382 IActivityManager am = mInjector.getIActivityManager();
4383 if (am.getCurrentUser().id == userHandle) {
4384 am.switchUser(UserHandle.USER_SYSTEM);
4387 boolean isManagedProfile = isManagedProfile(userHandle);
4388 if (!mUserManager.removeUser(userHandle)) {
4389 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4390 } else if (isManagedProfile) {
4391 sendWipeProfileNotification();
4393 } catch (RemoteException re) {
4401 private void sendWipeProfileNotification() {
4402 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4403 Notification notification = new Notification.Builder(mContext)
4404 .setSmallIcon(android.R.drawable.stat_sys_warning)
4405 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4406 .setContentText(contentText)
4407 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4408 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4410 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4413 private void clearWipeProfileNotification() {
4414 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4418 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4422 enforceFullCrossUsersPermission(userHandle);
4423 mContext.enforceCallingOrSelfPermission(
4424 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4426 synchronized (this) {
4427 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4428 if (admin == null) {
4429 result.sendResult(null);
4432 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4433 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4434 intent.setComponent(admin.info.getComponent());
4435 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4436 null, new BroadcastReceiver() {
4438 public void onReceive(Context context, Intent intent) {
4439 result.sendResult(getResultExtras(false));
4441 }, null, Activity.RESULT_OK, null, null);
4446 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4447 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4451 enforceFullCrossUsersPermission(userHandle);
4453 // Managed Profile password can only be changed when it has a separate challenge.
4454 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4455 enforceNotManagedProfile(userHandle, "set the active password");
4458 mContext.enforceCallingOrSelfPermission(
4459 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4460 validateQualityConstant(quality);
4462 DevicePolicyData policy = getUserData(userHandle);
4464 long ident = mInjector.binderClearCallingIdentity();
4466 synchronized (this) {
4467 policy.mActivePasswordQuality = quality;
4468 policy.mActivePasswordLength = length;
4469 policy.mActivePasswordLetters = letters;
4470 policy.mActivePasswordLowerCase = lowercase;
4471 policy.mActivePasswordUpperCase = uppercase;
4472 policy.mActivePasswordNumeric = numbers;
4473 policy.mActivePasswordSymbols = symbols;
4474 policy.mActivePasswordNonLetter = nonletter;
4475 policy.mFailedPasswordAttempts = 0;
4476 saveSettingsLocked(userHandle);
4477 updatePasswordExpirationsLocked(userHandle);
4478 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
4480 // Send a broadcast to each profile using this password as its primary unlock.
4481 sendAdminCommandForLockscreenPoliciesLocked(
4482 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4483 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
4486 mInjector.binderRestoreCallingIdentity(ident);
4491 * Called any time the device password is updated. Resets all password expiration clocks.
4493 private void updatePasswordExpirationsLocked(int userHandle) {
4494 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4495 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4496 userHandle, /* parent */ false);
4497 final int N = admins.size();
4498 for (int i = 0; i < N; i++) {
4499 ActiveAdmin admin = admins.get(i);
4500 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4501 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4502 long timeout = admin.passwordExpirationTimeout;
4503 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4504 admin.passwordExpirationDate = expiration;
4507 for (int affectedUserId : affectedUserIds) {
4508 saveSettingsLocked(affectedUserId);
4513 public void reportFailedPasswordAttempt(int userHandle) {
4514 enforceFullCrossUsersPermission(userHandle);
4515 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4516 enforceNotManagedProfile(userHandle,
4517 "report failed password attempt if separate profile challenge is not in place");
4519 mContext.enforceCallingOrSelfPermission(
4520 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4522 final long ident = mInjector.binderClearCallingIdentity();
4524 boolean wipeData = false;
4526 synchronized (this) {
4527 DevicePolicyData policy = getUserData(userHandle);
4528 policy.mFailedPasswordAttempts++;
4529 saveSettingsLocked(userHandle);
4531 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4532 userHandle, /* parent */ false);
4533 int max = strictestAdmin != null
4534 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4535 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4536 // Wipe the user/profile associated with the policy that was violated. This
4537 // is not necessarily calling user: if the policy that fired was from a
4538 // managed profile rather than the main user profile, we wipe former only.
4540 identifier = strictestAdmin.getUserHandle().getIdentifier();
4543 sendAdminCommandForLockscreenPoliciesLocked(
4544 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
4545 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4549 // Call without holding lock.
4550 wipeDeviceOrUserLocked(false, identifier,
4551 "reportFailedPasswordAttempt()");
4554 mInjector.binderRestoreCallingIdentity(ident);
4557 if (mInjector.securityLogIsLoggingEnabled()) {
4558 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4559 /*method strength*/ 1);
4564 public void reportSuccessfulPasswordAttempt(int userHandle) {
4565 enforceFullCrossUsersPermission(userHandle);
4566 mContext.enforceCallingOrSelfPermission(
4567 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4569 synchronized (this) {
4570 DevicePolicyData policy = getUserData(userHandle);
4571 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
4572 long ident = mInjector.binderClearCallingIdentity();
4574 policy.mFailedPasswordAttempts = 0;
4575 policy.mPasswordOwner = -1;
4576 saveSettingsLocked(userHandle);
4578 sendAdminCommandForLockscreenPoliciesLocked(
4579 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
4580 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4583 mInjector.binderRestoreCallingIdentity(ident);
4588 if (mInjector.securityLogIsLoggingEnabled()) {
4589 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4590 /*method strength*/ 1);
4595 public void reportFailedFingerprintAttempt(int userHandle) {
4596 enforceFullCrossUsersPermission(userHandle);
4597 mContext.enforceCallingOrSelfPermission(
4598 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4599 if (mInjector.securityLogIsLoggingEnabled()) {
4600 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4601 /*method strength*/ 0);
4606 public void reportSuccessfulFingerprintAttempt(int userHandle) {
4607 enforceFullCrossUsersPermission(userHandle);
4608 mContext.enforceCallingOrSelfPermission(
4609 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4610 if (mInjector.securityLogIsLoggingEnabled()) {
4611 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4612 /*method strength*/ 0);
4617 public void reportKeyguardDismissed(int userHandle) {
4618 enforceFullCrossUsersPermission(userHandle);
4619 mContext.enforceCallingOrSelfPermission(
4620 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4622 if (mInjector.securityLogIsLoggingEnabled()) {
4623 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
4628 public void reportKeyguardSecured(int userHandle) {
4629 enforceFullCrossUsersPermission(userHandle);
4630 mContext.enforceCallingOrSelfPermission(
4631 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4633 if (mInjector.securityLogIsLoggingEnabled()) {
4634 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
4639 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
4640 String exclusionList) {
4644 synchronized(this) {
4645 Preconditions.checkNotNull(who, "ComponentName is null");
4647 // Only check if system user has set global proxy. We don't allow other users to set it.
4648 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4649 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4650 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
4652 // Scan through active admins and find if anyone has already
4653 // set the global proxy.
4654 Set<ComponentName> compSet = policy.mAdminMap.keySet();
4655 for (ComponentName component : compSet) {
4656 ActiveAdmin ap = policy.mAdminMap.get(component);
4657 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
4658 // Another admin already sets the global proxy
4659 // Return it to the caller.
4664 // If the user is not system, don't set the global proxy. Fail silently.
4665 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
4666 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
4667 + UserHandle.getCallingUserId() + " is not permitted.");
4670 if (proxySpec == null) {
4671 admin.specifiesGlobalProxy = false;
4672 admin.globalProxySpec = null;
4673 admin.globalProxyExclusionList = null;
4676 admin.specifiesGlobalProxy = true;
4677 admin.globalProxySpec = proxySpec;
4678 admin.globalProxyExclusionList = exclusionList;
4681 // Reset the global proxy accordingly
4682 // Do this using system permissions, as apps cannot write to secure settings
4683 long origId = mInjector.binderClearCallingIdentity();
4685 resetGlobalProxyLocked(policy);
4687 mInjector.binderRestoreCallingIdentity(origId);
4694 public ComponentName getGlobalProxyAdmin(int userHandle) {
4698 enforceFullCrossUsersPermission(userHandle);
4699 synchronized(this) {
4700 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4701 // Scan through active admins and find if anyone has already
4702 // set the global proxy.
4703 final int N = policy.mAdminList.size();
4704 for (int i = 0; i < N; i++) {
4705 ActiveAdmin ap = policy.mAdminList.get(i);
4706 if (ap.specifiesGlobalProxy) {
4707 // Device admin sets the global proxy
4708 // Return it to the caller.
4709 return ap.info.getComponent();
4713 // No device admin sets the global proxy.
4718 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
4719 synchronized (this) {
4720 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4722 long token = mInjector.binderClearCallingIdentity();
4724 ConnectivityManager connectivityManager = (ConnectivityManager)
4725 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4726 connectivityManager.setGlobalProxy(proxyInfo);
4728 mInjector.binderRestoreCallingIdentity(token);
4732 private void resetGlobalProxyLocked(DevicePolicyData policy) {
4733 final int N = policy.mAdminList.size();
4734 for (int i = 0; i < N; i++) {
4735 ActiveAdmin ap = policy.mAdminList.get(i);
4736 if (ap.specifiesGlobalProxy) {
4737 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
4741 // No device admins defining global proxies - reset global proxy settings to none
4742 saveGlobalProxyLocked(null, null);
4745 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
4746 if (exclusionList == null) {
4749 if (proxySpec == null) {
4752 // Remove white spaces
4753 proxySpec = proxySpec.trim();
4754 String data[] = proxySpec.split(":");
4755 int proxyPort = 8080;
4756 if (data.length > 1) {
4758 proxyPort = Integer.parseInt(data[1]);
4759 } catch (NumberFormatException e) {}
4761 exclusionList = exclusionList.trim();
4763 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
4764 if (!proxyProperties.isValid()) {
4765 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
4768 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
4769 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
4770 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
4775 * Set the storage encryption request for a single admin. Returns the new total request
4776 * status (for all admins).
4779 public int setStorageEncryption(ComponentName who, boolean encrypt) {
4781 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4783 Preconditions.checkNotNull(who, "ComponentName is null");
4784 final int userHandle = UserHandle.getCallingUserId();
4785 synchronized (this) {
4786 // Check for permissions
4787 // Only system user can set storage encryption
4788 if (userHandle != UserHandle.USER_SYSTEM) {
4789 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
4790 + UserHandle.getCallingUserId() + " is not permitted.");
4794 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4795 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
4797 // Quick exit: If the filesystem does not support encryption, we can exit early.
4798 if (!isEncryptionSupported()) {
4799 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4802 // (1) Record the value for the admin so it's sticky
4803 if (ap.encryptionRequested != encrypt) {
4804 ap.encryptionRequested = encrypt;
4805 saveSettingsLocked(userHandle);
4808 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
4809 // (2) Compute "max" for all admins
4810 boolean newRequested = false;
4811 final int N = policy.mAdminList.size();
4812 for (int i = 0; i < N; i++) {
4813 newRequested |= policy.mAdminList.get(i).encryptionRequested;
4816 // Notify OS of new request
4817 setEncryptionRequested(newRequested);
4819 // Return the new global request status
4821 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
4822 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
4827 * Get the current storage encryption request status for a given admin, or aggregate of all
4831 public boolean getStorageEncryption(ComponentName who, int userHandle) {
4835 enforceFullCrossUsersPermission(userHandle);
4836 synchronized (this) {
4837 // Check for permissions if a particular caller is specified
4839 // When checking for a single caller, status is based on caller's request
4840 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
4841 return ap != null ? ap.encryptionRequested : false;
4844 // If no particular caller is specified, return the aggregate set of requests.
4845 // This is short circuited by returning true on the first hit.
4846 DevicePolicyData policy = getUserData(userHandle);
4847 final int N = policy.mAdminList.size();
4848 for (int i = 0; i < N; i++) {
4849 if (policy.mAdminList.get(i).encryptionRequested) {
4858 * Get the current encryption status of the device.
4861 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
4863 // Ok to return current status.
4865 enforceFullCrossUsersPermission(userHandle);
4867 // It's not critical here, but let's make sure the package name is correct, in case
4868 // we start using it for different purposes.
4869 ensureCallerPackage(callerPackage);
4871 final ApplicationInfo ai;
4873 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
4874 } catch (RemoteException e) {
4875 throw new SecurityException(e);
4878 boolean legacyApp = false;
4879 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
4881 } else if ("com.google.android.apps.enterprise.dmagent".equals(ai.packageName)
4882 && ai.versionCode == 697) {
4883 // TODO: STOPSHIP remove this (revert ag/895987) once a new prebuilt is dropped
4887 final int rawStatus = getEncryptionStatus();
4888 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
4889 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
4895 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
4897 private boolean isEncryptionSupported() {
4898 // Note, this can be implemented as
4899 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4900 // But is provided as a separate internal method if there's a faster way to do a
4901 // simple check for supported-or-not.
4902 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4906 * Hook to low-levels: Reporting the current status of encryption.
4907 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
4908 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
4909 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
4910 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
4911 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
4913 private int getEncryptionStatus() {
4914 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
4915 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
4916 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
4917 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
4918 } else if (mInjector.storageManagerIsEncrypted()) {
4919 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
4920 } else if (mInjector.storageManagerIsEncryptable()) {
4921 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
4923 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
4928 * Hook to low-levels: If needed, record the new admin setting for encryption.
4930 private void setEncryptionRequested(boolean encrypt) {
4934 * Set whether the screen capture is disabled for the user managed by the specified admin.
4937 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
4941 Preconditions.checkNotNull(who, "ComponentName is null");
4942 final int userHandle = UserHandle.getCallingUserId();
4943 synchronized (this) {
4944 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4945 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4946 if (ap.disableScreenCapture != disabled) {
4947 ap.disableScreenCapture = disabled;
4948 saveSettingsLocked(userHandle);
4949 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
4955 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
4956 * active admin (if given admin is null).
4959 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
4963 synchronized (this) {
4965 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4966 return (admin != null) ? admin.disableScreenCapture : false;
4969 DevicePolicyData policy = getUserData(userHandle);
4970 final int N = policy.mAdminList.size();
4971 for (int i = 0; i < N; i++) {
4972 ActiveAdmin admin = policy.mAdminList.get(i);
4973 if (admin.disableScreenCapture) {
4981 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
4982 final boolean disabled) {
4983 mHandler.post(new Runnable() {
4987 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
4988 } catch (RemoteException e) {
4989 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
4996 * Set whether auto time is required by the specified admin (must be device owner).
4999 public void setAutoTimeRequired(ComponentName who, boolean required) {
5003 Preconditions.checkNotNull(who, "ComponentName is null");
5004 final int userHandle = UserHandle.getCallingUserId();
5005 synchronized (this) {
5006 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5007 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5008 if (admin.requireAutoTime != required) {
5009 admin.requireAutoTime = required;
5010 saveSettingsLocked(userHandle);
5014 // Turn AUTO_TIME on in settings if it is required
5016 long ident = mInjector.binderClearCallingIdentity();
5018 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5020 mInjector.binderRestoreCallingIdentity(ident);
5026 * Returns whether or not auto time is required by the device owner.
5029 public boolean getAutoTimeRequired() {
5033 synchronized (this) {
5034 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5035 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5040 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5044 Preconditions.checkNotNull(who, "ComponentName is null");
5045 // Allow setting this policy to true only if there is a split system user.
5046 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5047 throw new UnsupportedOperationException(
5048 "Cannot force ephemeral users on systems without split system user.");
5050 boolean removeAllUsers = false;
5051 synchronized (this) {
5052 final ActiveAdmin deviceOwner =
5053 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5054 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5055 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5056 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5057 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5058 removeAllUsers = forceEphemeralUsers;
5061 if (removeAllUsers) {
5062 long identitity = mInjector.binderClearCallingIdentity();
5064 mUserManagerInternal.removeAllUsers();
5066 mInjector.binderRestoreCallingIdentity(identitity);
5072 public boolean getForceEphemeralUsers(ComponentName who) {
5076 Preconditions.checkNotNull(who, "ComponentName is null");
5077 synchronized (this) {
5078 final ActiveAdmin deviceOwner =
5079 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5080 return deviceOwner.forceEphemeralUsers;
5084 private boolean isDeviceOwnerManagedSingleUserDevice() {
5085 synchronized (this) {
5086 if (!mOwners.hasDeviceOwner()) {
5090 final long callingIdentity = mInjector.binderClearCallingIdentity();
5092 if (mInjector.userManagerIsSplitSystemUser()) {
5093 // In split system user mode, only allow the case where the device owner is managing
5094 // the only non-system user of the device
5095 return (mUserManager.getUserCount() == 2
5096 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5098 return mUserManager.getUserCount() == 1;
5101 mInjector.binderRestoreCallingIdentity(callingIdentity);
5105 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5106 synchronized (this) {
5107 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5109 if (!isDeviceOwnerManagedSingleUserDevice()) {
5110 throw new SecurityException(
5111 "There should only be one user, managed by Device Owner");
5116 public boolean requestBugreport(ComponentName who) {
5120 Preconditions.checkNotNull(who, "ComponentName is null");
5121 ensureDeviceOwnerManagingSingleUser(who);
5123 if (mRemoteBugreportServiceIsActive.get()
5124 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5125 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5129 final long callingIdentity = mInjector.binderClearCallingIdentity();
5131 ActivityManagerNative.getDefault().requestBugReport(
5132 ActivityManager.BUGREPORT_OPTION_REMOTE);
5134 mRemoteBugreportServiceIsActive.set(true);
5135 mRemoteBugreportSharingAccepted.set(false);
5136 registerRemoteBugreportReceivers();
5137 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5138 RemoteBugreportUtils.buildNotification(mContext,
5139 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5140 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5141 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5143 } catch (RemoteException re) {
5144 // should never happen
5145 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5148 mInjector.binderRestoreCallingIdentity(callingIdentity);
5152 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5153 Intent intent = new Intent(action);
5154 intent.setComponent(mOwners.getDeviceOwnerComponent());
5155 if (extras != null) {
5156 intent.putExtras(extras);
5158 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5161 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5162 return mOwners.getDeviceOwnerRemoteBugreportUri();
5165 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5166 String bugreportHash) {
5167 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5170 private void registerRemoteBugreportReceivers() {
5172 IntentFilter filterFinished = new IntentFilter(
5173 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5174 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5175 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5176 } catch (IntentFilter.MalformedMimeTypeException e) {
5177 // should never happen, as setting a constant
5178 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5180 IntentFilter filterConsent = new IntentFilter();
5181 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5182 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5183 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5186 private void onBugreportFinished(Intent intent) {
5187 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5188 mRemoteBugreportServiceIsActive.set(false);
5189 Uri bugreportUri = intent.getData();
5190 String bugreportUriString = null;
5191 if (bugreportUri != null) {
5192 bugreportUriString = bugreportUri.toString();
5194 String bugreportHash = intent.getStringExtra(
5195 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5196 if (mRemoteBugreportSharingAccepted.get()) {
5197 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5198 mInjector.getNotificationManager().cancel(LOG_TAG,
5199 RemoteBugreportUtils.NOTIFICATION_ID);
5201 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5202 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5203 RemoteBugreportUtils.buildNotification(mContext,
5204 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5207 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5210 private void onBugreportFailed() {
5211 mRemoteBugreportServiceIsActive.set(false);
5212 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5213 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5214 mRemoteBugreportSharingAccepted.set(false);
5215 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5216 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5217 Bundle extras = new Bundle();
5218 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5219 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5220 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5221 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5222 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5225 private void onBugreportSharingAccepted() {
5226 mRemoteBugreportSharingAccepted.set(true);
5227 String bugreportUriString = null;
5228 String bugreportHash = null;
5229 synchronized (this) {
5230 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5231 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5233 if (bugreportUriString != null) {
5234 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5235 } else if (mRemoteBugreportServiceIsActive.get()) {
5236 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5237 RemoteBugreportUtils.buildNotification(mContext,
5238 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5243 private void onBugreportSharingDeclined() {
5244 if (mRemoteBugreportServiceIsActive.get()) {
5245 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5246 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5247 mRemoteBugreportServiceIsActive.set(false);
5248 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5249 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5251 mRemoteBugreportSharingAccepted.set(false);
5252 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5253 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5256 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5257 String bugreportHash) {
5258 ParcelFileDescriptor pfd = null;
5260 if (bugreportUriString == null) {
5261 throw new FileNotFoundException();
5263 Uri bugreportUri = Uri.parse(bugreportUriString);
5264 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5266 synchronized (this) {
5267 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5268 intent.setComponent(mOwners.getDeviceOwnerComponent());
5269 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5270 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5271 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
5272 bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5273 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5275 } catch (FileNotFoundException e) {
5276 Bundle extras = new Bundle();
5277 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5278 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5279 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5285 } catch (IOException ex) {
5288 mRemoteBugreportSharingAccepted.set(false);
5289 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5294 * Disables all device cameras according to the specified admin.
5297 public void setCameraDisabled(ComponentName who, boolean disabled) {
5301 Preconditions.checkNotNull(who, "ComponentName is null");
5302 final int userHandle = mInjector.userHandleGetCallingUserId();
5303 synchronized (this) {
5304 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5305 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5306 if (ap.disableCamera != disabled) {
5307 ap.disableCamera = disabled;
5308 saveSettingsLocked(userHandle);
5311 // Tell the user manager that the restrictions have changed.
5312 pushUserRestrictions(userHandle);
5316 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5320 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5321 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5324 private boolean getCameraDisabled(ComponentName who, int userHandle,
5325 boolean mergeDeviceOwnerRestriction) {
5329 synchronized (this) {
5331 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5332 return (admin != null) ? admin.disableCamera : false;
5334 // First, see if DO has set it. If so, it's device-wide.
5335 if (mergeDeviceOwnerRestriction) {
5336 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5337 if (deviceOwner != null && deviceOwner.disableCamera) {
5342 // Then check each device admin on the user.
5343 DevicePolicyData policy = getUserData(userHandle);
5344 // Determine whether or not the device camera is disabled for any active admins.
5345 final int N = policy.mAdminList.size();
5346 for (int i = 0; i < N; i++) {
5347 ActiveAdmin admin = policy.mAdminList.get(i);
5348 if (admin.disableCamera) {
5357 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5361 Preconditions.checkNotNull(who, "ComponentName is null");
5362 final int userHandle = mInjector.userHandleGetCallingUserId();
5363 if (isManagedProfile(userHandle)) {
5365 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5367 which = which & PROFILE_KEYGUARD_FEATURES;
5370 synchronized (this) {
5371 ActiveAdmin ap = getActiveAdminForCallerLocked(
5372 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5373 if (ap.disabledKeyguardFeatures != which) {
5374 ap.disabledKeyguardFeatures = which;
5375 saveSettingsLocked(userHandle);
5381 * Gets the disabled state for features in keyguard for the given admin,
5382 * or the aggregate of all active admins if who is null.
5385 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5389 enforceFullCrossUsersPermission(userHandle);
5390 final long ident = mInjector.binderClearCallingIdentity();
5392 synchronized (this) {
5394 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5395 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5398 final List<ActiveAdmin> admins;
5399 if (!parent && isManagedProfile(userHandle)) {
5400 // If we are being asked about a managed profile, just return keyguard features
5401 // disabled by admins in the profile.
5402 admins = getUserDataUnchecked(userHandle).mAdminList;
5404 // Otherwise return those set by admins in the user and its profiles.
5405 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5408 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5409 final int N = admins.size();
5410 for (int i = 0; i < N; i++) {
5411 ActiveAdmin admin = admins.get(i);
5412 int userId = admin.getUserHandle().getIdentifier();
5413 boolean isRequestedUser = !parent && (userId == userHandle);
5414 if (isRequestedUser || !isManagedProfile(userId)) {
5415 // If we are being asked explicitly about this user
5416 // return all disabled features even if its a managed profile.
5417 which |= admin.disabledKeyguardFeatures;
5419 // Otherwise a managed profile is only allowed to disable
5420 // some features on the parent user.
5421 which |= (admin.disabledKeyguardFeatures
5422 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5428 mInjector.binderRestoreCallingIdentity(ident);
5433 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5437 Preconditions.checkNotNull(who, "ComponentName is null");
5438 Preconditions.checkNotNull(packageList, "packageList is null");
5439 final int userHandle = UserHandle.getCallingUserId();
5440 synchronized (this) {
5441 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5442 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5443 admin.keepUninstalledPackages = packageList;
5444 saveSettingsLocked(userHandle);
5445 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5450 public List<String> getKeepUninstalledPackages(ComponentName who) {
5451 Preconditions.checkNotNull(who, "ComponentName is null");
5455 // TODO In split system user mode, allow apps on user 0 to query the list
5456 synchronized (this) {
5457 // Check if this is the device owner who is calling
5458 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5459 return getKeepUninstalledPackagesLocked();
5463 private List<String> getKeepUninstalledPackagesLocked() {
5464 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5465 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5469 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5474 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5475 throw new IllegalArgumentException("Invalid component " + admin
5476 + " for device owner");
5478 synchronized (this) {
5479 enforceCanSetDeviceOwnerLocked(userId);
5480 if (getActiveAdminUncheckedLocked(admin, userId) == null) {
5481 throw new IllegalArgumentException("Not active admin: " + admin);
5484 // Shutting down backup manager service permanently.
5485 long ident = mInjector.binderClearCallingIdentity();
5487 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5488 } catch (RemoteException e) {
5489 throw new IllegalStateException("Failed deactivating backup service.", e);
5491 mInjector.binderRestoreCallingIdentity(ident);
5494 mOwners.setDeviceOwner(admin, ownerName, userId);
5495 mOwners.writeDeviceOwner();
5496 updateDeviceOwnerLocked();
5497 setDeviceOwnerSystemPropertyLocked();
5498 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5500 ident = mInjector.binderClearCallingIdentity();
5502 // TODO Send to system too?
5503 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5505 mInjector.binderRestoreCallingIdentity(ident);
5511 public boolean isDeviceOwner(ComponentName who, int userId) {
5512 synchronized (this) {
5513 return mOwners.hasDeviceOwner()
5514 && mOwners.getDeviceOwnerUserId() == userId
5515 && mOwners.getDeviceOwnerComponent().equals(who);
5519 public boolean isProfileOwner(ComponentName who, int userId) {
5520 final ComponentName profileOwner = getProfileOwner(userId);
5521 return who != null && who.equals(profileOwner);
5525 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5529 if (!callingUserOnly) {
5530 enforceManageUsers();
5532 synchronized (this) {
5533 if (!mOwners.hasDeviceOwner()) {
5536 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
5537 mOwners.getDeviceOwnerUserId()) {
5540 return mOwners.getDeviceOwnerComponent();
5545 public int getDeviceOwnerUserId() {
5547 return UserHandle.USER_NULL;
5549 enforceManageUsers();
5550 synchronized (this) {
5551 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
5556 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
5560 public String getDeviceOwnerName() {
5564 enforceManageUsers();
5565 synchronized (this) {
5566 if (!mOwners.hasDeviceOwner()) {
5569 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
5570 // Should setDeviceOwner/ProfileOwner still take a name?
5571 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
5572 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
5576 // Returns the active device owner or null if there is no device owner.
5578 ActiveAdmin getDeviceOwnerAdminLocked() {
5579 ComponentName component = mOwners.getDeviceOwnerComponent();
5580 if (component == null) {
5584 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
5585 final int n = policy.mAdminList.size();
5586 for (int i = 0; i < n; i++) {
5587 ActiveAdmin admin = policy.mAdminList.get(i);
5588 if (component.equals(admin.info.getComponent())) {
5592 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
5597 public void clearDeviceOwner(String packageName) {
5598 Preconditions.checkNotNull(packageName, "packageName is null");
5599 final int callingUid = mInjector.binderGetCallingUid();
5601 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
5602 UserHandle.getUserId(callingUid));
5603 if (uid != callingUid) {
5604 throw new SecurityException("Invalid packageName");
5606 } catch (NameNotFoundException e) {
5607 throw new SecurityException(e);
5609 synchronized (this) {
5610 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
5611 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
5612 if (!mOwners.hasDeviceOwner()
5613 || !deviceOwnerComponent.getPackageName().equals(packageName)
5614 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
5615 throw new SecurityException(
5616 "clearDeviceOwner can only be called by the device owner");
5618 enforceUserUnlocked(deviceOwnerUserId);
5620 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
5621 if (admin != null) {
5622 admin.disableCamera = false;
5623 admin.userRestrictions = null;
5624 admin.forceEphemeralUsers = false;
5625 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
5627 clearUserPoliciesLocked(deviceOwnerUserId);
5629 mOwners.clearDeviceOwner();
5630 mOwners.writeDeviceOwner();
5631 updateDeviceOwnerLocked();
5632 disableSecurityLoggingIfNotCompliant();
5633 // Reactivate backup service.
5634 long ident = mInjector.binderClearCallingIdentity();
5636 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
5638 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
5639 } catch (RemoteException e) {
5640 throw new IllegalStateException("Failed reactivating backup service.", e);
5642 mInjector.binderRestoreCallingIdentity(ident);
5648 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
5653 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
5654 throw new IllegalArgumentException("Component " + who
5655 + " not installed for userId:" + userHandle);
5657 synchronized (this) {
5658 enforceCanSetProfileOwnerLocked(userHandle);
5660 if (getActiveAdminUncheckedLocked(who, userHandle) == null) {
5661 throw new IllegalArgumentException("Not active admin: " + who);
5664 mOwners.setProfileOwner(who, ownerName, userHandle);
5665 mOwners.writeProfileOwner(userHandle);
5671 public void clearProfileOwner(ComponentName who) {
5675 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
5676 final int userId = callingUser.getIdentifier();
5677 enforceNotManagedProfile(userId, "clear profile owner");
5678 enforceUserUnlocked(userId);
5679 // Check if this is the profile owner who is calling
5680 final ActiveAdmin admin =
5681 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5682 synchronized (this) {
5683 admin.disableCamera = false;
5684 admin.userRestrictions = null;
5685 clearUserPoliciesLocked(userId);
5686 mOwners.removeProfileOwner(userId);
5687 mOwners.writeProfileOwner(userId);
5689 final long ident = mInjector.binderClearCallingIdentity();
5691 removeActiveAdminLocked(who, userId);
5693 mInjector.binderRestoreCallingIdentity(ident);
5699 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
5700 Preconditions.checkNotNull(who, "ComponentName is null");
5705 synchronized (this) {
5706 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5707 long token = mInjector.binderClearCallingIdentity();
5709 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
5711 mInjector.binderRestoreCallingIdentity(token);
5717 public CharSequence getDeviceOwnerLockScreenInfo() {
5718 return mLockPatternUtils.getDeviceOwnerInfo();
5721 private void clearUserPoliciesLocked(int userId) {
5722 // Reset some of the user-specific policies
5723 DevicePolicyData policy = getUserData(userId);
5724 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
5725 policy.mDelegatedCertInstallerPackage = null;
5726 policy.mApplicationRestrictionsManagingPackage = null;
5727 policy.mStatusBarDisabled = false;
5728 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
5729 saveSettingsLocked(userId);
5731 final long ident = mInjector.binderClearCallingIdentity();
5733 mIPackageManager.updatePermissionFlagsForAllApps(
5734 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
5735 0 /* flagValues */, userId);
5736 pushUserRestrictions(userId);
5737 } catch (RemoteException re) {
5739 mInjector.binderRestoreCallingIdentity(ident);
5744 public boolean hasUserSetupCompleted() {
5745 return hasUserSetupCompleted(UserHandle.getCallingUserId());
5748 private boolean hasUserSetupCompleted(int userHandle) {
5752 return getUserData(userHandle).mUserSetupComplete;
5756 public int getUserProvisioningState() {
5758 return DevicePolicyManager.STATE_USER_UNMANAGED;
5760 int userHandle = mInjector.userHandleGetCallingUserId();
5761 return getUserProvisioningState(userHandle);
5764 private int getUserProvisioningState(int userHandle) {
5765 return getUserData(userHandle).mUserProvisioningState;
5769 public void setUserProvisioningState(int newState, int userHandle) {
5774 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
5775 && getManagedUserId(userHandle) == -1) {
5776 // No managed device, user or profile, so setting provisioning state makes no sense.
5777 throw new IllegalStateException("Not allowed to change provisioning state unless a "
5778 + "device or profile owner is set.");
5781 synchronized (this) {
5782 boolean transitionCheckNeeded = true;
5784 // Calling identity/permission checks.
5785 final int callingUid = mInjector.binderGetCallingUid();
5786 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
5787 // ADB shell can only move directly from un-managed to finalized as part of directly
5788 // setting profile-owner or device-owner.
5789 if (getUserProvisioningState(userHandle) !=
5790 DevicePolicyManager.STATE_USER_UNMANAGED
5791 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
5792 throw new IllegalStateException("Not allowed to change provisioning state "
5793 + "unless current provisioning state is unmanaged, and new state is "
5796 transitionCheckNeeded = false;
5798 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
5799 mContext.enforceCallingOrSelfPermission(
5800 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
5803 final DevicePolicyData policyData = getUserData(userHandle);
5804 if (transitionCheckNeeded) {
5805 // Optional state transition check for non-ADB case.
5806 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
5808 policyData.mUserProvisioningState = newState;
5809 saveSettingsLocked(userHandle);
5813 private void checkUserProvisioningStateTransition(int currentState, int newState) {
5814 // Valid transitions for normal use-cases.
5815 switch (currentState) {
5816 case DevicePolicyManager.STATE_USER_UNMANAGED:
5817 // Can move to any state from unmanaged (except itself as an edge case)..
5818 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
5822 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
5823 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
5824 // Can only move to finalized from these states.
5825 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
5829 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
5830 // Current user has a managed-profile, but current user is not managed, so
5831 // rather than moving to finalized state, go back to unmanaged once
5832 // profile provisioning is complete.
5833 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
5837 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
5838 // Cannot transition out of finalized.
5842 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
5843 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
5844 + "from state [" + currentState + "]");
5848 public void setProfileEnabled(ComponentName who) {
5852 Preconditions.checkNotNull(who, "ComponentName is null");
5853 synchronized (this) {
5854 // Check if this is the profile owner who is calling
5855 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5856 final int userId = UserHandle.getCallingUserId();
5857 enforceManagedProfile(userId, "enable the profile");
5859 long id = mInjector.binderClearCallingIdentity();
5861 mUserManager.setUserEnabled(userId);
5862 UserInfo parent = mUserManager.getProfileParent(userId);
5863 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
5864 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
5865 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
5866 Intent.FLAG_RECEIVER_FOREGROUND);
5867 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
5869 mInjector.binderRestoreCallingIdentity(id);
5875 public void setProfileName(ComponentName who, String profileName) {
5876 Preconditions.checkNotNull(who, "ComponentName is null");
5877 int userId = UserHandle.getCallingUserId();
5878 // Check if this is the profile owner (includes device owner).
5879 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5881 long id = mInjector.binderClearCallingIdentity();
5883 mUserManager.setUserName(userId, profileName);
5885 mInjector.binderRestoreCallingIdentity(id);
5890 public ComponentName getProfileOwner(int userHandle) {
5895 synchronized (this) {
5896 return mOwners.getProfileOwnerComponent(userHandle);
5900 // Returns the active profile owner for this user or null if the current user has no
5903 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
5904 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
5905 if (profileOwner == null) {
5908 DevicePolicyData policy = getUserData(userHandle);
5909 final int n = policy.mAdminList.size();
5910 for (int i = 0; i < n; i++) {
5911 ActiveAdmin admin = policy.mAdminList.get(i);
5912 if (profileOwner.equals(admin.info.getComponent())) {
5920 public String getProfileOwnerName(int userHandle) {
5924 enforceManageUsers();
5925 ComponentName profileOwner = getProfileOwner(userHandle);
5926 if (profileOwner == null) {
5929 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
5933 * Canonical name for a given package.
5935 private String getApplicationLabel(String packageName, int userHandle) {
5936 long token = mInjector.binderClearCallingIdentity();
5938 final Context userContext;
5940 UserHandle handle = new UserHandle(userHandle);
5941 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
5942 } catch (PackageManager.NameNotFoundException nnfe) {
5943 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
5946 ApplicationInfo appInfo = userContext.getApplicationInfo();
5947 CharSequence result = null;
5948 if (appInfo != null) {
5949 PackageManager pm = userContext.getPackageManager();
5950 result = pm.getApplicationLabel(appInfo);
5952 return result != null ? result.toString() : null;
5954 mInjector.binderRestoreCallingIdentity(token);
5959 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
5961 * The profile owner can only be set before the user setup phase has completed,
5964 * - adb if there are not accounts.
5966 private void enforceCanSetProfileOwnerLocked(int userHandle) {
5967 UserInfo info = getUserInfo(userHandle);
5969 // User doesn't exist.
5970 throw new IllegalArgumentException(
5971 "Attempted to set profile owner for invalid userId: " + userHandle);
5973 if (info.isGuest()) {
5974 throw new IllegalStateException("Cannot set a profile owner on a guest");
5976 if (mOwners.hasProfileOwner(userHandle)) {
5977 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
5978 + "is already set.");
5980 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
5981 throw new IllegalStateException("Trying to set the profile owner, but the user "
5982 + "already has a device owner.");
5984 int callingUid = mInjector.binderGetCallingUid();
5985 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
5986 if (hasUserSetupCompleted(userHandle) &&
5987 AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) {
5988 throw new IllegalStateException("Not allowed to set the profile owner because "
5989 + "there are already some accounts on the profile");
5993 mContext.enforceCallingOrSelfPermission(
5994 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
5995 if (hasUserSetupCompleted(userHandle) && !isCallerWithSystemUid()) {
5996 throw new IllegalStateException("Cannot set the profile owner on a user which is "
5997 + "already set-up");
6002 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6005 private void enforceCanSetDeviceOwnerLocked(int userId) {
6006 int callingUid = mInjector.binderGetCallingUid();
6007 boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6009 mContext.enforceCallingOrSelfPermission(
6010 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
6013 final int code = checkSetDeviceOwnerPreCondition(userId, isAdb);
6017 case CODE_HAS_DEVICE_OWNER:
6018 throw new IllegalStateException(
6019 "Trying to set the device owner, but device owner is already set.");
6020 case CODE_USER_HAS_PROFILE_OWNER:
6021 throw new IllegalStateException("Trying to set the device owner, but the user "
6022 + "already has a profile owner.");
6023 case CODE_USER_NOT_RUNNING:
6024 throw new IllegalStateException("User not running: " + userId);
6025 case CODE_NOT_SYSTEM_USER:
6026 throw new IllegalStateException("User is not system user");
6027 case CODE_USER_SETUP_COMPLETED:
6028 throw new IllegalStateException(
6029 "Cannot set the device owner if the device is already set-up");
6030 case CODE_NONSYSTEM_USER_EXISTS:
6031 throw new IllegalStateException("Not allowed to set the device owner because there "
6032 + "are already several users on the device");
6033 case CODE_ACCOUNTS_NOT_EMPTY:
6034 throw new IllegalStateException("Not allowed to set the device owner because there "
6035 + "are already some accounts on the device");
6037 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6041 private void enforceUserUnlocked(int userId) {
6042 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6043 "User must be running and unlocked");
6046 private void enforceManageUsers() {
6047 final int callingUid = mInjector.binderGetCallingUid();
6048 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6049 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6053 private void enforceFullCrossUsersPermission(int userHandle) {
6054 enforceSystemUserOrPermission(userHandle,
6055 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6058 private void enforceCrossUsersPermission(int userHandle) {
6059 enforceSystemUserOrPermission(userHandle,
6060 android.Manifest.permission.INTERACT_ACROSS_USERS);
6063 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6064 if (userHandle < 0) {
6065 throw new IllegalArgumentException("Invalid userId " + userHandle);
6067 final int callingUid = mInjector.binderGetCallingUid();
6068 if (userHandle == UserHandle.getUserId(callingUid)) {
6071 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6072 mContext.enforceCallingOrSelfPermission(permission,
6073 "Must be system or have " + permission + " permission");
6077 private void enforceManagedProfile(int userHandle, String message) {
6078 if(!isManagedProfile(userHandle)) {
6079 throw new SecurityException("You can not " + message + " outside a managed profile.");
6083 private void enforceNotManagedProfile(int userHandle, String message) {
6084 if(isManagedProfile(userHandle)) {
6085 throw new SecurityException("You can not " + message + " for a managed profile.");
6089 private void ensureCallerPackage(@Nullable String packageName) {
6090 if (packageName == null) {
6091 Preconditions.checkState(isCallerWithSystemUid(),
6092 "Only caller can omit package name");
6094 final int callingUid = mInjector.binderGetCallingUid();
6095 final int userId = mInjector.userHandleGetCallingUserId();
6097 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6098 packageName, 0, userId);
6099 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6100 } catch (RemoteException e) {
6106 private boolean isCallerWithSystemUid() {
6107 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6110 private int getProfileParentId(int userHandle) {
6111 final long ident = mInjector.binderClearCallingIdentity();
6113 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6114 return parentUser != null ? parentUser.id : userHandle;
6116 mInjector.binderRestoreCallingIdentity(ident);
6120 private int getCredentialOwner(int userHandle, boolean parent) {
6121 final long ident = mInjector.binderClearCallingIdentity();
6124 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6125 if (parentProfile != null) {
6126 userHandle = parentProfile.id;
6129 return mUserManager.getCredentialOwnerProfile(userHandle);
6131 mInjector.binderRestoreCallingIdentity(ident);
6135 private boolean isManagedProfile(int userHandle) {
6136 return getUserInfo(userHandle).isManagedProfile();
6139 private void enableIfNecessary(String packageName, int userId) {
6141 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6142 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6144 if (ai.enabledSetting
6145 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6146 mIPackageManager.setApplicationEnabledSetting(packageName,
6147 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6148 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6150 } catch (RemoteException e) {
6155 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6156 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6157 != PackageManager.PERMISSION_GRANTED) {
6159 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6160 + mInjector.binderGetCallingPid()
6161 + ", uid=" + mInjector.binderGetCallingUid());
6165 synchronized (this) {
6166 pw.println("Current Device Policy Manager state:");
6167 mOwners.dump(" ", pw);
6168 int userCount = mUserData.size();
6169 for (int u = 0; u < userCount; u++) {
6170 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6172 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6173 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6174 final int N = policy.mAdminList.size();
6175 for (int i=0; i<N; i++) {
6176 ActiveAdmin ap = policy.mAdminList.get(i);
6178 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6183 if (!policy.mRemovingAdmins.isEmpty()) {
6184 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6185 + policy.mRemovingAdmins);
6189 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6192 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6196 private String getEncryptionStatusName(int encryptionStatus) {
6197 switch (encryptionStatus) {
6198 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6200 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6201 return "block default key";
6202 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6204 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6206 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6207 return "unsupported";
6208 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6209 return "activating";
6216 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6217 ComponentName activity) {
6218 Preconditions.checkNotNull(who, "ComponentName is null");
6219 final int userHandle = UserHandle.getCallingUserId();
6220 synchronized (this) {
6221 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6223 long id = mInjector.binderClearCallingIdentity();
6225 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6226 } catch (RemoteException re) {
6229 mInjector.binderRestoreCallingIdentity(id);
6235 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6236 Preconditions.checkNotNull(who, "ComponentName is null");
6237 final int userHandle = UserHandle.getCallingUserId();
6238 synchronized (this) {
6239 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6241 long id = mInjector.binderClearCallingIdentity();
6243 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6244 } catch (RemoteException re) {
6247 mInjector.binderRestoreCallingIdentity(id);
6253 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6254 String packageName) {
6255 Preconditions.checkNotNull(admin, "ComponentName is null");
6257 final int userHandle = mInjector.userHandleGetCallingUserId();
6258 synchronized (this) {
6259 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6260 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6263 DevicePolicyData policy = getUserData(userHandle);
6264 policy.mApplicationRestrictionsManagingPackage = packageName;
6265 saveSettingsLocked(userHandle);
6271 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6272 Preconditions.checkNotNull(admin, "ComponentName is null");
6274 final int userHandle = mInjector.userHandleGetCallingUserId();
6275 synchronized (this) {
6276 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6277 DevicePolicyData policy = getUserData(userHandle);
6278 return policy.mApplicationRestrictionsManagingPackage;
6283 public boolean isCallerApplicationRestrictionsManagingPackage() {
6284 final int callingUid = mInjector.binderGetCallingUid();
6285 final int userHandle = UserHandle.getUserId(callingUid);
6286 synchronized (this) {
6287 final DevicePolicyData policy = getUserData(userHandle);
6288 if (policy.mApplicationRestrictionsManagingPackage == null) {
6293 int uid = mContext.getPackageManager().getPackageUidAsUser(
6294 policy.mApplicationRestrictionsManagingPackage, userHandle);
6295 return uid == callingUid;
6296 } catch (NameNotFoundException e) {
6302 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6304 synchronized (this) {
6305 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6307 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6308 throw new SecurityException(
6309 "No admin component given, and caller cannot manage application restrictions "
6310 + "for other apps.");
6315 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6316 enforceCanManageApplicationRestrictions(who);
6318 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6319 final long id = mInjector.binderClearCallingIdentity();
6321 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6323 mInjector.binderRestoreCallingIdentity(id);
6328 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6329 PersistableBundle args) {
6333 Preconditions.checkNotNull(admin, "admin is null");
6334 Preconditions.checkNotNull(agent, "agent is null");
6335 final int userHandle = UserHandle.getCallingUserId();
6336 enforceNotManagedProfile(userHandle, "set trust agent configuration");
6337 synchronized (this) {
6338 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6339 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
6340 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6341 saveSettingsLocked(userHandle);
6346 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6347 ComponentName agent, int userHandle) {
6351 Preconditions.checkNotNull(agent, "agent null");
6352 enforceFullCrossUsersPermission(userHandle);
6354 synchronized (this) {
6355 final String componentName = agent.flattenToString();
6356 if (admin != null) {
6357 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle);
6358 if (ap == null) return null;
6359 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6360 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6361 List<PersistableBundle> result = new ArrayList<PersistableBundle>();
6362 result.add(trustAgentInfo.options);
6366 // Return strictest policy for this user and profiles that are visible from this user.
6367 final List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
6368 List<PersistableBundle> result = null;
6370 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6371 // of the options. If any admin doesn't have options, discard options for the rest
6373 boolean allAdminsHaveOptions = true;
6374 for (UserInfo userInfo : profiles) {
6375 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
6376 final int N = policy.mAdminList.size();
6377 for (int i=0; i < N; i++) {
6378 final ActiveAdmin active = policy.mAdminList.get(i);
6379 final boolean disablesTrust = (active.disabledKeyguardFeatures
6380 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6381 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6382 if (info != null && info.options != null && !info.options.isEmpty()) {
6383 if (disablesTrust) {
6384 if (result == null) {
6385 result = new ArrayList<PersistableBundle>();
6387 result.add(info.options);
6389 Log.w(LOG_TAG, "Ignoring admin " + active.info
6390 + " because it has trust options but doesn't declare "
6391 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6393 } else if (disablesTrust) {
6394 allAdminsHaveOptions = false;
6399 return allAdminsHaveOptions ? result : null;
6404 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6405 Preconditions.checkNotNull(who, "ComponentName is null");
6406 synchronized (this) {
6407 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6409 int userHandle = UserHandle.getCallingUserId();
6410 DevicePolicyData userData = getUserData(userHandle);
6411 userData.mRestrictionsProvider = permissionProvider;
6412 saveSettingsLocked(userHandle);
6417 public ComponentName getRestrictionsProvider(int userHandle) {
6418 synchronized (this) {
6419 if (!isCallerWithSystemUid()) {
6420 throw new SecurityException("Only the system can query the permission provider");
6422 DevicePolicyData userData = getUserData(userHandle);
6423 return userData != null ? userData.mRestrictionsProvider : null;
6428 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6429 Preconditions.checkNotNull(who, "ComponentName is null");
6430 int callingUserId = UserHandle.getCallingUserId();
6431 synchronized (this) {
6432 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6434 long id = mInjector.binderClearCallingIdentity();
6436 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6437 if (parent == null) {
6438 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6442 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6443 mIPackageManager.addCrossProfileIntentFilter(
6444 filter, who.getPackageName(), callingUserId, parent.id, 0);
6446 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6447 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6448 parent.id, callingUserId, 0);
6450 } catch (RemoteException re) {
6453 mInjector.binderRestoreCallingIdentity(id);
6459 public void clearCrossProfileIntentFilters(ComponentName who) {
6460 Preconditions.checkNotNull(who, "ComponentName is null");
6461 int callingUserId = UserHandle.getCallingUserId();
6462 synchronized (this) {
6463 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6464 long id = mInjector.binderClearCallingIdentity();
6466 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6467 if (parent == null) {
6468 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6472 // Removing those that go from the managed profile to the parent.
6473 mIPackageManager.clearCrossProfileIntentFilters(
6474 callingUserId, who.getPackageName());
6475 // And those that go from the parent to the managed profile.
6476 // If we want to support multiple managed profiles, we will have to only remove
6477 // those that have callingUserId as their target.
6478 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6479 } catch (RemoteException re) {
6482 mInjector.binderRestoreCallingIdentity(id);
6488 * @return true if all packages in enabledPackages are either in the list
6489 * permittedList or are a system app.
6491 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6492 List<String> permittedList, int userIdToCheck) {
6493 long id = mInjector.binderClearCallingIdentity();
6495 // If we have an enabled packages list for a managed profile the packages
6496 // we should check are installed for the parent user.
6497 UserInfo user = getUserInfo(userIdToCheck);
6498 if (user.isManagedProfile()) {
6499 userIdToCheck = user.profileGroupId;
6502 for (String enabledPackage : enabledPackages) {
6503 boolean systemService = false;
6505 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
6506 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
6507 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6508 } catch (RemoteException e) {
6509 Log.i(LOG_TAG, "Can't talk to package managed", e);
6511 if (!systemService && !permittedList.contains(enabledPackage)) {
6516 mInjector.binderRestoreCallingIdentity(id);
6521 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
6522 // Not using AccessibilityManager.getInstance because that guesses
6523 // at the user you require based on callingUid and caches for a given
6525 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
6526 IAccessibilityManager service = iBinder == null
6527 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
6528 return new AccessibilityManager(mContext, service, userId);
6532 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
6536 Preconditions.checkNotNull(who, "ComponentName is null");
6538 if (packageList != null) {
6539 int userId = UserHandle.getCallingUserId();
6540 List<AccessibilityServiceInfo> enabledServices = null;
6541 long id = mInjector.binderClearCallingIdentity();
6543 UserInfo user = getUserInfo(userId);
6544 if (user.isManagedProfile()) {
6545 userId = user.profileGroupId;
6547 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
6548 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
6549 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
6551 mInjector.binderRestoreCallingIdentity(id);
6554 if (enabledServices != null) {
6555 List<String> enabledPackages = new ArrayList<String>();
6556 for (AccessibilityServiceInfo service : enabledServices) {
6557 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
6559 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6561 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
6562 + "because it contains already enabled accesibility services.");
6568 synchronized (this) {
6569 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6570 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6571 admin.permittedAccessiblityServices = packageList;
6572 saveSettingsLocked(UserHandle.getCallingUserId());
6578 public List getPermittedAccessibilityServices(ComponentName who) {
6582 Preconditions.checkNotNull(who, "ComponentName is null");
6584 synchronized (this) {
6585 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6586 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6587 return admin.permittedAccessiblityServices;
6592 public List getPermittedAccessibilityServicesForUser(int userId) {
6596 synchronized (this) {
6597 List<String> result = null;
6598 // If we have multiple profiles we return the intersection of the
6599 // permitted lists. This can happen in cases where we have a device
6600 // and profile owner.
6601 List<UserInfo> profiles = mUserManager.getProfiles(userId);
6602 final int PROFILES_SIZE = profiles.size();
6603 for (int i = 0; i < PROFILES_SIZE; ++i) {
6604 // Just loop though all admins, only device or profiles
6605 // owners can have permitted lists set.
6606 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
6607 final int N = policy.mAdminList.size();
6608 for (int j = 0; j < N; j++) {
6609 ActiveAdmin admin = policy.mAdminList.get(j);
6610 List<String> fromAdmin = admin.permittedAccessiblityServices;
6611 if (fromAdmin != null) {
6612 if (result == null) {
6613 result = new ArrayList<String>(fromAdmin);
6615 result.retainAll(fromAdmin);
6621 // If we have a permitted list add all system accessibility services.
6622 if (result != null) {
6623 long id = mInjector.binderClearCallingIdentity();
6625 UserInfo user = getUserInfo(userId);
6626 if (user.isManagedProfile()) {
6627 userId = user.profileGroupId;
6629 AccessibilityManager accessibilityManager =
6630 getAccessibilityManagerForUser(userId);
6631 List<AccessibilityServiceInfo> installedServices =
6632 accessibilityManager.getInstalledAccessibilityServiceList();
6634 if (installedServices != null) {
6635 for (AccessibilityServiceInfo service : installedServices) {
6636 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
6637 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
6638 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6639 result.add(serviceInfo.packageName);
6644 mInjector.binderRestoreCallingIdentity(id);
6653 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
6658 Preconditions.checkNotNull(who, "ComponentName is null");
6659 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
6660 if (!isCallerWithSystemUid()){
6661 throw new SecurityException(
6662 "Only the system can query if an accessibility service is disabled by admin");
6664 synchronized (this) {
6665 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6666 if (admin.permittedAccessiblityServices == null) {
6669 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
6670 admin.permittedAccessiblityServices, userHandle);
6674 private boolean checkCallerIsCurrentUserOrProfile() {
6675 int callingUserId = UserHandle.getCallingUserId();
6676 long token = mInjector.binderClearCallingIdentity();
6678 UserInfo currentUser;
6679 UserInfo callingUser = getUserInfo(callingUserId);
6681 currentUser = mInjector.getIActivityManager().getCurrentUser();
6682 } catch (RemoteException e) {
6683 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
6687 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
6688 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
6689 + "of a user that isn't the foreground user.");
6692 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
6693 Slog.e(LOG_TAG, "Cannot set permitted input methods "
6694 + "of a user that isn't the foreground user.");
6698 mInjector.binderRestoreCallingIdentity(token);
6704 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
6708 Preconditions.checkNotNull(who, "ComponentName is null");
6710 // TODO When InputMethodManager supports per user calls remove
6711 // this restriction.
6712 if (!checkCallerIsCurrentUserOrProfile()) {
6716 if (packageList != null) {
6717 // InputMethodManager fetches input methods for current user.
6718 // So this can only be set when calling user is the current user
6719 // or parent is current user in case of managed profiles.
6720 InputMethodManager inputMethodManager =
6721 mContext.getSystemService(InputMethodManager.class);
6722 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
6724 if (enabledImes != null) {
6725 List<String> enabledPackages = new ArrayList<String>();
6726 for (InputMethodInfo ime : enabledImes) {
6727 enabledPackages.add(ime.getPackageName());
6729 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6730 mInjector.binderGetCallingUserHandle().getIdentifier())) {
6731 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
6732 + "because it contains already enabled input method.");
6738 synchronized (this) {
6739 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6740 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6741 admin.permittedInputMethods = packageList;
6742 saveSettingsLocked(UserHandle.getCallingUserId());
6748 public List getPermittedInputMethods(ComponentName who) {
6752 Preconditions.checkNotNull(who, "ComponentName is null");
6754 synchronized (this) {
6755 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6756 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6757 return admin.permittedInputMethods;
6762 public List getPermittedInputMethodsForCurrentUser() {
6763 UserInfo currentUser;
6765 currentUser = mInjector.getIActivityManager().getCurrentUser();
6766 } catch (RemoteException e) {
6767 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
6768 // Activity managed is dead, just allow all IMEs
6772 int userId = currentUser.id;
6773 synchronized (this) {
6774 List<String> result = null;
6775 // If we have multiple profiles we return the intersection of the
6776 // permitted lists. This can happen in cases where we have a device
6777 // and profile owner.
6778 List<UserInfo> profiles = mUserManager.getProfiles(userId);
6779 final int PROFILES_SIZE = profiles.size();
6780 for (int i = 0; i < PROFILES_SIZE; ++i) {
6781 // Just loop though all admins, only device or profiles
6782 // owners can have permitted lists set.
6783 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
6784 final int N = policy.mAdminList.size();
6785 for (int j = 0; j < N; j++) {
6786 ActiveAdmin admin = policy.mAdminList.get(j);
6787 List<String> fromAdmin = admin.permittedInputMethods;
6788 if (fromAdmin != null) {
6789 if (result == null) {
6790 result = new ArrayList<String>(fromAdmin);
6792 result.retainAll(fromAdmin);
6798 // If we have a permitted list add all system input methods.
6799 if (result != null) {
6800 InputMethodManager inputMethodManager =
6801 mContext.getSystemService(InputMethodManager.class);
6802 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
6803 long id = mInjector.binderClearCallingIdentity();
6806 for (InputMethodInfo ime : imes) {
6807 ServiceInfo serviceInfo = ime.getServiceInfo();
6808 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
6809 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6810 result.add(serviceInfo.packageName);
6815 mInjector.binderRestoreCallingIdentity(id);
6823 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
6828 Preconditions.checkNotNull(who, "ComponentName is null");
6829 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
6830 if (!isCallerWithSystemUid()) {
6831 throw new SecurityException(
6832 "Only the system can query if an input method is disabled by admin");
6834 synchronized (this) {
6835 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6836 if (admin.permittedInputMethods == null) {
6839 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
6840 admin.permittedInputMethods, userHandle);
6844 private void sendAdminEnabledBroadcastLocked(int userHandle) {
6845 DevicePolicyData policyData = getUserData(userHandle);
6846 if (policyData.mAdminBroadcastPending) {
6847 // Send the initialization data to profile owner and delete the data
6848 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
6849 if (admin != null) {
6850 PersistableBundle initBundle = policyData.mInitBundle;
6851 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
6852 initBundle == null ? null : new Bundle(initBundle), null);
6854 policyData.mInitBundle = null;
6855 policyData.mAdminBroadcastPending = false;
6856 saveSettingsLocked(userHandle);
6861 public UserHandle createAndManageUser(ComponentName admin, String name,
6862 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
6863 Preconditions.checkNotNull(admin, "admin is null");
6864 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
6865 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
6866 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
6867 + admin + " are not in the same package");
6869 // Only allow the system user to use this method
6870 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
6871 throw new SecurityException("createAndManageUser was called from non-system user");
6873 if (!mInjector.userManagerIsSplitSystemUser()
6874 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
6875 throw new IllegalArgumentException(
6876 "Ephemeral users are only supported on systems with a split system user.");
6879 UserHandle user = null;
6880 synchronized (this) {
6881 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6883 final long id = mInjector.binderClearCallingIdentity();
6885 int userInfoFlags = 0;
6886 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
6887 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
6889 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
6891 if (userInfo != null) {
6892 user = userInfo.getUserHandle();
6895 mInjector.binderRestoreCallingIdentity(id);
6902 final long id = mInjector.binderClearCallingIdentity();
6904 final String adminPkg = admin.getPackageName();
6906 final int userHandle = user.getIdentifier();
6908 // Install the profile owner if not present.
6909 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
6910 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
6912 } catch (RemoteException e) {
6913 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
6914 + "removing created user", e);
6915 mUserManager.removeUser(user.getIdentifier());
6919 setActiveAdmin(profileOwner, true, userHandle);
6920 // User is not started yet, the broadcast by setActiveAdmin will not be received.
6921 // So we store adminExtras for broadcasting when the user starts for first time.
6922 synchronized(this) {
6923 DevicePolicyData policyData = getUserData(userHandle);
6924 policyData.mInitBundle = adminExtras;
6925 policyData.mAdminBroadcastPending = true;
6926 saveSettingsLocked(userHandle);
6928 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
6929 setProfileOwner(profileOwner, ownerName, userHandle);
6931 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
6932 Settings.Secure.putIntForUser(mContext.getContentResolver(),
6933 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
6938 mInjector.binderRestoreCallingIdentity(id);
6943 public boolean removeUser(ComponentName who, UserHandle userHandle) {
6944 Preconditions.checkNotNull(who, "ComponentName is null");
6945 synchronized (this) {
6946 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6948 long id = mInjector.binderClearCallingIdentity();
6950 return mUserManager.removeUser(userHandle.getIdentifier());
6952 mInjector.binderRestoreCallingIdentity(id);
6958 public boolean switchUser(ComponentName who, UserHandle userHandle) {
6959 Preconditions.checkNotNull(who, "ComponentName is null");
6960 synchronized (this) {
6961 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6963 long id = mInjector.binderClearCallingIdentity();
6965 int userId = UserHandle.USER_SYSTEM;
6966 if (userHandle != null) {
6967 userId = userHandle.getIdentifier();
6969 return mInjector.getIActivityManager().switchUser(userId);
6970 } catch (RemoteException e) {
6971 Log.e(LOG_TAG, "Couldn't switch user", e);
6974 mInjector.binderRestoreCallingIdentity(id);
6980 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
6981 enforceCanManageApplicationRestrictions(who);
6983 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6984 final long id = mInjector.binderClearCallingIdentity();
6986 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
6987 // if no restrictions were saved, mUserManager.getApplicationRestrictions
6988 // returns null, but DPM method should return an empty Bundle as per JavaDoc
6989 return bundle != null ? bundle : Bundle.EMPTY;
6991 mInjector.binderRestoreCallingIdentity(id);
6996 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
6997 boolean suspended) {
6998 Preconditions.checkNotNull(who, "ComponentName is null");
6999 int callingUserId = UserHandle.getCallingUserId();
7000 synchronized (this) {
7001 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7003 long id = mInjector.binderClearCallingIdentity();
7005 return mIPackageManager.setPackagesSuspendedAsUser(
7006 packageNames, suspended, callingUserId);
7007 } catch (RemoteException re) {
7008 // Shouldn't happen.
7009 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7011 mInjector.binderRestoreCallingIdentity(id);
7013 return packageNames;
7018 public boolean getPackageSuspended(ComponentName who, String packageName) {
7019 Preconditions.checkNotNull(who, "ComponentName is null");
7020 int callingUserId = UserHandle.getCallingUserId();
7021 synchronized (this) {
7022 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7024 long id = mInjector.binderClearCallingIdentity();
7026 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7027 } catch (RemoteException re) {
7028 // Shouldn't happen.
7029 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7031 mInjector.binderRestoreCallingIdentity(id);
7038 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7039 Preconditions.checkNotNull(who, "ComponentName is null");
7040 if (!UserRestrictionsUtils.isValidRestriction(key)) {
7044 final int userHandle = mInjector.userHandleGetCallingUserId();
7045 synchronized (this) {
7046 ActiveAdmin activeAdmin =
7047 getActiveAdminForCallerLocked(who,
7048 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7049 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7050 if (isDeviceOwner) {
7051 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7052 throw new SecurityException("Device owner cannot set user restriction " + key);
7054 } else { // profile owner
7055 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7056 throw new SecurityException("Profile owner cannot set user restriction " + key);
7060 // Save the restriction to ActiveAdmin.
7061 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7062 saveSettingsLocked(userHandle);
7064 pushUserRestrictions(userHandle);
7066 sendChangedNotification(userHandle);
7070 private void pushUserRestrictions(int userId) {
7071 synchronized (this) {
7072 final Bundle global;
7073 final Bundle local = new Bundle();
7074 if (mOwners.isDeviceOwnerUserId(userId)) {
7075 global = new Bundle();
7077 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7078 if (deviceOwner == null) {
7079 return; // Shouldn't happen.
7082 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7084 // DO can disable camera globally.
7085 if (deviceOwner.disableCamera) {
7086 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7091 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7092 if (profileOwner != null) {
7093 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7096 // Also merge in *local* camera restriction.
7097 if (getCameraDisabled(/* who= */ null,
7098 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7099 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7101 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7106 public Bundle getUserRestrictions(ComponentName who, int userHandle) {
7107 Preconditions.checkNotNull(who, "ComponentName is null");
7108 enforceFullCrossUsersPermission(userHandle);
7109 synchronized (this) {
7110 ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(who, userHandle);
7111 if (activeAdmin == null) {
7112 throw new SecurityException("No active admin: " + activeAdmin);
7114 if (activeAdmin.getUid() != mInjector.binderGetCallingUid()) {
7115 mContext.enforceCallingOrSelfPermission(
7116 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
7117 "Calling uid " + mInjector.binderGetCallingUid() + " neither owns the admin"
7118 + " " + who + " nor has MANAGE_PROFILE_AND_DEVICE_OWNERS permission");
7120 return activeAdmin.userRestrictions;
7125 public boolean setApplicationHidden(ComponentName who, String packageName,
7127 Preconditions.checkNotNull(who, "ComponentName is null");
7128 int callingUserId = UserHandle.getCallingUserId();
7129 synchronized (this) {
7130 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7132 long id = mInjector.binderClearCallingIdentity();
7134 return mIPackageManager.setApplicationHiddenSettingAsUser(
7135 packageName, hidden, callingUserId);
7136 } catch (RemoteException re) {
7138 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7140 mInjector.binderRestoreCallingIdentity(id);
7147 public boolean isApplicationHidden(ComponentName who, String packageName) {
7148 Preconditions.checkNotNull(who, "ComponentName is null");
7149 int callingUserId = UserHandle.getCallingUserId();
7150 synchronized (this) {
7151 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7153 long id = mInjector.binderClearCallingIdentity();
7155 return mIPackageManager.getApplicationHiddenSettingAsUser(
7156 packageName, callingUserId);
7157 } catch (RemoteException re) {
7159 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7161 mInjector.binderRestoreCallingIdentity(id);
7168 public void enableSystemApp(ComponentName who, String packageName) {
7169 Preconditions.checkNotNull(who, "ComponentName is null");
7170 synchronized (this) {
7171 // This API can only be called by an active device admin,
7172 // so try to retrieve it to check that the caller is one.
7173 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7175 int userId = UserHandle.getCallingUserId();
7176 long id = mInjector.binderClearCallingIdentity();
7180 Slog.v(LOG_TAG, "installing " + packageName + " for "
7184 int parentUserId = getProfileParentId(userId);
7185 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7186 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7190 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7192 } catch (RemoteException re) {
7194 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7196 mInjector.binderRestoreCallingIdentity(id);
7202 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7203 Preconditions.checkNotNull(who, "ComponentName is null");
7204 synchronized (this) {
7205 // This API can only be called by an active device admin,
7206 // so try to retrieve it to check that the caller is one.
7207 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7209 int userId = UserHandle.getCallingUserId();
7210 long id = mInjector.binderClearCallingIdentity();
7213 int parentUserId = getProfileParentId(userId);
7214 List<ResolveInfo> activitiesToEnable = mIPackageManager
7215 .queryIntentActivities(intent,
7216 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7217 PackageManager.MATCH_DIRECT_BOOT_AWARE
7218 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7223 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7225 int numberOfAppsInstalled = 0;
7226 if (activitiesToEnable != null) {
7227 for (ResolveInfo info : activitiesToEnable) {
7228 if (info.activityInfo != null) {
7229 String packageName = info.activityInfo.packageName;
7230 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7231 numberOfAppsInstalled++;
7232 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7234 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7240 return numberOfAppsInstalled;
7241 } catch (RemoteException e) {
7243 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7246 mInjector.binderRestoreCallingIdentity(id);
7251 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7252 throws RemoteException {
7253 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7255 if (appInfo == null) {
7256 throw new IllegalArgumentException("The application " + packageName +
7257 " is not present on this device");
7259 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7263 public void setAccountManagementDisabled(ComponentName who, String accountType,
7268 Preconditions.checkNotNull(who, "ComponentName is null");
7269 synchronized (this) {
7270 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7271 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7273 ap.accountTypesWithManagementDisabled.add(accountType);
7275 ap.accountTypesWithManagementDisabled.remove(accountType);
7277 saveSettingsLocked(UserHandle.getCallingUserId());
7282 public String[] getAccountTypesWithManagementDisabled() {
7283 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7287 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7288 enforceFullCrossUsersPermission(userId);
7292 synchronized (this) {
7293 DevicePolicyData policy = getUserData(userId);
7294 final int N = policy.mAdminList.size();
7295 ArraySet<String> resultSet = new ArraySet<>();
7296 for (int i = 0; i < N; i++) {
7297 ActiveAdmin admin = policy.mAdminList.get(i);
7298 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7300 return resultSet.toArray(new String[resultSet.size()]);
7305 public void setUninstallBlocked(ComponentName who, String packageName,
7306 boolean uninstallBlocked) {
7307 Preconditions.checkNotNull(who, "ComponentName is null");
7308 final int userId = UserHandle.getCallingUserId();
7309 synchronized (this) {
7310 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7312 long id = mInjector.binderClearCallingIdentity();
7314 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7315 } catch (RemoteException re) {
7316 // Shouldn't happen.
7317 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7319 mInjector.binderRestoreCallingIdentity(id);
7325 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7326 // This function should return true if and only if the package is blocked by
7327 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7328 // when the package is a system app, or when it is an active device admin.
7329 final int userId = UserHandle.getCallingUserId();
7331 synchronized (this) {
7333 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7336 long id = mInjector.binderClearCallingIdentity();
7338 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7339 } catch (RemoteException re) {
7340 // Shouldn't happen.
7341 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7343 mInjector.binderRestoreCallingIdentity(id);
7350 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7354 Preconditions.checkNotNull(who, "ComponentName is null");
7355 synchronized (this) {
7356 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7357 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7358 if (admin.disableCallerId != disabled) {
7359 admin.disableCallerId = disabled;
7360 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7366 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7370 Preconditions.checkNotNull(who, "ComponentName is null");
7371 synchronized (this) {
7372 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7373 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7374 return admin.disableCallerId;
7379 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7380 enforceCrossUsersPermission(userId);
7381 synchronized (this) {
7382 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7383 return (admin != null) ? admin.disableCallerId : false;
7388 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7392 Preconditions.checkNotNull(who, "ComponentName is null");
7393 synchronized (this) {
7394 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7395 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7396 if (admin.disableContactsSearch != disabled) {
7397 admin.disableContactsSearch = disabled;
7398 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7404 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7408 Preconditions.checkNotNull(who, "ComponentName is null");
7409 synchronized (this) {
7410 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7411 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7412 return admin.disableContactsSearch;
7417 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7418 enforceCrossUsersPermission(userId);
7419 synchronized (this) {
7420 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7421 return (admin != null) ? admin.disableContactsSearch : false;
7426 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7427 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7428 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7429 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7430 final int callingUserId = UserHandle.getCallingUserId();
7432 final long ident = mInjector.binderClearCallingIdentity();
7434 synchronized (this) {
7435 final int managedUserId = getManagedUserId(callingUserId);
7436 if (managedUserId < 0) {
7439 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7442 "Cross-profile contacts access disabled for user " + managedUserId);
7446 ContactsInternal.startQuickContactWithErrorToastForUser(
7447 mContext, intent, new UserHandle(managedUserId));
7450 mInjector.binderRestoreCallingIdentity(ident);
7455 * @return true if cross-profile QuickContact is disabled
7457 private boolean isCrossProfileQuickContactDisabled(int userId) {
7458 return getCrossProfileCallerIdDisabledForUser(userId)
7459 && getCrossProfileContactsSearchDisabledForUser(userId);
7463 * @return the user ID of the managed user that is linked to the current user, if any.
7466 public int getManagedUserId(int callingUserId) {
7468 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7471 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7472 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7473 continue; // Caller user self, or not a managed profile. Skip.
7476 Log.v(LOG_TAG, "Managed user=" + ui.id);
7481 Log.v(LOG_TAG, "Managed user not found.");
7487 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7491 Preconditions.checkNotNull(who, "ComponentName is null");
7492 synchronized (this) {
7493 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7494 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7495 if (admin.disableBluetoothContactSharing != disabled) {
7496 admin.disableBluetoothContactSharing = disabled;
7497 saveSettingsLocked(UserHandle.getCallingUserId());
7503 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
7507 Preconditions.checkNotNull(who, "ComponentName is null");
7508 synchronized (this) {
7509 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7510 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7511 return admin.disableBluetoothContactSharing;
7516 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
7517 // TODO: Should there be a check to make sure this relationship is
7518 // within a profile group?
7519 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
7520 synchronized (this) {
7521 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7522 return (admin != null) ? admin.disableBluetoothContactSharing : false;
7527 * Sets which packages may enter lock task mode.
7529 * <p>This function can only be called by the device owner or alternatively by the profile owner
7530 * in case the user is affiliated.
7532 * @param packages The list of packages allowed to enter lock task mode.
7535 public void setLockTaskPackages(ComponentName who, String[] packages)
7536 throws SecurityException {
7537 Preconditions.checkNotNull(who, "ComponentName is null");
7538 synchronized (this) {
7539 ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
7540 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
7541 ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
7542 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
7543 if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
7544 int userHandle = mInjector.userHandleGetCallingUserId();
7545 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
7547 throw new SecurityException("Admin " + who +
7548 " is neither the device owner or affiliated user's profile owner.");
7553 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
7554 DevicePolicyData policy = getUserData(userHandle);
7555 policy.mLockTaskPackages = packages;
7557 // Store the settings persistently.
7558 saveSettingsLocked(userHandle);
7559 updateLockTaskPackagesLocked(packages, userHandle);
7563 * This function returns the list of components allowed to start the task lock mode.
7566 public String[] getLockTaskPackages(ComponentName who) {
7567 Preconditions.checkNotNull(who, "ComponentName is null");
7568 synchronized (this) {
7569 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7570 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
7571 final List<String> packages = getLockTaskPackagesLocked(userHandle);
7572 return packages.toArray(new String[packages.size()]);
7576 private List<String> getLockTaskPackagesLocked(int userHandle) {
7577 final DevicePolicyData policy = getUserData(userHandle);
7578 return policy.mLockTaskPackages;
7582 * This function lets the caller know whether the given package is allowed to start the
7584 * @param pkg The package to check
7587 public boolean isLockTaskPermitted(String pkg) {
7588 // Get current user's devicepolicy
7589 int uid = mInjector.binderGetCallingUid();
7590 int userHandle = UserHandle.getUserId(uid);
7591 DevicePolicyData policy = getUserData(userHandle);
7592 synchronized (this) {
7593 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
7594 String lockTaskPackage = policy.mLockTaskPackages.get(i);
7596 // If the given package equals one of the packages stored our list,
7597 // we allow this package to start lock task mode.
7598 if (lockTaskPackage.equals(pkg)) {
7607 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
7608 if (!isCallerWithSystemUid()) {
7609 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
7611 synchronized (this) {
7612 final DevicePolicyData policy = getUserData(userHandle);
7613 Bundle adminExtras = new Bundle();
7614 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
7615 for (ActiveAdmin admin : policy.mAdminList) {
7616 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
7617 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
7618 if (ownsDevice || ownsProfile) {
7620 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
7623 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
7631 public void setGlobalSetting(ComponentName who, String setting, String value) {
7632 Preconditions.checkNotNull(who, "ComponentName is null");
7634 synchronized (this) {
7635 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7637 // Some settings are no supported any more. However we do not want to throw a
7638 // SecurityException to avoid breaking apps.
7639 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
7640 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
7644 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
7645 throw new SecurityException(String.format(
7646 "Permission denial: device owners cannot update %1$s", setting));
7649 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
7650 // ignore if it contradicts an existing policy
7651 long timeMs = getMaximumTimeToLock(
7652 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
7653 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
7658 long id = mInjector.binderClearCallingIdentity();
7660 mInjector.settingsGlobalPutString(setting, value);
7662 mInjector.binderRestoreCallingIdentity(id);
7668 public void setSecureSetting(ComponentName who, String setting, String value) {
7669 Preconditions.checkNotNull(who, "ComponentName is null");
7670 int callingUserId = mInjector.userHandleGetCallingUserId();
7672 synchronized (this) {
7673 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7675 if (isDeviceOwner(who, callingUserId)) {
7676 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
7677 throw new SecurityException(String.format(
7678 "Permission denial: Device owners cannot update %1$s", setting));
7680 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
7681 throw new SecurityException(String.format(
7682 "Permission denial: Profile owners cannot update %1$s", setting));
7685 long id = mInjector.binderClearCallingIdentity();
7687 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
7689 mInjector.binderRestoreCallingIdentity(id);
7695 public void setMasterVolumeMuted(ComponentName who, boolean on) {
7696 Preconditions.checkNotNull(who, "ComponentName is null");
7697 synchronized (this) {
7698 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7699 int userId = UserHandle.getCallingUserId();
7700 long identity = mInjector.binderClearCallingIdentity();
7702 IAudioService iAudioService = IAudioService.Stub.asInterface(
7703 ServiceManager.getService(Context.AUDIO_SERVICE));
7704 iAudioService.setMasterMute(on, 0, mContext.getPackageName(), userId);
7705 } catch (RemoteException re) {
7706 Slog.e(LOG_TAG, "Failed to setMasterMute", re);
7708 mInjector.binderRestoreCallingIdentity(identity);
7714 public boolean isMasterVolumeMuted(ComponentName who) {
7715 Preconditions.checkNotNull(who, "ComponentName is null");
7716 synchronized (this) {
7717 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7719 AudioManager audioManager =
7720 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
7721 return audioManager.isMasterMute();
7726 public void setUserIcon(ComponentName who, Bitmap icon) {
7727 synchronized (this) {
7728 Preconditions.checkNotNull(who, "ComponentName is null");
7729 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7731 int userId = UserHandle.getCallingUserId();
7732 long id = mInjector.binderClearCallingIdentity();
7734 mUserManagerInternal.setUserIcon(userId, icon);
7736 mInjector.binderRestoreCallingIdentity(id);
7742 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
7743 Preconditions.checkNotNull(who, "ComponentName is null");
7744 synchronized (this) {
7745 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7747 final int userId = UserHandle.getCallingUserId();
7749 long ident = mInjector.binderClearCallingIdentity();
7751 // disallow disabling the keyguard if a password is currently set
7752 if (disabled && mLockPatternUtils.isSecure(userId)) {
7755 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
7757 mInjector.binderRestoreCallingIdentity(ident);
7763 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
7764 int userId = UserHandle.getCallingUserId();
7765 synchronized (this) {
7766 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7767 DevicePolicyData policy = getUserData(userId);
7768 if (policy.mStatusBarDisabled != disabled) {
7769 if (!setStatusBarDisabledInternal(disabled, userId)) {
7772 policy.mStatusBarDisabled = disabled;
7773 saveSettingsLocked(userId);
7779 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
7780 long ident = mInjector.binderClearCallingIdentity();
7782 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
7783 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
7784 if (statusBarService != null) {
7785 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
7786 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
7787 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
7788 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
7791 } catch (RemoteException e) {
7792 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
7794 mInjector.binderRestoreCallingIdentity(ident);
7800 * We need to update the internal state of whether a user has completed setup once. After
7801 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
7802 * as we don't trust any apps that might try to reset it.
7804 * Unfortunately, we don't know which user's setup state was changed, so we write all of
7807 void updateUserSetupComplete() {
7808 List<UserInfo> users = mUserManager.getUsers(true);
7809 final int N = users.size();
7810 for (int i = 0; i < N; i++) {
7811 int userHandle = users.get(i).id;
7812 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
7814 DevicePolicyData policy = getUserData(userHandle);
7815 if (!policy.mUserSetupComplete) {
7816 policy.mUserSetupComplete = true;
7817 synchronized (this) {
7818 saveSettingsLocked(userHandle);
7825 private class SetupContentObserver extends ContentObserver {
7827 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
7828 Settings.Secure.USER_SETUP_COMPLETE);
7829 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
7830 Settings.Global.DEVICE_PROVISIONED);
7832 public SetupContentObserver(Handler handler) {
7836 void register(ContentResolver resolver) {
7837 resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
7838 resolver.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
7842 public void onChange(boolean selfChange, Uri uri) {
7843 if (mUserSetupComplete.equals(uri)) {
7844 updateUserSetupComplete();
7845 } else if (mDeviceProvisioned.equals(uri)) {
7846 synchronized (DevicePolicyManagerService.this) {
7847 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
7848 // is delayed until device is marked as provisioned.
7849 setDeviceOwnerSystemPropertyLocked();
7856 final class LocalService extends DevicePolicyManagerInternal {
7857 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
7860 public List<String> getCrossProfileWidgetProviders(int profileId) {
7861 synchronized (DevicePolicyManagerService.this) {
7862 if (mOwners == null) {
7863 return Collections.emptyList();
7865 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
7866 if (ownerComponent == null) {
7867 return Collections.emptyList();
7870 DevicePolicyData policy = getUserDataUnchecked(profileId);
7871 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
7873 if (admin == null || admin.crossProfileWidgetProviders == null
7874 || admin.crossProfileWidgetProviders.isEmpty()) {
7875 return Collections.emptyList();
7878 return admin.crossProfileWidgetProviders;
7883 public void addOnCrossProfileWidgetProvidersChangeListener(
7884 OnCrossProfileWidgetProvidersChangeListener listener) {
7885 synchronized (DevicePolicyManagerService.this) {
7886 if (mWidgetProviderListeners == null) {
7887 mWidgetProviderListeners = new ArrayList<>();
7889 if (!mWidgetProviderListeners.contains(listener)) {
7890 mWidgetProviderListeners.add(listener);
7896 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
7897 synchronized(DevicePolicyManagerService.this) {
7898 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
7902 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
7903 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
7904 synchronized (DevicePolicyManagerService.this) {
7905 listeners = new ArrayList<>(mWidgetProviderListeners);
7907 final int listenerCount = listeners.size();
7908 for (int i = 0; i < listenerCount; i++) {
7909 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
7910 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
7915 public boolean hasDeviceOwnerOrProfileOwner(String packageName, int userId) {
7916 if (!mHasFeature || packageName == null) {
7920 throw new UnsupportedOperationException("userId should be >= 0");
7922 synchronized (DevicePolicyManagerService.this) {
7923 if (packageName.equals(mOwners.getProfileOwnerPackage(userId))) {
7926 if (userId == mOwners.getDeviceOwnerUserId()
7927 && packageName.equals(mOwners.getDeviceOwnerPackageName())) {
7935 public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
7936 Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
7937 intent.putExtra(Intent.EXTRA_USER_ID, userId);
7938 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7939 synchronized (DevicePolicyManagerService.this) {
7940 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
7941 if (profileOwner != null) {
7942 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
7946 if (mOwners.getDeviceOwnerUserId() == userId) {
7947 ComponentName deviceOwner = mOwners.getDeviceOwnerComponent();
7948 if (deviceOwner != null) {
7949 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner);
7959 * Returns true if specified admin is allowed to limit passwords and has a
7960 * {@code passwordQuality} of at least {@code minPasswordQuality}
7962 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
7963 if (admin.passwordQuality < minPasswordQuality) {
7966 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
7970 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
7971 if (policy != null && !policy.isValid()) {
7972 throw new IllegalArgumentException("Invalid system update policy.");
7974 synchronized (this) {
7975 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7976 if (policy == null) {
7977 mOwners.clearSystemUpdatePolicy();
7979 mOwners.setSystemUpdatePolicy(policy);
7981 mOwners.writeDeviceOwner();
7983 mContext.sendBroadcastAsUser(
7984 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
7989 public SystemUpdatePolicy getSystemUpdatePolicy() {
7990 synchronized (this) {
7991 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
7992 if (policy != null && !policy.isValid()) {
7993 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8001 * Checks if the caller of the method is the device owner app.
8003 * @param callerUid UID of the caller.
8004 * @return true if the caller is the device owner app
8007 boolean isCallerDeviceOwner(int callerUid) {
8008 synchronized (this) {
8009 if (!mOwners.hasDeviceOwner()) {
8012 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8015 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8017 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8019 for (String pkg : pkgs) {
8020 if (deviceOwnerPackageName.equals(pkg)) {
8030 public void notifyPendingSystemUpdate(long updateReceivedTime) {
8031 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8032 "Only the system update service can broadcast update information");
8034 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8035 Slog.w(LOG_TAG, "Only the system update service in the system user " +
8036 "can broadcast update information.");
8039 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8040 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8041 updateReceivedTime);
8043 synchronized (this) {
8044 final String deviceOwnerPackage =
8045 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8047 if (deviceOwnerPackage == null) {
8050 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8052 ActivityInfo[] receivers = null;
8054 receivers = mContext.getPackageManager().getPackageInfo(
8055 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8056 } catch (NameNotFoundException e) {
8057 Log.e(LOG_TAG, "Cannot find device owner package", e);
8059 if (receivers != null) {
8060 long ident = mInjector.binderClearCallingIdentity();
8062 for (int i = 0; i < receivers.length; i++) {
8063 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8064 intent.setComponent(new ComponentName(deviceOwnerPackage,
8065 receivers[i].name));
8066 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8070 mInjector.binderRestoreCallingIdentity(ident);
8077 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8078 int userId = UserHandle.getCallingUserId();
8079 synchronized (this) {
8080 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8081 DevicePolicyData userPolicy = getUserData(userId);
8082 if (userPolicy.mPermissionPolicy != policy) {
8083 userPolicy.mPermissionPolicy = policy;
8084 saveSettingsLocked(userId);
8090 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8091 int userId = UserHandle.getCallingUserId();
8092 synchronized (this) {
8093 DevicePolicyData userPolicy = getUserData(userId);
8094 return userPolicy.mPermissionPolicy;
8099 public boolean setPermissionGrantState(ComponentName admin, String packageName,
8100 String permission, int grantState) throws RemoteException {
8101 UserHandle user = mInjector.binderGetCallingUserHandle();
8102 synchronized (this) {
8103 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8104 long ident = mInjector.binderClearCallingIdentity();
8106 if (getTargetSdk(packageName, user.getIdentifier())
8107 < android.os.Build.VERSION_CODES.M) {
8110 final PackageManager packageManager = mContext.getPackageManager();
8111 switch (grantState) {
8112 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8113 packageManager.grantRuntimePermission(packageName, permission, user);
8114 packageManager.updatePermissionFlags(permission, packageName,
8115 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8116 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8119 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8120 packageManager.revokeRuntimePermission(packageName,
8122 packageManager.updatePermissionFlags(permission, packageName,
8123 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8124 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8127 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8128 packageManager.updatePermissionFlags(permission, packageName,
8129 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8133 } catch (SecurityException se) {
8136 mInjector.binderRestoreCallingIdentity(ident);
8142 public int getPermissionGrantState(ComponentName admin, String packageName,
8143 String permission) throws RemoteException {
8144 PackageManager packageManager = mContext.getPackageManager();
8146 UserHandle user = mInjector.binderGetCallingUserHandle();
8147 synchronized (this) {
8148 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8149 long ident = mInjector.binderClearCallingIdentity();
8151 int granted = mIPackageManager.checkPermission(permission,
8152 packageName, user.getIdentifier());
8153 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8154 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8155 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8156 // Not controlled by policy
8157 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8159 // Policy controlled so return result based on permission grant state
8160 return granted == PackageManager.PERMISSION_GRANTED
8161 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8162 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8165 mInjector.binderRestoreCallingIdentity(ident);
8170 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8172 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8174 return (pi != null) && (pi.applicationInfo.flags != 0);
8175 } catch (RemoteException re) {
8176 throw new RuntimeException("Package manager has died", re);
8181 public boolean isProvisioningAllowed(String action) {
8186 final int callingUserId = mInjector.userHandleGetCallingUserId();
8187 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8188 if (!hasFeatureManagedUsers()) {
8191 synchronized (this) {
8192 if (mOwners.hasDeviceOwner()) {
8193 if (!mInjector.userManagerIsSplitSystemUser()) {
8194 // Only split-system-user systems support managed-profiles in combination with
8198 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8199 // Only system device-owner supports managed-profiles. Non-system device-owner
8203 if (callingUserId == UserHandle.USER_SYSTEM) {
8204 // Managed-profiles cannot be setup on the system user, only regular users.
8209 if (getProfileOwner(callingUserId) != null) {
8210 // Managed user cannot have a managed profile.
8213 final long ident = mInjector.binderClearCallingIdentity();
8215 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8219 mInjector.binderRestoreCallingIdentity(ident);
8222 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8223 return isDeviceOwnerProvisioningAllowed(callingUserId);
8224 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8225 if (!hasFeatureManagedUsers()) {
8228 if (!mInjector.userManagerIsSplitSystemUser()) {
8229 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8232 if (callingUserId == UserHandle.USER_SYSTEM) {
8233 // System user cannot be a managed user.
8236 if (hasUserSetupCompleted(callingUserId)) {
8240 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8241 if (!mInjector.userManagerIsSplitSystemUser()) {
8242 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8245 return isDeviceOwnerProvisioningAllowed(callingUserId);
8247 throw new IllegalArgumentException("Unknown provisioning action " + action);
8251 * The device owner can only be set before the setup phase of the primary user has completed,
8252 * except for adb command if no accounts or additional users are present on the device.
8254 private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreCondition(
8255 int deviceOwnerUserId, boolean isAdb) {
8256 if (mOwners.hasDeviceOwner()) {
8257 return CODE_HAS_DEVICE_OWNER;
8259 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8260 return CODE_USER_HAS_PROFILE_OWNER;
8262 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8263 return CODE_USER_NOT_RUNNING;
8266 // if shell command runs after user setup completed check device status. Otherwise, OK.
8267 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8268 if (!mInjector.userManagerIsSplitSystemUser()) {
8269 if (mUserManager.getUserCount() > 1) {
8270 return CODE_NONSYSTEM_USER_EXISTS;
8272 if (AccountManager.get(mContext).getAccounts().length > 0) {
8273 return CODE_ACCOUNTS_NOT_EMPTY;
8276 // STOPSHIP Do proper check in split user mode
8281 if (!mInjector.userManagerIsSplitSystemUser()) {
8282 // In non-split user mode, DO has to be user 0
8283 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8284 return CODE_NOT_SYSTEM_USER;
8286 // In non-split user mode, only provision DO before setup wizard completes
8287 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8288 return CODE_USER_SETUP_COMPLETED;
8291 // STOPSHIP Do proper check in split user mode
8297 private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8298 return CODE_OK == checkSetDeviceOwnerPreCondition(deviceOwnerUserId, /* isAdb */ false);
8301 private boolean hasFeatureManagedUsers() {
8303 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8304 } catch (RemoteException e) {
8310 public String getWifiMacAddress(ComponentName admin) {
8311 // Make sure caller has DO.
8312 synchronized (this) {
8313 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8316 final long ident = mInjector.binderClearCallingIdentity();
8318 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8319 if (wifiInfo == null) {
8322 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8324 mInjector.binderRestoreCallingIdentity(ident);
8329 * Returns the target sdk version number that the given packageName was built for
8330 * in the given user.
8332 private int getTargetSdk(String packageName, int userId) {
8333 final ApplicationInfo ai;
8335 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8336 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8337 return targetSdkVersion;
8338 } catch (RemoteException e) {
8345 public boolean isManagedProfile(ComponentName admin) {
8346 synchronized (this) {
8347 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8349 final int callingUserId = mInjector.userHandleGetCallingUserId();
8350 final UserInfo user = getUserInfo(callingUserId);
8351 return user != null && user.isManagedProfile();
8355 public boolean isSystemOnlyUser(ComponentName admin) {
8356 synchronized (this) {
8357 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8359 final int callingUserId = mInjector.userHandleGetCallingUserId();
8360 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8364 public void reboot(ComponentName admin) {
8365 Preconditions.checkNotNull(admin);
8366 // Make sure caller has DO.
8367 synchronized (this) {
8368 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8370 long ident = mInjector.binderClearCallingIdentity();
8372 // Make sure there are no ongoing calls on the device.
8373 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8374 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8376 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8378 mInjector.binderRestoreCallingIdentity(ident);
8383 public void setShortSupportMessage(@NonNull ComponentName who, String message) {
8387 Preconditions.checkNotNull(who, "ComponentName is null");
8388 final int userHandle = mInjector.userHandleGetCallingUserId();
8389 synchronized (this) {
8390 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8391 mInjector.binderGetCallingUid());
8392 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8393 admin.shortSupportMessage = message;
8394 saveSettingsLocked(userHandle);
8400 public String getShortSupportMessage(@NonNull ComponentName who) {
8404 Preconditions.checkNotNull(who, "ComponentName is null");
8405 synchronized (this) {
8406 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8407 mInjector.binderGetCallingUid());
8408 return admin.shortSupportMessage;
8413 public void setLongSupportMessage(@NonNull ComponentName who, String message) {
8417 Preconditions.checkNotNull(who, "ComponentName is null");
8418 final int userHandle = mInjector.userHandleGetCallingUserId();
8419 synchronized (this) {
8420 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8421 mInjector.binderGetCallingUid());
8422 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8423 admin.longSupportMessage = message;
8424 saveSettingsLocked(userHandle);
8430 public String getLongSupportMessage(@NonNull ComponentName who) {
8434 Preconditions.checkNotNull(who, "ComponentName is null");
8435 synchronized (this) {
8436 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8437 mInjector.binderGetCallingUid());
8438 return admin.longSupportMessage;
8443 public String getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8447 Preconditions.checkNotNull(who, "ComponentName is null");
8448 if (!isCallerWithSystemUid()) {
8449 throw new SecurityException("Only the system can query support message for user");
8451 synchronized (this) {
8452 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8453 if (admin != null) {
8454 return admin.shortSupportMessage;
8461 public String getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8465 Preconditions.checkNotNull(who, "ComponentName is null");
8466 if (!isCallerWithSystemUid()) {
8467 throw new SecurityException("Only the system can query support message for user");
8469 synchronized (this) {
8470 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8471 if (admin != null) {
8472 return admin.longSupportMessage;
8479 public void setOrganizationColor(@NonNull ComponentName who, int color) {
8483 Preconditions.checkNotNull(who, "ComponentName is null");
8484 final int userHandle = mInjector.userHandleGetCallingUserId();
8485 enforceManagedProfile(userHandle, "set organization color");
8486 synchronized (this) {
8487 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8488 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8489 admin.organizationColor = color;
8490 saveSettingsLocked(userHandle);
8495 public void setOrganizationColorForUser(int color, int userId) {
8499 enforceFullCrossUsersPermission(userId);
8500 enforceManageUsers();
8501 enforceManagedProfile(userId, "set organization color");
8502 synchronized (this) {
8503 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8504 admin.organizationColor = color;
8505 saveSettingsLocked(userId);
8510 public int getOrganizationColor(@NonNull ComponentName who) {
8512 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8514 Preconditions.checkNotNull(who, "ComponentName is null");
8515 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
8516 synchronized (this) {
8517 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8518 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8519 return admin.organizationColor;
8524 public int getOrganizationColorForUser(int userHandle) {
8526 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8528 enforceFullCrossUsersPermission(userHandle);
8529 enforceManagedProfile(userHandle, "get organization color");
8530 synchronized (this) {
8531 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8532 return (profileOwner != null)
8533 ? profileOwner.organizationColor
8534 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
8539 public void setOrganizationName(@NonNull ComponentName who, String text) {
8543 Preconditions.checkNotNull(who, "ComponentName is null");
8544 final int userHandle = mInjector.userHandleGetCallingUserId();
8545 enforceManagedProfile(userHandle, "set organization name");
8546 synchronized (this) {
8547 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8548 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8549 if (!TextUtils.equals(admin.organizationName, text)) {
8550 admin.organizationName = TextUtils.nullIfEmpty(text);
8551 saveSettingsLocked(userHandle);
8557 public String getOrganizationName(@NonNull ComponentName who) {
8561 Preconditions.checkNotNull(who, "ComponentName is null");
8562 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
8563 synchronized(this) {
8564 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8565 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8566 return admin.organizationName;
8571 public String getOrganizationNameForUser(int userHandle) {
8575 enforceFullCrossUsersPermission(userHandle);
8576 enforceManagedProfile(userHandle, "get organization name");
8577 synchronized (this) {
8578 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8579 return (profileOwner != null)
8580 ? profileOwner.organizationName
8586 public void setAffiliationIds(ComponentName admin, List<String> ids) {
8587 final Set<String> affiliationIds = new ArraySet<String>(ids);
8588 final int callingUserId = mInjector.userHandleGetCallingUserId();
8590 synchronized (this) {
8591 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8592 getUserData(callingUserId).mAffiliationIds = affiliationIds;
8593 saveSettingsLocked(callingUserId);
8594 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
8595 // Affiliation ids specified by the device owner are additionally stored in
8596 // UserHandle.USER_SYSTEM's DevicePolicyData.
8597 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
8598 saveSettingsLocked(UserHandle.USER_SYSTEM);
8604 public boolean isAffiliatedUser() {
8605 final int callingUserId = mInjector.userHandleGetCallingUserId();
8607 synchronized (this) {
8608 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
8609 // The user that the DO is installed on is always affiliated.
8612 final ComponentName profileOwner = getProfileOwner(callingUserId);
8613 if (profileOwner == null
8614 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
8617 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
8618 final Set<String> deviceAffiliationIds =
8619 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
8620 for (String id : userAffiliationIds) {
8621 if (deviceAffiliationIds.contains(id)) {
8629 private synchronized void disableSecurityLoggingIfNotCompliant() {
8630 if (!isDeviceOwnerManagedSingleUserDevice()) {
8631 mInjector.securityLogSetLoggingEnabledProperty(false);
8632 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user device.");
8637 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
8638 Preconditions.checkNotNull(admin);
8639 ensureDeviceOwnerManagingSingleUser(admin);
8641 synchronized (this) {
8642 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
8645 mInjector.securityLogSetLoggingEnabledProperty(enabled);
8647 mSecurityLogMonitor.start();
8649 mSecurityLogMonitor.stop();
8655 public boolean isSecurityLoggingEnabled(ComponentName admin) {
8656 Preconditions.checkNotNull(admin);
8657 synchronized (this) {
8658 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8659 return mInjector.securityLogGetLoggingEnabledProperty();
8664 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
8665 Preconditions.checkNotNull(admin);
8666 ensureDeviceOwnerManagingSingleUser(admin);
8668 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
8670 SecurityLog.readPreviousEvents(output);
8671 return new ParceledListSlice<SecurityEvent>(output);
8672 } catch (IOException e) {
8673 Slog.w(LOG_TAG, "Fail to read previous events" , e);
8674 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
8679 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
8680 Preconditions.checkNotNull(admin);
8681 ensureDeviceOwnerManagingSingleUser(admin);
8683 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
8684 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
8687 private void enforceCanManageDeviceAdmin() {
8688 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
8693 public boolean isUninstallInQueue(final String packageName) {
8694 enforceCanManageDeviceAdmin();
8695 final int userId = mInjector.userHandleGetCallingUserId();
8696 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8697 synchronized (this) {
8698 return mPackagesToRemove.contains(packageUserPair);
8703 public void uninstallPackageWithActiveAdmins(final String packageName) {
8704 enforceCanManageDeviceAdmin();
8705 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
8707 final int userId = mInjector.userHandleGetCallingUserId();
8709 enforceUserUnlocked(userId);
8711 final ComponentName profileOwner = getProfileOwner(userId);
8712 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
8713 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
8716 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
8717 if (getDeviceOwnerUserId() == userId && deviceOwner != null
8718 && packageName.equals(deviceOwner.getPackageName())) {
8719 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
8722 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8723 synchronized (this) {
8724 mPackagesToRemove.add(packageUserPair);
8727 // All active admins on the user.
8728 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
8730 // Active admins in the target package.
8731 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
8732 if (allActiveAdmins != null) {
8733 for (ComponentName activeAdmin : allActiveAdmins) {
8734 if (packageName.equals(activeAdmin.getPackageName())) {
8735 packageActiveAdmins.add(activeAdmin);
8736 removeActiveAdmin(activeAdmin, userId);
8740 if (packageActiveAdmins.size() == 0) {
8741 startUninstallIntent(packageName, userId);
8743 mHandler.postDelayed(new Runnable() {
8746 for (ComponentName activeAdmin : packageActiveAdmins) {
8747 removeAdminArtifacts(activeAdmin, userId);
8749 startUninstallIntent(packageName, userId);
8751 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
8755 private void removePackageIfRequired(final String packageName, final int userId) {
8756 if (!packageHasActiveAdmins(packageName, userId)) {
8757 // Will not do anything if uninstall was not requested or was already started.
8758 startUninstallIntent(packageName, userId);
8762 private void startUninstallIntent(final String packageName, final int userId) {
8763 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
8764 synchronized (this) {
8765 if (!mPackagesToRemove.contains(packageUserPair)) {
8766 // Do nothing if uninstall was not requested or was already started.
8769 mPackagesToRemove.remove(packageUserPair);
8772 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
8773 // Package does not exist. Nothing to do.
8776 } catch (RemoteException re) {
8777 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
8780 try { // force stop the package before uninstalling
8781 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
8782 } catch (RemoteException re) {
8783 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
8785 final Uri packageURI = Uri.parse("package:" + packageName);
8786 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
8787 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8788 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
8792 * Removes the admin from the policy. Ideally called after the admin's
8793 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
8795 * @param adminReceiver The admin to remove
8796 * @param userHandle The user for which this admin has to be removed.
8798 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
8799 synchronized (this) {
8800 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
8801 if (admin == null) {
8804 final DevicePolicyData policy = getUserData(userHandle);
8805 final boolean doProxyCleanup = admin.info.usesPolicy(
8806 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
8807 policy.mAdminList.remove(admin);
8808 policy.mAdminMap.remove(adminReceiver);
8809 validatePasswordOwnerLocked(policy);
8810 if (doProxyCleanup) {
8811 resetGlobalProxyLocked(policy);
8813 saveSettingsLocked(userHandle);
8814 updateMaximumTimeToLockLocked(userHandle);
8815 policy.mRemovingAdmins.remove(adminReceiver);
8817 // The removed admin might have disabled camera, so update user
8819 pushUserRestrictions(userHandle);