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.ACTION_SHOW_DEVICE_MONITORING_DIALOG;
21 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
22 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
23 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
24 import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
26 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
27 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
28 import static org.xmlpull.v1.XmlPullParser.END_TAG;
29 import static org.xmlpull.v1.XmlPullParser.TEXT;
31 import android.Manifest.permission;
32 import android.accessibilityservice.AccessibilityServiceInfo;
33 import android.accounts.Account;
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.ActivityManagerInternal;
42 import android.app.ActivityManagerNative;
43 import android.app.AlarmManager;
44 import android.app.AppGlobals;
45 import android.app.IActivityManager;
46 import android.app.Notification;
47 import android.app.NotificationManager;
48 import android.app.PendingIntent;
49 import android.app.StatusBarManager;
50 import android.app.admin.DeviceAdminInfo;
51 import android.app.admin.DeviceAdminReceiver;
52 import android.app.admin.DevicePolicyManager;
53 import android.app.admin.DevicePolicyManagerInternal;
54 import android.app.admin.IDevicePolicyManager;
55 import android.app.admin.NetworkEvent;
56 import android.app.admin.SecurityLog;
57 import android.app.admin.SecurityLog.SecurityEvent;
58 import android.app.admin.SystemUpdatePolicy;
59 import android.app.backup.IBackupManager;
60 import android.app.trust.TrustManager;
61 import android.content.BroadcastReceiver;
62 import android.content.ComponentName;
63 import android.content.Context;
64 import android.content.Intent;
65 import android.content.IntentFilter;
66 import android.content.pm.ActivityInfo;
67 import android.content.pm.ApplicationInfo;
68 import android.content.pm.IPackageManager;
69 import android.content.pm.PackageInfo;
70 import android.content.pm.PackageManager;
71 import android.content.pm.PackageManager.NameNotFoundException;
72 import android.content.pm.PackageManagerInternal;
73 import android.content.pm.ParceledListSlice;
74 import android.content.pm.PermissionInfo;
75 import android.content.pm.ResolveInfo;
76 import android.content.pm.ServiceInfo;
77 import android.content.pm.UserInfo;
78 import android.database.ContentObserver;
79 import android.graphics.Bitmap;
80 import android.graphics.Color;
81 import android.media.AudioManager;
82 import android.media.IAudioService;
83 import android.net.ConnectivityManager;
84 import android.net.IIpConnectivityMetrics;
85 import android.net.ProxyInfo;
86 import android.net.Uri;
87 import android.net.metrics.IpConnectivityLog;
88 import android.net.wifi.WifiInfo;
89 import android.net.wifi.WifiManager;
90 import android.os.AsyncTask;
91 import android.os.Binder;
92 import android.os.Build;
93 import android.os.Bundle;
94 import android.os.Environment;
95 import android.os.FileUtils;
96 import android.os.Handler;
97 import android.os.IBinder;
98 import android.os.Looper;
99 import android.os.ParcelFileDescriptor;
100 import android.os.PersistableBundle;
101 import android.os.PowerManager;
102 import android.os.PowerManagerInternal;
103 import android.os.Process;
104 import android.os.RecoverySystem;
105 import android.os.RemoteCallback;
106 import android.os.RemoteException;
107 import android.os.ServiceManager;
108 import android.os.SystemClock;
109 import android.os.SystemProperties;
110 import android.os.UserHandle;
111 import android.os.UserManager;
112 import android.os.UserManagerInternal;
113 import android.os.storage.StorageManager;
114 import android.provider.ContactsContract.QuickContact;
115 import android.provider.ContactsInternal;
116 import android.provider.Settings;
117 import android.security.Credentials;
118 import android.security.IKeyChainAliasCallback;
119 import android.security.IKeyChainService;
120 import android.security.KeyChain;
121 import android.security.KeyChain.KeyChainConnection;
122 import android.service.persistentdata.PersistentDataBlockManager;
123 import android.telephony.TelephonyManager;
124 import android.text.TextUtils;
125 import android.util.ArrayMap;
126 import android.util.ArraySet;
127 import android.util.EventLog;
128 import android.util.Log;
129 import android.util.Pair;
130 import android.util.Slog;
131 import android.util.SparseArray;
132 import android.util.Xml;
133 import android.view.IWindowManager;
134 import android.view.accessibility.AccessibilityManager;
135 import android.view.accessibility.IAccessibilityManager;
136 import android.view.inputmethod.InputMethodInfo;
137 import android.view.inputmethod.InputMethodManager;
139 import com.android.internal.R;
140 import com.android.internal.annotations.VisibleForTesting;
141 import com.android.internal.statusbar.IStatusBarService;
142 import com.android.internal.util.FastXmlSerializer;
143 import com.android.internal.util.JournaledFile;
144 import com.android.internal.util.ParcelableString;
145 import com.android.internal.util.Preconditions;
146 import com.android.internal.util.XmlUtils;
147 import com.android.internal.widget.LockPatternUtils;
148 import com.android.server.LocalServices;
149 import com.android.server.SystemService;
150 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
151 import com.android.server.pm.UserRestrictionsUtils;
152 import com.google.android.collect.Sets;
154 import org.xmlpull.v1.XmlPullParser;
155 import org.xmlpull.v1.XmlPullParserException;
156 import org.xmlpull.v1.XmlSerializer;
158 import java.io.ByteArrayInputStream;
160 import java.io.FileDescriptor;
161 import java.io.FileInputStream;
162 import java.io.FileNotFoundException;
163 import java.io.FileOutputStream;
164 import java.io.IOException;
165 import java.io.PrintWriter;
166 import java.lang.annotation.Retention;
167 import java.lang.annotation.RetentionPolicy;
168 import java.nio.charset.StandardCharsets;
169 import java.security.cert.CertificateException;
170 import java.security.cert.CertificateFactory;
171 import java.security.cert.X509Certificate;
172 import java.text.DateFormat;
173 import java.util.ArrayList;
174 import java.util.Arrays;
175 import java.util.Collections;
176 import java.util.Date;
177 import java.util.List;
178 import java.util.Map.Entry;
179 import java.util.Set;
180 import java.util.concurrent.atomic.AtomicBoolean;
183 * Implementation of the device policy APIs.
185 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
187 private static final String LOG_TAG = "DevicePolicyManagerService";
189 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
191 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
193 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
195 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
197 private static final String TAG_STATUS_BAR = "statusbar";
199 private static final String ATTR_DISABLED = "disabled";
201 private static final String ATTR_NAME = "name";
203 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
204 "do-not-ask-credentials-on-boot";
206 private static final String TAG_AFFILIATION_ID = "affiliation-id";
208 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
210 private static final String ATTR_VALUE = "value";
212 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
214 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
216 private static final long MS_PER_DAY = 86400 * 1000;
218 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
220 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
221 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
223 private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
224 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
225 private static final int NETWORK_LOGGING_NOTIFICATION_ID = 1002;
227 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
228 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
229 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
230 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
231 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
232 "device-provisioning-config-applied";
233 private static final String ATTR_DEVICE_PAIRED = "device-paired";
235 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
236 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
237 = "application-restrictions-manager";
240 * System property whose value is either "true" or "false", indicating whether
242 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
244 private static final int STATUS_BAR_DISABLE_MASK =
245 StatusBarManager.DISABLE_EXPAND |
246 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
247 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
248 StatusBarManager.DISABLE_SEARCH;
250 private static final int STATUS_BAR_DISABLE2_MASK =
251 StatusBarManager.DISABLE2_QUICK_SETTINGS;
253 private static final Set<String> SECURE_SETTINGS_WHITELIST;
254 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
255 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
256 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
258 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
259 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
260 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
261 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
263 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
264 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
265 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
267 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
268 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
269 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
270 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
271 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
272 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
273 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
274 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
275 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
277 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
278 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
279 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
280 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
281 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
282 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
286 * Keyguard features that when set on a managed profile that doesn't have its own challenge will
287 * affect the profile's parent user. These can also be set on the managed profile's parent DPM
290 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
291 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
292 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
295 * Keyguard features that when set on a profile affect the profile content or challenge only.
296 * These cannot be set on the managed profile's parent DPM instance
298 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
299 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
301 /** Keyguard features that are allowed to be set on a managed profile */
302 private static final int PROFILE_KEYGUARD_FEATURES =
303 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
305 private static final int CODE_OK = 0;
306 private static final int CODE_HAS_DEVICE_OWNER = 1;
307 private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
308 private static final int CODE_USER_NOT_RUNNING = 3;
309 private static final int CODE_USER_SETUP_COMPLETED = 4;
310 private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
311 private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
312 private static final int CODE_NOT_SYSTEM_USER = 7;
313 private static final int CODE_HAS_PAIRED = 8;
315 @Retention(RetentionPolicy.SOURCE)
316 @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
317 CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
318 private @interface DeviceOwnerPreConditionCode {}
320 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
323 * Minimum timeout in milliseconds after which unlocking with weak auth times out,
324 * i.e. the user has to use a strong authentication method like password, PIN or pattern.
326 private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
328 final Context mContext;
329 final Injector mInjector;
330 final IPackageManager mIPackageManager;
331 final UserManager mUserManager;
332 final UserManagerInternal mUserManagerInternal;
333 final TelephonyManager mTelephonyManager;
334 private final LockPatternUtils mLockPatternUtils;
337 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
338 * is requested for user u.
340 private final Set<Pair<String, Integer>> mPackagesToRemove =
341 new ArraySet<Pair<String, Integer>>();
343 final LocalService mLocalService;
345 // Stores and loads state on device and profile owners.
347 final Owners mOwners;
349 private final Binder mToken = new Binder();
352 * Whether or not device admin feature is supported. If it isn't return defaults for all
358 * Whether or not this device is a watch.
362 private final SecurityLogMonitor mSecurityLogMonitor;
363 private NetworkLogger mNetworkLogger;
365 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
366 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
368 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
371 if(mRemoteBugreportServiceIsActive.get()) {
377 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
380 public void onReceive(Context context, Intent intent) {
381 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
382 && mRemoteBugreportServiceIsActive.get()) {
383 onBugreportFinished(intent);
388 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
391 public void onReceive(Context context, Intent intent) {
392 String action = intent.getAction();
393 mInjector.getNotificationManager().cancel(LOG_TAG,
394 RemoteBugreportUtils.NOTIFICATION_ID);
395 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
396 onBugreportSharingAccepted();
397 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
398 onBugreportSharingDeclined();
400 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
404 public static final class Lifecycle extends SystemService {
405 private DevicePolicyManagerService mService;
407 public Lifecycle(Context context) {
409 mService = new DevicePolicyManagerService(context);
413 public void onStart() {
414 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
418 public void onBootPhase(int phase) {
419 mService.systemReady(phase);
423 public void onStartUser(int userHandle) {
424 mService.onStartUser(userHandle);
428 public static class DevicePolicyData {
429 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
430 int mActivePasswordLength = 0;
431 int mActivePasswordUpperCase = 0;
432 int mActivePasswordLowerCase = 0;
433 int mActivePasswordLetters = 0;
434 int mActivePasswordNumeric = 0;
435 int mActivePasswordSymbols = 0;
436 int mActivePasswordNonLetter = 0;
437 int mFailedPasswordAttempts = 0;
440 int mPasswordOwner = -1;
441 long mLastMaximumTimeToLock = -1;
442 boolean mUserSetupComplete = false;
443 boolean mPaired = false;
444 int mUserProvisioningState;
445 int mPermissionPolicy;
447 boolean mDeviceProvisioningConfigApplied = false;
449 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
450 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
451 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
453 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
455 // This is the list of component allowed to start lock task mode.
456 List<String> mLockTaskPackages = new ArrayList<>();
458 boolean mStatusBarDisabled = false;
460 ComponentName mRestrictionsProvider;
462 String mDelegatedCertInstallerPackage;
464 boolean doNotAskCredentialsOnBoot = false;
466 String mApplicationRestrictionsManagingPackage;
468 Set<String> mAffiliationIds = new ArraySet<>();
470 // Used for initialization of users created by createAndManageUsers.
471 boolean mAdminBroadcastPending = false;
472 PersistableBundle mInitBundle = null;
474 public DevicePolicyData(int userHandle) {
475 mUserHandle = userHandle;
479 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
481 final Handler mHandler;
483 BroadcastReceiver mReceiver = new BroadcastReceiver() {
485 public void onReceive(Context context, Intent intent) {
486 final String action = intent.getAction();
487 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
491 * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
492 * however it's too early in the boot process to register with IIpConnectivityMetrics
493 * to listen for events.
495 if (Intent.ACTION_USER_STARTED.equals(action)
496 && userHandle == mOwners.getDeviceOwnerUserId()) {
497 synchronized (DevicePolicyManagerService.this) {
498 if (isNetworkLoggingEnabledInternalLocked()) {
499 setNetworkLoggingActiveInternal(true);
503 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
504 && userHandle == mOwners.getDeviceOwnerUserId()
505 && getDeviceOwnerRemoteBugreportUri() != null) {
506 IntentFilter filterConsent = new IntentFilter();
507 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
508 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
509 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
510 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
511 RemoteBugreportUtils.NOTIFICATION_ID,
512 RemoteBugreportUtils.buildNotification(mContext,
513 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
516 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
517 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
519 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
520 + action + " for user " + userHandle);
522 mHandler.post(new Runnable() {
525 handlePasswordExpirationNotification(userHandle);
529 if (Intent.ACTION_USER_UNLOCKED.equals(action)
530 || Intent.ACTION_USER_STARTED.equals(action)
531 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
532 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
533 new MonitoringCertNotificationTask().execute(userId);
535 if (Intent.ACTION_USER_ADDED.equals(action)) {
536 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
537 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
538 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
539 removeUserData(userHandle);
540 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
541 synchronized (DevicePolicyManagerService.this) {
542 // Reset the policy data
543 mUserData.remove(userHandle);
544 sendAdminEnabledBroadcastLocked(userHandle);
546 handlePackagesChanged(null /* check all admins */, userHandle);
547 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
548 handlePackagesChanged(null /* check all admins */, userHandle);
549 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
550 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
551 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
552 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
553 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
554 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
555 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
556 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
557 clearWipeProfileNotification();
562 static class ActiveAdmin {
563 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
564 private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
565 private static final String TAG_DISABLE_CAMERA = "disable-camera";
566 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
567 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
568 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
569 = "disable-bt-contacts-sharing";
570 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
571 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
572 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
573 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
574 private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled";
575 private static final String TAG_ACCOUNT_TYPE = "account-type";
576 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
577 = "permitted-accessiblity-services";
578 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
579 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
580 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
581 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
582 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
583 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
584 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
585 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
586 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
587 private static final String TAG_PERMITTED_IMES = "permitted-imes";
588 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
589 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
590 private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
591 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
592 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
593 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
594 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
595 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
596 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
597 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
598 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
599 private static final String ATTR_VALUE = "value";
600 private static final String TAG_PASSWORD_QUALITY = "password-quality";
601 private static final String TAG_POLICIES = "policies";
602 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
603 "cross-profile-widget-providers";
604 private static final String TAG_PROVIDER = "provider";
605 private static final String TAG_PACKAGE_LIST_ITEM = "item";
606 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
607 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
608 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
609 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
610 private static final String TAG_PARENT_ADMIN = "parent-admin";
611 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
612 private static final String TAG_ORGANIZATION_NAME = "organization-name";
613 private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification";
614 private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications";
616 final DeviceAdminInfo info;
618 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
620 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
621 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
623 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
624 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
626 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
627 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
629 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
630 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
632 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
633 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
635 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
636 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
638 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
639 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
641 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
642 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
644 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
645 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
647 long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
649 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
650 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
652 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
653 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
655 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
656 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
658 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
660 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
662 boolean encryptionRequested = false;
663 boolean testOnlyAdmin = false;
664 boolean disableCamera = false;
665 boolean disableCallerId = false;
666 boolean disableContactsSearch = false;
667 boolean disableBluetoothContactSharing = true;
668 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
669 boolean requireAutoTime = false; // Can only be set by a device owner.
670 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
671 boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner.
673 // one notification after enabling + 3 more after reboots
674 static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 4;
675 int numNetworkLoggingNotifications = 0;
676 long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch
678 ActiveAdmin parentAdmin;
679 final boolean isParent;
681 static class TrustAgentInfo {
682 public PersistableBundle options;
683 TrustAgentInfo(PersistableBundle bundle) {
688 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
690 // The list of permitted accessibility services package namesas set by a profile
691 // or device owner. Null means all accessibility services are allowed, empty means
692 // none except system services are allowed.
693 List<String> permittedAccessiblityServices;
695 // The list of permitted input methods package names as set by a profile or device owner.
696 // Null means all input methods are allowed, empty means none except system imes are
698 List<String> permittedInputMethods;
700 // List of package names to keep cached.
701 List<String> keepUninstalledPackages;
703 // TODO: review implementation decisions with frameworks team
704 boolean specifiesGlobalProxy = false;
705 String globalProxySpec = null;
706 String globalProxyExclusionList = null;
708 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
710 List<String> crossProfileWidgetProviders;
712 Bundle userRestrictions;
714 // Support text provided by the admin to display to the user.
715 CharSequence shortSupportMessage = null;
716 CharSequence longSupportMessage = null;
718 // Background color of confirm credentials screen. Default: teal.
719 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
720 int organizationColor = DEF_ORGANIZATION_COLOR;
722 // Default title of confirm credentials screen
723 String organizationName = null;
725 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
730 ActiveAdmin getParentActiveAdmin() {
731 Preconditions.checkState(!isParent);
733 if (parentAdmin == null) {
734 parentAdmin = new ActiveAdmin(info, /* parent */ true);
739 boolean hasParentActiveAdmin() {
740 return parentAdmin != null;
743 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
745 public UserHandle getUserHandle() {
746 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
749 void writeToXml(XmlSerializer out)
750 throws IllegalArgumentException, IllegalStateException, IOException {
751 out.startTag(null, TAG_POLICIES);
752 info.writePoliciesToXml(out);
753 out.endTag(null, TAG_POLICIES);
754 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
755 out.startTag(null, TAG_PASSWORD_QUALITY);
756 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
757 out.endTag(null, TAG_PASSWORD_QUALITY);
758 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
759 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
760 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
761 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
763 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
764 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
765 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
766 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
768 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
769 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
770 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
771 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
773 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
774 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
775 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
776 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
778 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
779 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
780 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
781 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
783 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
784 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
785 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
786 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
788 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
789 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
790 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
791 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
793 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
794 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
795 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
796 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
799 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
800 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
801 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
802 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
804 if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
805 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
806 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
807 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
809 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
810 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
811 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
812 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
814 if (specifiesGlobalProxy) {
815 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
816 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
817 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
818 if (globalProxySpec != null) {
819 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
820 out.attribute(null, ATTR_VALUE, globalProxySpec);
821 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
823 if (globalProxyExclusionList != null) {
824 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
825 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
826 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
829 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
830 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
831 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
832 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
834 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
835 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
836 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
837 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
839 if (encryptionRequested) {
840 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
841 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
842 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
845 out.startTag(null, TAG_TEST_ONLY_ADMIN);
846 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
847 out.endTag(null, TAG_TEST_ONLY_ADMIN);
850 out.startTag(null, TAG_DISABLE_CAMERA);
851 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
852 out.endTag(null, TAG_DISABLE_CAMERA);
854 if (disableCallerId) {
855 out.startTag(null, TAG_DISABLE_CALLER_ID);
856 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
857 out.endTag(null, TAG_DISABLE_CALLER_ID);
859 if (disableContactsSearch) {
860 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
861 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
862 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
864 if (!disableBluetoothContactSharing) {
865 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
866 out.attribute(null, ATTR_VALUE,
867 Boolean.toString(disableBluetoothContactSharing));
868 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
870 if (disableScreenCapture) {
871 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
872 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
873 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
875 if (requireAutoTime) {
876 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
877 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
878 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
880 if (forceEphemeralUsers) {
881 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
882 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
883 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
885 if (isNetworkLoggingEnabled) {
886 out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
887 out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled));
888 out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS,
889 Integer.toString(numNetworkLoggingNotifications));
890 out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION,
891 Long.toString(lastNetworkLoggingNotificationTimeMs));
892 out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
894 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
895 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
896 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
897 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
899 if (!accountTypesWithManagementDisabled.isEmpty()) {
900 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
901 for (String ac : accountTypesWithManagementDisabled) {
902 out.startTag(null, TAG_ACCOUNT_TYPE);
903 out.attribute(null, ATTR_VALUE, ac);
904 out.endTag(null, TAG_ACCOUNT_TYPE);
906 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
908 if (!trustAgentInfos.isEmpty()) {
909 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
910 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
911 for (Entry<String, TrustAgentInfo> entry : set) {
912 TrustAgentInfo trustAgentInfo = entry.getValue();
913 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
914 out.attribute(null, ATTR_VALUE, entry.getKey());
915 if (trustAgentInfo.options != null) {
916 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
918 trustAgentInfo.options.saveToXml(out);
919 } catch (XmlPullParserException e) {
920 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
922 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
924 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
926 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
928 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
929 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
930 final int providerCount = crossProfileWidgetProviders.size();
931 for (int i = 0; i < providerCount; i++) {
932 String provider = crossProfileWidgetProviders.get(i);
933 out.startTag(null, TAG_PROVIDER);
934 out.attribute(null, ATTR_VALUE, provider);
935 out.endTag(null, TAG_PROVIDER);
937 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
939 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
940 permittedAccessiblityServices);
941 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
942 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
943 if (hasUserRestrictions()) {
944 UserRestrictionsUtils.writeRestrictions(
945 out, userRestrictions, TAG_USER_RESTRICTIONS);
947 if (!TextUtils.isEmpty(shortSupportMessage)) {
948 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
949 out.text(shortSupportMessage.toString());
950 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
952 if (!TextUtils.isEmpty(longSupportMessage)) {
953 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
954 out.text(longSupportMessage.toString());
955 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
957 if (parentAdmin != null) {
958 out.startTag(null, TAG_PARENT_ADMIN);
959 parentAdmin.writeToXml(out);
960 out.endTag(null, TAG_PARENT_ADMIN);
962 if (organizationColor != DEF_ORGANIZATION_COLOR) {
963 out.startTag(null, TAG_ORGANIZATION_COLOR);
964 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
965 out.endTag(null, TAG_ORGANIZATION_COLOR);
967 if (organizationName != null) {
968 out.startTag(null, TAG_ORGANIZATION_NAME);
969 out.text(organizationName);
970 out.endTag(null, TAG_ORGANIZATION_NAME);
974 void writePackageListToXml(XmlSerializer out, String outerTag,
975 List<String> packageList)
976 throws IllegalArgumentException, IllegalStateException, IOException {
977 if (packageList == null) {
981 out.startTag(null, outerTag);
982 for (String packageName : packageList) {
983 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
984 out.attribute(null, ATTR_VALUE, packageName);
985 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
987 out.endTag(null, outerTag);
990 void readFromXml(XmlPullParser parser)
991 throws XmlPullParserException, IOException {
992 int outerDepth = parser.getDepth();
994 while ((type=parser.next()) != END_DOCUMENT
995 && (type != END_TAG || parser.getDepth() > outerDepth)) {
996 if (type == END_TAG || type == TEXT) {
999 String tag = parser.getName();
1000 if (TAG_POLICIES.equals(tag)) {
1001 info.readPoliciesFromXml(parser);
1002 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
1003 passwordQuality = Integer.parseInt(
1004 parser.getAttributeValue(null, ATTR_VALUE));
1005 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
1006 minimumPasswordLength = Integer.parseInt(
1007 parser.getAttributeValue(null, ATTR_VALUE));
1008 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
1009 passwordHistoryLength = Integer.parseInt(
1010 parser.getAttributeValue(null, ATTR_VALUE));
1011 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
1012 minimumPasswordUpperCase = Integer.parseInt(
1013 parser.getAttributeValue(null, ATTR_VALUE));
1014 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
1015 minimumPasswordLowerCase = Integer.parseInt(
1016 parser.getAttributeValue(null, ATTR_VALUE));
1017 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
1018 minimumPasswordLetters = Integer.parseInt(
1019 parser.getAttributeValue(null, ATTR_VALUE));
1020 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
1021 minimumPasswordNumeric = Integer.parseInt(
1022 parser.getAttributeValue(null, ATTR_VALUE));
1023 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
1024 minimumPasswordSymbols = Integer.parseInt(
1025 parser.getAttributeValue(null, ATTR_VALUE));
1026 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
1027 minimumPasswordNonLetter = Integer.parseInt(
1028 parser.getAttributeValue(null, ATTR_VALUE));
1029 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
1030 maximumTimeToUnlock = Long.parseLong(
1031 parser.getAttributeValue(null, ATTR_VALUE));
1032 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
1033 strongAuthUnlockTimeout = Long.parseLong(
1034 parser.getAttributeValue(null, ATTR_VALUE));
1035 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
1036 maximumFailedPasswordsForWipe = Integer.parseInt(
1037 parser.getAttributeValue(null, ATTR_VALUE));
1038 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
1039 specifiesGlobalProxy = Boolean.parseBoolean(
1040 parser.getAttributeValue(null, ATTR_VALUE));
1041 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1043 parser.getAttributeValue(null, ATTR_VALUE);
1044 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1045 globalProxyExclusionList =
1046 parser.getAttributeValue(null, ATTR_VALUE);
1047 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1048 passwordExpirationTimeout = Long.parseLong(
1049 parser.getAttributeValue(null, ATTR_VALUE));
1050 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1051 passwordExpirationDate = Long.parseLong(
1052 parser.getAttributeValue(null, ATTR_VALUE));
1053 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1054 encryptionRequested = Boolean.parseBoolean(
1055 parser.getAttributeValue(null, ATTR_VALUE));
1056 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1057 testOnlyAdmin = Boolean.parseBoolean(
1058 parser.getAttributeValue(null, ATTR_VALUE));
1059 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1060 disableCamera = Boolean.parseBoolean(
1061 parser.getAttributeValue(null, ATTR_VALUE));
1062 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1063 disableCallerId = Boolean.parseBoolean(
1064 parser.getAttributeValue(null, ATTR_VALUE));
1065 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1066 disableContactsSearch = Boolean.parseBoolean(
1067 parser.getAttributeValue(null, ATTR_VALUE));
1068 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1069 disableBluetoothContactSharing = Boolean.parseBoolean(parser
1070 .getAttributeValue(null, ATTR_VALUE));
1071 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1072 disableScreenCapture = Boolean.parseBoolean(
1073 parser.getAttributeValue(null, ATTR_VALUE));
1074 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1075 requireAutoTime = Boolean.parseBoolean(
1076 parser.getAttributeValue(null, ATTR_VALUE));
1077 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1078 forceEphemeralUsers = Boolean.parseBoolean(
1079 parser.getAttributeValue(null, ATTR_VALUE));
1080 } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) {
1081 isNetworkLoggingEnabled = Boolean.parseBoolean(
1082 parser.getAttributeValue(null, ATTR_VALUE));
1083 lastNetworkLoggingNotificationTimeMs = Long.parseLong(
1084 parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION));
1085 numNetworkLoggingNotifications = Integer.parseInt(
1086 parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS));
1087 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1088 disabledKeyguardFeatures = Integer.parseInt(
1089 parser.getAttributeValue(null, ATTR_VALUE));
1090 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1091 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
1092 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1093 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1094 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1095 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
1096 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1097 permittedAccessiblityServices = readPackageList(parser, tag);
1098 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1099 permittedInputMethods = readPackageList(parser, tag);
1100 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1101 keepUninstalledPackages = readPackageList(parser, tag);
1102 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1103 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
1104 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1105 type = parser.next();
1106 if (type == XmlPullParser.TEXT) {
1107 shortSupportMessage = parser.getText();
1109 Log.w(LOG_TAG, "Missing text when loading short support message");
1111 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1112 type = parser.next();
1113 if (type == XmlPullParser.TEXT) {
1114 longSupportMessage = parser.getText();
1116 Log.w(LOG_TAG, "Missing text when loading long support message");
1118 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1119 Preconditions.checkState(!isParent);
1121 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1122 parentAdmin.readFromXml(parser);
1123 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1124 organizationColor = Integer.parseInt(
1125 parser.getAttributeValue(null, ATTR_VALUE));
1126 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1127 type = parser.next();
1128 if (type == XmlPullParser.TEXT) {
1129 organizationName = parser.getText();
1131 Log.w(LOG_TAG, "Missing text when loading organization name");
1134 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1135 XmlUtils.skipCurrentTag(parser);
1140 private List<String> readPackageList(XmlPullParser parser,
1141 String tag) throws XmlPullParserException, IOException {
1142 List<String> result = new ArrayList<String>();
1143 int outerDepth = parser.getDepth();
1145 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1146 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1147 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1150 String outerTag = parser.getName();
1151 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1152 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1153 if (packageName != null) {
1154 result.add(packageName);
1156 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1159 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1165 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1166 throws XmlPullParserException, IOException {
1167 int outerDepthDAM = parser.getDepth();
1169 Set<String> result = new ArraySet<>();
1170 while ((typeDAM=parser.next()) != END_DOCUMENT
1171 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1172 if (typeDAM == END_TAG || typeDAM == TEXT) {
1175 String tagDAM = parser.getName();
1176 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1177 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1179 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1185 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1186 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1187 int outerDepthDAM = parser.getDepth();
1189 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1190 while ((typeDAM=parser.next()) != END_DOCUMENT
1191 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1192 if (typeDAM == END_TAG || typeDAM == TEXT) {
1195 String tagDAM = parser.getName();
1196 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1197 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1198 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1199 result.put(component, trustAgentInfo);
1201 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1207 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1208 throws XmlPullParserException, IOException {
1209 int outerDepthDAM = parser.getDepth();
1211 TrustAgentInfo result = new TrustAgentInfo(null);
1212 while ((typeDAM=parser.next()) != END_DOCUMENT
1213 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1214 if (typeDAM == END_TAG || typeDAM == TEXT) {
1217 String tagDAM = parser.getName();
1218 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1219 result.options = PersistableBundle.restoreFromXml(parser);
1221 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1227 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1228 throws XmlPullParserException, IOException {
1229 int outerDepthDAM = parser.getDepth();
1231 ArrayList<String> result = null;
1232 while ((typeDAM=parser.next()) != END_DOCUMENT
1233 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1234 if (typeDAM == END_TAG || typeDAM == TEXT) {
1237 String tagDAM = parser.getName();
1238 if (TAG_PROVIDER.equals(tagDAM)) {
1239 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1240 if (result == null) {
1241 result = new ArrayList<>();
1243 result.add(provider);
1245 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1251 boolean hasUserRestrictions() {
1252 return userRestrictions != null && userRestrictions.size() > 0;
1255 Bundle ensureUserRestrictions() {
1256 if (userRestrictions == null) {
1257 userRestrictions = new Bundle();
1259 return userRestrictions;
1262 void dump(String prefix, PrintWriter pw) {
1263 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1264 pw.print(prefix); pw.print("testOnlyAdmin=");
1265 pw.println(testOnlyAdmin);
1266 pw.print(prefix); pw.println("policies:");
1267 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1269 for (int i=0; i<pols.size(); i++) {
1270 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1273 pw.print(prefix); pw.print("passwordQuality=0x");
1274 pw.println(Integer.toHexString(passwordQuality));
1275 pw.print(prefix); pw.print("minimumPasswordLength=");
1276 pw.println(minimumPasswordLength);
1277 pw.print(prefix); pw.print("passwordHistoryLength=");
1278 pw.println(passwordHistoryLength);
1279 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1280 pw.println(minimumPasswordUpperCase);
1281 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1282 pw.println(minimumPasswordLowerCase);
1283 pw.print(prefix); pw.print("minimumPasswordLetters=");
1284 pw.println(minimumPasswordLetters);
1285 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1286 pw.println(minimumPasswordNumeric);
1287 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1288 pw.println(minimumPasswordSymbols);
1289 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1290 pw.println(minimumPasswordNonLetter);
1291 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1292 pw.println(maximumTimeToUnlock);
1293 pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1294 pw.println(strongAuthUnlockTimeout);
1295 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1296 pw.println(maximumFailedPasswordsForWipe);
1297 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1298 pw.println(specifiesGlobalProxy);
1299 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1300 pw.println(passwordExpirationTimeout);
1301 pw.print(prefix); pw.print("passwordExpirationDate=");
1302 pw.println(passwordExpirationDate);
1303 if (globalProxySpec != null) {
1304 pw.print(prefix); pw.print("globalProxySpec=");
1305 pw.println(globalProxySpec);
1307 if (globalProxyExclusionList != null) {
1308 pw.print(prefix); pw.print("globalProxyEclusionList=");
1309 pw.println(globalProxyExclusionList);
1311 pw.print(prefix); pw.print("encryptionRequested=");
1312 pw.println(encryptionRequested);
1313 pw.print(prefix); pw.print("disableCamera=");
1314 pw.println(disableCamera);
1315 pw.print(prefix); pw.print("disableCallerId=");
1316 pw.println(disableCallerId);
1317 pw.print(prefix); pw.print("disableContactsSearch=");
1318 pw.println(disableContactsSearch);
1319 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1320 pw.println(disableBluetoothContactSharing);
1321 pw.print(prefix); pw.print("disableScreenCapture=");
1322 pw.println(disableScreenCapture);
1323 pw.print(prefix); pw.print("requireAutoTime=");
1324 pw.println(requireAutoTime);
1325 pw.print(prefix); pw.print("forceEphemeralUsers=");
1326 pw.println(forceEphemeralUsers);
1327 pw.print(prefix); pw.print("isNetworkLoggingEnabled=");
1328 pw.println(isNetworkLoggingEnabled);
1329 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1330 pw.println(disabledKeyguardFeatures);
1331 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1332 pw.println(crossProfileWidgetProviders);
1333 if (permittedAccessiblityServices != null) {
1334 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1335 pw.println(permittedAccessiblityServices);
1337 if (permittedInputMethods != null) {
1338 pw.print(prefix); pw.print("permittedInputMethods=");
1339 pw.println(permittedInputMethods);
1341 if (keepUninstalledPackages != null) {
1342 pw.print(prefix); pw.print("keepUninstalledPackages=");
1343 pw.println(keepUninstalledPackages);
1345 pw.print(prefix); pw.print("organizationColor=");
1346 pw.println(organizationColor);
1347 if (organizationName != null) {
1348 pw.print(prefix); pw.print("organizationName=");
1349 pw.println(organizationName);
1351 pw.print(prefix); pw.println("userRestrictions:");
1352 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1353 pw.print(prefix); pw.print("isParent=");
1354 pw.println(isParent);
1355 if (parentAdmin != null) {
1356 pw.print(prefix); pw.println("parentAdmin:");
1357 parentAdmin.dump(prefix + " ", pw);
1362 private void handlePackagesChanged(String packageName, int userHandle) {
1363 boolean removed = false;
1364 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1365 DevicePolicyData policy = getUserData(userHandle);
1366 synchronized (this) {
1367 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1368 ActiveAdmin aa = policy.mAdminList.get(i);
1370 // If we're checking all packages or if the specific one we're checking matches,
1371 // then check if the package and receiver still exist.
1372 final String adminPackage = aa.info.getPackageName();
1373 if (packageName == null || packageName.equals(adminPackage)) {
1374 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1375 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1376 PackageManager.MATCH_DIRECT_BOOT_AWARE
1377 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1378 userHandle) == null) {
1380 policy.mAdminList.remove(i);
1381 policy.mAdminMap.remove(aa.info.getComponent());
1384 } catch (RemoteException re) {
1389 validatePasswordOwnerLocked(policy);
1390 saveSettingsLocked(policy.mUserHandle);
1393 // Check if delegated cert installer or app restrictions managing packages are removed.
1394 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1395 policy.mDelegatedCertInstallerPackage = null;
1396 saveSettingsLocked(policy.mUserHandle);
1398 if (isRemovedPackage(
1399 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1400 policy.mApplicationRestrictionsManagingPackage = null;
1401 saveSettingsLocked(policy.mUserHandle);
1405 // The removed admin might have disabled camera, so update user restrictions.
1406 pushUserRestrictions(userHandle);
1410 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1412 return targetPackage != null
1413 && (changedPackage == null || changedPackage.equals(targetPackage))
1414 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1415 } catch (RemoteException e) {
1423 * Unit test will subclass it to inject mocks.
1426 static class Injector {
1428 private final Context mContext;
1430 Injector(Context context) {
1434 Owners newOwners() {
1435 return new Owners(getUserManager(), getUserManagerInternal(),
1436 getPackageManagerInternal());
1439 UserManager getUserManager() {
1440 return UserManager.get(mContext);
1443 UserManagerInternal getUserManagerInternal() {
1444 return LocalServices.getService(UserManagerInternal.class);
1447 PackageManagerInternal getPackageManagerInternal() {
1448 return LocalServices.getService(PackageManagerInternal.class);
1451 NotificationManager getNotificationManager() {
1452 return mContext.getSystemService(NotificationManager.class);
1455 IIpConnectivityMetrics getIIpConnectivityMetrics() {
1456 return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1457 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1460 PowerManagerInternal getPowerManagerInternal() {
1461 return LocalServices.getService(PowerManagerInternal.class);
1464 TelephonyManager getTelephonyManager() {
1465 return TelephonyManager.from(mContext);
1468 TrustManager getTrustManager() {
1469 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1472 AlarmManager getAlarmManager() {
1473 return (AlarmManager) mContext.getSystemService(AlarmManager.class);
1476 IWindowManager getIWindowManager() {
1477 return IWindowManager.Stub
1478 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1481 IActivityManager getIActivityManager() {
1482 return ActivityManagerNative.getDefault();
1485 IPackageManager getIPackageManager() {
1486 return AppGlobals.getPackageManager();
1489 IBackupManager getIBackupManager() {
1490 return IBackupManager.Stub.asInterface(
1491 ServiceManager.getService(Context.BACKUP_SERVICE));
1494 IAudioService getIAudioService() {
1495 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1498 LockPatternUtils newLockPatternUtils() {
1499 return new LockPatternUtils(mContext);
1502 boolean storageManagerIsFileBasedEncryptionEnabled() {
1503 return StorageManager.isFileEncryptedNativeOnly();
1506 boolean storageManagerIsNonDefaultBlockEncrypted() {
1507 long identity = Binder.clearCallingIdentity();
1509 return StorageManager.isNonDefaultBlockEncrypted();
1511 Binder.restoreCallingIdentity(identity);
1515 boolean storageManagerIsEncrypted() {
1516 return StorageManager.isEncrypted();
1519 boolean storageManagerIsEncryptable() {
1520 return StorageManager.isEncryptable();
1523 Looper getMyLooper() {
1524 return Looper.myLooper();
1527 WifiManager getWifiManager() {
1528 return mContext.getSystemService(WifiManager.class);
1531 long binderClearCallingIdentity() {
1532 return Binder.clearCallingIdentity();
1535 void binderRestoreCallingIdentity(long token) {
1536 Binder.restoreCallingIdentity(token);
1539 int binderGetCallingUid() {
1540 return Binder.getCallingUid();
1543 int binderGetCallingPid() {
1544 return Binder.getCallingPid();
1547 UserHandle binderGetCallingUserHandle() {
1548 return Binder.getCallingUserHandle();
1551 boolean binderIsCallingUidMyUid() {
1552 return getCallingUid() == Process.myUid();
1555 final int userHandleGetCallingUserId() {
1556 return UserHandle.getUserId(binderGetCallingUid());
1559 File environmentGetUserSystemDirectory(int userId) {
1560 return Environment.getUserSystemDirectory(userId);
1563 void powerManagerGoToSleep(long time, int reason, int flags) {
1564 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1567 void powerManagerReboot(String reason) {
1568 mContext.getSystemService(PowerManager.class).reboot(reason);
1571 boolean systemPropertiesGetBoolean(String key, boolean def) {
1572 return SystemProperties.getBoolean(key, def);
1575 long systemPropertiesGetLong(String key, long def) {
1576 return SystemProperties.getLong(key, def);
1579 String systemPropertiesGet(String key, String def) {
1580 return SystemProperties.get(key, def);
1583 String systemPropertiesGet(String key) {
1584 return SystemProperties.get(key);
1587 void systemPropertiesSet(String key, String value) {
1588 SystemProperties.set(key, value);
1591 boolean userManagerIsSplitSystemUser() {
1592 return UserManager.isSplitSystemUser();
1595 String getDevicePolicyFilePathForSystemUser() {
1596 return "/data/system/";
1599 void registerContentObserver(Uri uri, boolean notifyForDescendents,
1600 ContentObserver observer, int userHandle) {
1601 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1602 observer, userHandle);
1605 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1606 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1607 name, def, userHandle);
1610 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1611 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1612 name, value, userHandle);
1615 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1616 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1617 name, value, userHandle);
1620 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1621 Settings.Global.putStringForUser(mContext.getContentResolver(),
1622 name, value, userHandle);
1625 void settingsSecurePutInt(String name, int value) {
1626 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1629 int settingsGlobalGetInt(String name, int def) {
1630 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1633 void settingsGlobalPutInt(String name, int value) {
1634 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1637 void settingsSecurePutString(String name, String value) {
1638 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1641 void settingsGlobalPutString(String name, String value) {
1642 Settings.Global.putString(mContext.getContentResolver(), name, value);
1645 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1646 SecurityLog.setLoggingEnabledProperty(enabled);
1649 boolean securityLogGetLoggingEnabledProperty() {
1650 return SecurityLog.getLoggingEnabledProperty();
1653 boolean securityLogIsLoggingEnabled() {
1654 return SecurityLog.isLoggingEnabled();
1659 * Instantiates the service.
1661 public DevicePolicyManagerService(Context context) {
1662 this(new Injector(context));
1666 DevicePolicyManagerService(Injector injector) {
1667 mInjector = injector;
1668 mContext = Preconditions.checkNotNull(injector.mContext);
1669 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1670 mOwners = Preconditions.checkNotNull(injector.newOwners());
1672 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1673 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1674 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1675 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1677 mLocalService = new LocalService();
1678 mLockPatternUtils = injector.newLockPatternUtils();
1680 mSecurityLogMonitor = new SecurityLogMonitor(this);
1682 mHasFeature = mContext.getPackageManager()
1683 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1684 mIsWatch = mContext.getPackageManager()
1685 .hasSystemFeature(PackageManager.FEATURE_WATCH);
1687 // Skip the rest of the initialization
1690 IntentFilter filter = new IntentFilter();
1691 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1692 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1693 filter.addAction(Intent.ACTION_USER_ADDED);
1694 filter.addAction(Intent.ACTION_USER_REMOVED);
1695 filter.addAction(Intent.ACTION_USER_STARTED);
1696 filter.addAction(Intent.ACTION_USER_UNLOCKED);
1697 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1698 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1699 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1700 filter = new IntentFilter();
1701 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1702 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1703 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1704 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1705 filter.addDataScheme("package");
1706 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1707 filter = new IntentFilter();
1708 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1709 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1711 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1715 * Creates and loads the policy data from xml.
1716 * @param userHandle the user for whom to load the policy data
1720 DevicePolicyData getUserData(int userHandle) {
1721 synchronized (this) {
1722 DevicePolicyData policy = mUserData.get(userHandle);
1723 if (policy == null) {
1724 policy = new DevicePolicyData(userHandle);
1725 mUserData.append(userHandle, policy);
1726 loadSettingsLocked(policy, userHandle);
1733 * Creates and loads the policy data from xml for data that is shared between
1734 * various profiles of a user. In contrast to {@link #getUserData(int)}
1735 * it allows access to data of users other than the calling user.
1737 * This function should only be used for shared data, e.g. everything regarding
1738 * passwords and should be removed once multiple screen locks are present.
1739 * @param userHandle the user for whom to load the policy data
1742 DevicePolicyData getUserDataUnchecked(int userHandle) {
1743 long ident = mInjector.binderClearCallingIdentity();
1745 return getUserData(userHandle);
1747 mInjector.binderRestoreCallingIdentity(ident);
1751 void removeUserData(int userHandle) {
1752 synchronized (this) {
1753 if (userHandle == UserHandle.USER_SYSTEM) {
1754 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1757 mOwners.removeProfileOwner(userHandle);
1758 mOwners.writeProfileOwner(userHandle);
1760 DevicePolicyData policy = mUserData.get(userHandle);
1761 if (policy != null) {
1762 mUserData.remove(userHandle);
1764 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1765 DEVICE_POLICIES_XML);
1766 policyFile.delete();
1767 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1769 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1773 synchronized (this) {
1775 setDeviceOwnerSystemPropertyLocked();
1776 findOwnerComponentIfNecessaryLocked();
1777 migrateUserRestrictionsIfNecessaryLocked();
1779 // TODO PO may not have a class name either due to b/17652534. Address that too.
1781 updateDeviceOwnerLocked();
1785 private void setDeviceOwnerSystemPropertyLocked() {
1786 final boolean deviceProvisioned =
1787 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0;
1788 // If the device is not provisioned and there is currently no device owner, do not set the
1789 // read-only system property yet, since Device owner may still be provisioned. For Wear
1790 // devices, if there is already a device owner then it's OK to set the property to true now,
1791 // regardless the provision state.
1792 final boolean isWatchWithDeviceOwner = mIsWatch && mOwners.hasDeviceOwner();
1793 if (!isWatchWithDeviceOwner && !deviceProvisioned) {
1796 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1797 // always false at this point.
1798 if (StorageManager.inCryptKeeperBounce()) {
1802 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1803 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1805 if (mOwners.hasDeviceOwner()) {
1806 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1807 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1808 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
1809 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1810 mSecurityLogMonitor.start();
1813 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1814 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1819 private void findOwnerComponentIfNecessaryLocked() {
1820 if (!mOwners.hasDeviceOwner()) {
1823 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1825 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1826 return; // Already a full component name.
1829 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1830 doComponentName.getPackageName(),
1831 mOwners.getDeviceOwnerUserId());
1832 if (doComponent == null) {
1833 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1835 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1837 mOwners.getDeviceOwnerName(),
1838 mOwners.getDeviceOwnerUserId(),
1839 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1840 mOwners.writeDeviceOwner();
1842 Log.v(LOG_TAG, "Device owner component filled in");
1848 * We didn't use to persist user restrictions for each owners but only persisted in user
1851 private void migrateUserRestrictionsIfNecessaryLocked() {
1852 boolean migrated = false;
1853 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1854 // except for the "system controlled" ones.
1855 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1857 Log.v(LOG_TAG, "Migrating DO user restrictions");
1861 // Migrate user 0 restrictions to DO.
1862 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1864 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1865 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1867 // Push DO user restrictions to user manager.
1868 pushUserRestrictions(UserHandle.USER_SYSTEM);
1870 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1875 // The following restrictions can be set on secondary users by the device owner, so we
1876 // assume they're not from the PO.
1877 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1878 UserManager.DISALLOW_OUTGOING_CALLS,
1879 UserManager.DISALLOW_SMS);
1881 for (UserInfo ui : mUserManager.getUsers()) {
1882 final int userId = ui.id;
1883 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1885 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1889 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1891 final Set<String> exceptionList =
1892 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1894 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1895 exceptionList, /* isDeviceOwner =*/ false);
1897 // Note if a secondary user has no PO but has a DA that disables camera, we
1898 // don't get here and won't push the camera user restriction to UserManager
1899 // here. That's okay because we'll push user restrictions anyway when a user
1900 // starts. But we still do it because we want to let user manager persist
1902 pushUserRestrictions(userId);
1904 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1907 if (VERBOSE_LOG && migrated) {
1908 Log.v(LOG_TAG, "User restrictions migrated.");
1912 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1913 Set<String> exceptionList, boolean isDeviceOwner) {
1914 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1915 user.getIdentifier());
1917 final Bundle newBaseRestrictions = new Bundle();
1918 final Bundle newOwnerRestrictions = new Bundle();
1920 for (String key : origRestrictions.keySet()) {
1921 if (!origRestrictions.getBoolean(key)) {
1924 final boolean canOwnerChange = isDeviceOwner
1925 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1926 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1928 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1929 newBaseRestrictions.putBoolean(key, true);
1931 newOwnerRestrictions.putBoolean(key, true);
1936 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1937 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1938 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1940 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1941 newBaseRestrictions);
1943 if (admin != null) {
1944 admin.ensureUserRestrictions().clear();
1945 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1947 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1949 saveSettingsLocked(user.getIdentifier());
1952 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1953 final DevicePolicyData policy = getUserData(userId);
1954 final int n = policy.mAdminList.size();
1955 ComponentName found = null;
1957 for (int i = 0; i < n; i++) {
1958 final ActiveAdmin admin = policy.mAdminList.get(i);
1959 if (packageName.equals(admin.info.getPackageName())) {
1962 found = admin.info.getComponent();
1968 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1974 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1975 * reminders. Clears alarm if no expirations are configured.
1977 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1978 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1979 final long now = System.currentTimeMillis();
1980 final long timeToExpire = expiration - now;
1981 final long alarmTime;
1982 if (expiration == 0) {
1983 // No expirations are currently configured: Cancel alarm.
1985 } else if (timeToExpire <= 0) {
1986 // The password has already expired: Repeat every 24 hours.
1987 alarmTime = now + MS_PER_DAY;
1989 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1990 // the expiration time.
1991 long alarmInterval = timeToExpire % MS_PER_DAY;
1992 if (alarmInterval == 0) {
1993 alarmInterval = MS_PER_DAY;
1995 alarmTime = now + alarmInterval;
1998 long token = mInjector.binderClearCallingIdentity();
2000 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
2001 AlarmManager am = mInjector.getAlarmManager();
2002 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2003 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2004 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
2005 UserHandle.of(affectedUserHandle));
2007 if (alarmTime != 0) {
2008 am.set(AlarmManager.RTC, alarmTime, pi);
2011 mInjector.binderRestoreCallingIdentity(token);
2015 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2016 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2018 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2019 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2025 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2027 enforceManagedProfile(userHandle, "call APIs on the parent profile");
2029 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2030 if (admin != null && parent) {
2031 admin = admin.getParentActiveAdmin();
2036 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2037 throws SecurityException {
2038 final int callingUid = mInjector.binderGetCallingUid();
2040 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
2041 if (result != null) {
2046 final int userId = UserHandle.getUserId(callingUid);
2047 final DevicePolicyData policy = getUserData(userId);
2048 ActiveAdmin admin = policy.mAdminMap.get(who);
2049 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2050 throw new SecurityException("Admin " + admin.info.getComponent()
2051 + " does not own the device");
2053 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2054 throw new SecurityException("Admin " + admin.info.getComponent()
2055 + " does not own the profile");
2057 throw new SecurityException("Admin " + admin.info.getComponent()
2058 + " did not specify uses-policy for: "
2059 + admin.info.getTagForPolicy(reqPolicy));
2061 throw new SecurityException("No active admin owned by uid "
2062 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
2066 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2067 throws SecurityException {
2069 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2070 "call APIs on the parent profile");
2072 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2073 return parent ? admin.getParentActiveAdmin() : admin;
2076 * Find the admin for the component and userId bit of the uid, then check
2077 * the admin's uid matches the uid.
2079 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2080 final int userId = UserHandle.getUserId(uid);
2081 final DevicePolicyData policy = getUserData(userId);
2082 ActiveAdmin admin = policy.mAdminMap.get(who);
2083 if (admin == null) {
2084 throw new SecurityException("No active admin " + who);
2086 if (admin.getUid() != uid) {
2087 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2092 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2094 // Try to find an admin which can use reqPolicy
2095 final int userId = UserHandle.getUserId(uid);
2096 final DevicePolicyData policy = getUserData(userId);
2098 ActiveAdmin admin = policy.mAdminMap.get(who);
2099 if (admin == null) {
2100 throw new SecurityException("No active admin " + who);
2102 if (admin.getUid() != uid) {
2103 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2105 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2109 for (ActiveAdmin admin : policy.mAdminList) {
2110 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2121 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2123 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2124 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2126 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2128 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2129 // DO always has the PO power.
2130 return ownsDevice || ownsProfile;
2132 return admin.info.usesPolicy(reqPolicy);
2136 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2137 sendAdminCommandLocked(admin, action, null);
2140 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2141 sendAdminCommandLocked(admin, action, null, result);
2145 * Send an update to one specific admin, get notified when that admin returns a result.
2147 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2148 BroadcastReceiver result) {
2149 Intent intent = new Intent(action);
2150 intent.setComponent(admin.info.getComponent());
2151 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2152 intent.putExtra("expiration", admin.passwordExpirationDate);
2154 if (adminExtras != null) {
2155 intent.putExtras(adminExtras);
2157 if (result != null) {
2158 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2159 null, result, mHandler, Activity.RESULT_OK, null, null);
2161 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2166 * Send an update to all admins of a user that enforce a specified policy.
2168 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2169 final DevicePolicyData policy = getUserData(userHandle);
2170 final int count = policy.mAdminList.size();
2172 for (int i = 0; i < count; i++) {
2173 final ActiveAdmin admin = policy.mAdminList.get(i);
2174 if (admin.info.usesPolicy(reqPolicy)) {
2175 sendAdminCommandLocked(admin, action);
2182 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2183 * enforce a specified policy.
2185 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2187 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2188 for (int profileId : profileIds) {
2189 sendAdminCommandLocked(action, reqPolicy, profileId);
2194 * Sends a broadcast to each profile that share the password unlock with the given user id.
2196 private void sendAdminCommandForLockscreenPoliciesLocked(
2197 String action, int reqPolicy, int userHandle) {
2198 if (isSeparateProfileChallengeEnabled(userHandle)) {
2199 sendAdminCommandLocked(action, reqPolicy, userHandle);
2201 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2205 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2206 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2207 DevicePolicyData policy = getUserData(userHandle);
2208 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2209 policy.mRemovingAdmins.add(adminReceiver);
2210 sendAdminCommandLocked(admin,
2211 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2212 new BroadcastReceiver() {
2214 public void onReceive(Context context, Intent intent) {
2215 removeAdminArtifacts(adminReceiver, userHandle);
2216 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2223 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2224 boolean throwForMissiongPermission) {
2228 enforceFullCrossUsersPermission(userHandle);
2229 ActivityInfo ai = null;
2231 ai = mIPackageManager.getReceiverInfo(adminName,
2232 PackageManager.GET_META_DATA |
2233 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2234 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2235 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2236 } catch (RemoteException e) {
2237 // shouldn't happen.
2240 throw new IllegalArgumentException("Unknown admin: " + adminName);
2243 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2244 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2245 + permission.BIND_DEVICE_ADMIN;
2246 Slog.w(LOG_TAG, message);
2247 if (throwForMissiongPermission &&
2248 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2249 throw new IllegalArgumentException(message);
2254 return new DeviceAdminInfo(mContext, ai);
2255 } catch (XmlPullParserException | IOException e) {
2256 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2262 private JournaledFile makeJournaledFile(int userHandle) {
2263 final String base = userHandle == UserHandle.USER_SYSTEM
2264 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2265 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2266 DEVICE_POLICIES_XML).getAbsolutePath();
2268 Log.v(LOG_TAG, "Opening " + base);
2270 return new JournaledFile(new File(base), new File(base + ".tmp"));
2273 private void saveSettingsLocked(int userHandle) {
2274 DevicePolicyData policy = getUserData(userHandle);
2275 JournaledFile journal = makeJournaledFile(userHandle);
2276 FileOutputStream stream = null;
2278 stream = new FileOutputStream(journal.chooseForWrite(), false);
2279 XmlSerializer out = new FastXmlSerializer();
2280 out.setOutput(stream, StandardCharsets.UTF_8.name());
2281 out.startDocument(null, true);
2283 out.startTag(null, "policies");
2284 if (policy.mRestrictionsProvider != null) {
2285 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2286 policy.mRestrictionsProvider.flattenToString());
2288 if (policy.mUserSetupComplete) {
2289 out.attribute(null, ATTR_SETUP_COMPLETE,
2290 Boolean.toString(true));
2292 if (policy.mPaired) {
2293 out.attribute(null, ATTR_DEVICE_PAIRED,
2294 Boolean.toString(true));
2296 if (policy.mDeviceProvisioningConfigApplied) {
2297 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2298 Boolean.toString(true));
2300 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2301 out.attribute(null, ATTR_PROVISIONING_STATE,
2302 Integer.toString(policy.mUserProvisioningState));
2304 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2305 out.attribute(null, ATTR_PERMISSION_POLICY,
2306 Integer.toString(policy.mPermissionPolicy));
2308 if (policy.mDelegatedCertInstallerPackage != null) {
2309 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2310 policy.mDelegatedCertInstallerPackage);
2312 if (policy.mApplicationRestrictionsManagingPackage != null) {
2313 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2314 policy.mApplicationRestrictionsManagingPackage);
2317 final int N = policy.mAdminList.size();
2318 for (int i=0; i<N; i++) {
2319 ActiveAdmin ap = policy.mAdminList.get(i);
2321 out.startTag(null, "admin");
2322 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2324 out.endTag(null, "admin");
2328 if (policy.mPasswordOwner >= 0) {
2329 out.startTag(null, "password-owner");
2330 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2331 out.endTag(null, "password-owner");
2334 if (policy.mFailedPasswordAttempts != 0) {
2335 out.startTag(null, "failed-password-attempts");
2336 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2337 out.endTag(null, "failed-password-attempts");
2340 // Don't save metrics for FBE devices
2341 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
2342 && (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2343 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2344 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2345 || policy.mActivePasswordSymbols != 0
2346 || policy.mActivePasswordNonLetter != 0)) {
2347 out.startTag(null, "active-password");
2348 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2349 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2350 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2351 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2352 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2353 out.attribute(null, "numeric", Integer
2354 .toString(policy.mActivePasswordNumeric));
2355 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2356 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2357 out.endTag(null, "active-password");
2360 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2361 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2362 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2363 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2366 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2367 String component = policy.mLockTaskPackages.get(i);
2368 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2369 out.attribute(null, "name", component);
2370 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2373 if (policy.mStatusBarDisabled) {
2374 out.startTag(null, TAG_STATUS_BAR);
2375 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2376 out.endTag(null, TAG_STATUS_BAR);
2379 if (policy.doNotAskCredentialsOnBoot) {
2380 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2381 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2384 for (String id : policy.mAffiliationIds) {
2385 out.startTag(null, TAG_AFFILIATION_ID);
2386 out.attribute(null, "id", id);
2387 out.endTag(null, TAG_AFFILIATION_ID);
2390 if (policy.mAdminBroadcastPending) {
2391 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2392 out.attribute(null, ATTR_VALUE,
2393 Boolean.toString(policy.mAdminBroadcastPending));
2394 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2397 if (policy.mInitBundle != null) {
2398 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2399 policy.mInitBundle.saveToXml(out);
2400 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2403 out.endTag(null, "policies");
2407 FileUtils.sync(stream);
2410 sendChangedNotification(userHandle);
2411 } catch (XmlPullParserException | IOException e) {
2412 Slog.w(LOG_TAG, "failed writing file", e);
2414 if (stream != null) {
2417 } catch (IOException ex) {
2424 private void sendChangedNotification(int userHandle) {
2425 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2426 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2427 long ident = mInjector.binderClearCallingIdentity();
2429 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2431 mInjector.binderRestoreCallingIdentity(ident);
2435 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2436 JournaledFile journal = makeJournaledFile(userHandle);
2437 FileInputStream stream = null;
2438 File file = journal.chooseForRead();
2439 boolean needsRewrite = false;
2441 stream = new FileInputStream(file);
2442 XmlPullParser parser = Xml.newPullParser();
2443 parser.setInput(stream, StandardCharsets.UTF_8.name());
2446 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2447 && type != XmlPullParser.START_TAG) {
2449 String tag = parser.getName();
2450 if (!"policies".equals(tag)) {
2451 throw new XmlPullParserException(
2452 "Settings do not start with policies tag: found " + tag);
2455 // Extract the permission provider component name if available
2456 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2457 if (permissionProvider != null) {
2458 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2460 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2461 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2462 policy.mUserSetupComplete = true;
2464 String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
2465 if (paired != null && Boolean.toString(true).equals(paired)) {
2466 policy.mPaired = true;
2468 String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2469 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2470 if (deviceProvisioningConfigApplied != null
2471 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2472 policy.mDeviceProvisioningConfigApplied = true;
2474 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2475 if (!TextUtils.isEmpty(provisioningState)) {
2476 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2478 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2479 if (!TextUtils.isEmpty(permissionPolicy)) {
2480 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2482 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2483 ATTR_DELEGATED_CERT_INSTALLER);
2484 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2485 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2487 type = parser.next();
2488 int outerDepth = parser.getDepth();
2489 policy.mLockTaskPackages.clear();
2490 policy.mAdminList.clear();
2491 policy.mAdminMap.clear();
2492 policy.mAffiliationIds.clear();
2493 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2494 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2495 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2498 tag = parser.getName();
2499 if ("admin".equals(tag)) {
2500 String name = parser.getAttributeValue(null, "name");
2502 DeviceAdminInfo dai = findAdmin(
2503 ComponentName.unflattenFromString(name), userHandle,
2504 /* throwForMissionPermission= */ false);
2506 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2508 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2509 + dai.getActivityInfo().applicationInfo.uid + " for user "
2513 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2514 ap.readFromXml(parser);
2515 policy.mAdminMap.put(ap.info.getComponent(), ap);
2517 } catch (RuntimeException e) {
2518 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2520 } else if ("failed-password-attempts".equals(tag)) {
2521 policy.mFailedPasswordAttempts = Integer.parseInt(
2522 parser.getAttributeValue(null, "value"));
2523 } else if ("password-owner".equals(tag)) {
2524 policy.mPasswordOwner = Integer.parseInt(
2525 parser.getAttributeValue(null, "value"));
2526 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2527 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2528 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2529 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2530 } else if (TAG_STATUS_BAR.equals(tag)) {
2531 policy.mStatusBarDisabled = Boolean.parseBoolean(
2532 parser.getAttributeValue(null, ATTR_DISABLED));
2533 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2534 policy.doNotAskCredentialsOnBoot = true;
2535 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2536 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2537 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2538 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2539 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2540 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2541 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2542 } else if ("active-password".equals(tag)) {
2543 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2544 // Remove this from FBE devices
2545 needsRewrite = true;
2547 policy.mActivePasswordQuality = Integer.parseInt(
2548 parser.getAttributeValue(null, "quality"));
2549 policy.mActivePasswordLength = Integer.parseInt(
2550 parser.getAttributeValue(null, "length"));
2551 policy.mActivePasswordUpperCase = Integer.parseInt(
2552 parser.getAttributeValue(null, "uppercase"));
2553 policy.mActivePasswordLowerCase = Integer.parseInt(
2554 parser.getAttributeValue(null, "lowercase"));
2555 policy.mActivePasswordLetters = Integer.parseInt(
2556 parser.getAttributeValue(null, "letters"));
2557 policy.mActivePasswordNumeric = Integer.parseInt(
2558 parser.getAttributeValue(null, "numeric"));
2559 policy.mActivePasswordSymbols = Integer.parseInt(
2560 parser.getAttributeValue(null, "symbols"));
2561 policy.mActivePasswordNonLetter = Integer.parseInt(
2562 parser.getAttributeValue(null, "nonletter"));
2565 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2566 XmlUtils.skipCurrentTag(parser);
2569 } catch (FileNotFoundException e) {
2570 // Don't be noisy, this is normal if we haven't defined any policies.
2571 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2572 | IndexOutOfBoundsException e) {
2573 Slog.w(LOG_TAG, "failed parsing " + file, e);
2576 if (stream != null) {
2579 } catch (IOException e) {
2583 // Generate a list of admins from the admin map
2584 policy.mAdminList.addAll(policy.mAdminMap.values());
2586 // Might need to upgrade the file by rewriting it
2588 saveSettingsLocked(userHandle);
2591 validatePasswordOwnerLocked(policy);
2592 updateMaximumTimeToLockLocked(userHandle);
2593 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2594 if (policy.mStatusBarDisabled) {
2595 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2599 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2600 long ident = mInjector.binderClearCallingIdentity();
2602 mInjector.getIActivityManager()
2603 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2604 } catch (RemoteException e) {
2605 // Not gonna happen.
2607 mInjector.binderRestoreCallingIdentity(ident);
2611 private void updateDeviceOwnerLocked() {
2612 long ident = mInjector.binderClearCallingIdentity();
2614 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2615 // user id and also protect all other DAs too.
2616 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2617 if (deviceOwnerComponent != null) {
2618 mInjector.getIActivityManager()
2619 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2621 } catch (RemoteException e) {
2622 // Not gonna happen.
2624 mInjector.binderRestoreCallingIdentity(ident);
2628 static void validateQualityConstant(int quality) {
2630 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2631 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2632 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2633 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2634 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2635 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2636 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2637 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2638 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2641 throw new IllegalArgumentException("Invalid quality constant: 0x"
2642 + Integer.toHexString(quality));
2645 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2646 if (policy.mPasswordOwner >= 0) {
2647 boolean haveOwner = false;
2648 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2649 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2655 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2656 + " no longer active; disabling");
2657 policy.mPasswordOwner = -1;
2663 void systemReady(int phase) {
2668 case SystemService.PHASE_LOCK_SETTINGS_READY:
2669 onLockSettingsReady();
2671 case SystemService.PHASE_BOOT_COMPLETED:
2672 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2677 private void onLockSettingsReady() {
2678 getUserData(UserHandle.USER_SYSTEM);
2682 onStartUser(UserHandle.USER_SYSTEM);
2684 // Register an observer for watching for user setup complete.
2685 new SetupContentObserver(mHandler).register();
2686 // Initialize the user setup state, to handle the upgrade case.
2687 updateUserSetupCompleteAndPaired();
2689 List<String> packageList;
2690 synchronized (this) {
2691 packageList = getKeepUninstalledPackagesLocked();
2693 if (packageList != null) {
2694 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2697 synchronized (this) {
2698 // push the force-ephemeral-users policy to the user manager.
2699 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2700 if (deviceOwner != null) {
2701 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2706 private void ensureDeviceOwnerUserStarted() {
2708 synchronized (this) {
2709 if (!mOwners.hasDeviceOwner()) {
2712 userId = mOwners.getDeviceOwnerUserId();
2715 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2717 if (userId != UserHandle.USER_SYSTEM) {
2719 mInjector.getIActivityManager().startUserInBackground(userId);
2721 // STOPSHIP Prevent the DO user from being killed.
2723 } catch (RemoteException e) {
2724 Slog.w(LOG_TAG, "Exception starting user", e);
2729 private void onStartUser(int userId) {
2730 updateScreenCaptureDisabledInWindowManager(userId,
2731 getScreenCaptureDisabled(null, userId));
2732 pushUserRestrictions(userId);
2735 private void cleanUpOldUsers() {
2736 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2738 Set<Integer> usersWithProfileOwners;
2739 Set<Integer> usersWithData;
2740 synchronized(this) {
2741 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2742 usersWithData = new ArraySet<>();
2743 for (int i = 0; i < mUserData.size(); i++) {
2744 usersWithData.add(mUserData.keyAt(i));
2747 List<UserInfo> allUsers = mUserManager.getUsers();
2749 Set<Integer> deletedUsers = new ArraySet<>();
2750 deletedUsers.addAll(usersWithProfileOwners);
2751 deletedUsers.addAll(usersWithData);
2752 for (UserInfo userInfo : allUsers) {
2753 deletedUsers.remove(userInfo.id);
2755 for (Integer userId : deletedUsers) {
2756 removeUserData(userId);
2760 private void handlePasswordExpirationNotification(int userHandle) {
2761 synchronized (this) {
2762 final long now = System.currentTimeMillis();
2764 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2765 userHandle, /* parent */ false);
2766 final int N = admins.size();
2767 for (int i = 0; i < N; i++) {
2768 ActiveAdmin admin = admins.get(i);
2769 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2770 && admin.passwordExpirationTimeout > 0L
2771 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2772 && admin.passwordExpirationDate > 0L) {
2773 sendAdminCommandLocked(admin,
2774 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2777 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2781 private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2783 protected Void doInBackground(Integer... params) {
2784 int userHandle = params[0];
2786 if (userHandle == UserHandle.USER_ALL) {
2787 for (UserInfo userInfo : mUserManager.getUsers(true)) {
2788 manageNotification(userInfo.getUserHandle());
2791 manageNotification(UserHandle.of(userHandle));
2796 private void manageNotification(UserHandle userHandle) {
2797 if (!mUserManager.isUserUnlocked(userHandle)) {
2801 // Call out to KeyChain to check for CAs which are waiting for approval.
2802 final List<String> pendingCertificates;
2804 pendingCertificates = getInstalledCaCertificates(userHandle);
2805 } catch (RemoteException | RuntimeException e) {
2806 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2810 synchronized (DevicePolicyManagerService.this) {
2811 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2813 // Remove deleted certificates. Flush xml if necessary.
2814 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2815 saveSettingsLocked(userHandle.getIdentifier());
2817 // Trim to approved certificates.
2818 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2821 if (pendingCertificates.isEmpty()) {
2822 mInjector.getNotificationManager().cancelAsUser(
2823 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2827 // Build and show a warning notification
2830 int parentUserId = userHandle.getIdentifier();
2831 if (getProfileOwner(userHandle.getIdentifier()) != null) {
2832 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2833 getProfileOwnerName(userHandle.getIdentifier()));
2834 smallIconId = R.drawable.stat_sys_certificate_info;
2835 parentUserId = getProfileParentId(userHandle.getIdentifier());
2836 } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
2837 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2838 getDeviceOwnerName());
2839 smallIconId = R.drawable.stat_sys_certificate_info;
2841 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2842 smallIconId = android.R.drawable.stat_sys_warning;
2845 final int numberOfCertificates = pendingCertificates.size();
2846 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2847 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2848 dialogIntent.setPackage("com.android.settings");
2849 dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
2850 dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
2851 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2852 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
2853 new UserHandle(parentUserId));
2855 final Context userContext;
2857 final String packageName = mContext.getPackageName();
2858 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
2859 } catch (PackageManager.NameNotFoundException e) {
2860 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2863 final Notification noti = new Notification.Builder(userContext)
2864 .setSmallIcon(smallIconId)
2865 .setContentTitle(mContext.getResources().getQuantityText(
2866 R.plurals.ssl_ca_cert_warning, numberOfCertificates))
2867 .setContentText(contentText)
2868 .setContentIntent(notifyIntent)
2869 .setPriority(Notification.PRIORITY_HIGH)
2871 .setColor(mContext.getColor(
2872 com.android.internal.R.color.system_notification_accent_color))
2875 mInjector.getNotificationManager().notifyAsUser(
2876 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2879 private List<String> getInstalledCaCertificates(UserHandle userHandle)
2880 throws RemoteException, RuntimeException {
2881 KeyChainConnection conn = null;
2883 conn = KeyChain.bindAsUser(mContext, userHandle);
2884 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
2885 List<String> result = new ArrayList<>(aliases.size());
2886 for (int i = 0; i < aliases.size(); i++) {
2887 result.add(aliases.get(i).string);
2890 } catch (InterruptedException e) {
2891 Thread.currentThread().interrupt();
2893 } catch (AssertionError e) {
2894 throw new RuntimeException(e);
2904 * @param adminReceiver The admin to add
2905 * @param refreshing true = update an active admin, no error
2908 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2912 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2915 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2916 Bundle onEnableData) {
2917 mContext.enforceCallingOrSelfPermission(
2918 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2919 enforceFullCrossUsersPermission(userHandle);
2921 DevicePolicyData policy = getUserData(userHandle);
2922 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2923 /* throwForMissionPermission= */ true);
2925 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2927 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2928 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2931 synchronized (this) {
2932 long ident = mInjector.binderClearCallingIdentity();
2934 final ActiveAdmin existingAdmin
2935 = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2936 if (!refreshing && existingAdmin != null) {
2937 throw new IllegalArgumentException("Admin is already added");
2939 if (policy.mRemovingAdmins.contains(adminReceiver)) {
2940 throw new IllegalArgumentException(
2941 "Trying to set an admin which is being removed");
2943 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2944 newAdmin.testOnlyAdmin =
2945 (existingAdmin != null) ? existingAdmin.testOnlyAdmin
2946 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
2947 policy.mAdminMap.put(adminReceiver, newAdmin);
2948 int replaceIndex = -1;
2949 final int N = policy.mAdminList.size();
2950 for (int i=0; i < N; i++) {
2951 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2952 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2957 if (replaceIndex == -1) {
2958 policy.mAdminList.add(newAdmin);
2959 enableIfNecessary(info.getPackageName(), userHandle);
2961 policy.mAdminList.set(replaceIndex, newAdmin);
2963 saveSettingsLocked(userHandle);
2964 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2965 onEnableData, null);
2967 mInjector.binderRestoreCallingIdentity(ident);
2973 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2977 enforceFullCrossUsersPermission(userHandle);
2978 synchronized (this) {
2979 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2984 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2988 enforceFullCrossUsersPermission(userHandle);
2989 synchronized (this) {
2990 DevicePolicyData policyData = getUserData(userHandle);
2991 return policyData.mRemovingAdmins.contains(adminReceiver);
2996 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
3000 enforceFullCrossUsersPermission(userHandle);
3001 synchronized (this) {
3002 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3003 if (administrator == null) {
3004 throw new SecurityException("No active admin " + adminReceiver);
3006 return administrator.info.usesPolicy(policyId);
3011 @SuppressWarnings("unchecked")
3012 public List<ComponentName> getActiveAdmins(int userHandle) {
3014 return Collections.EMPTY_LIST;
3017 enforceFullCrossUsersPermission(userHandle);
3018 synchronized (this) {
3019 DevicePolicyData policy = getUserData(userHandle);
3020 final int N = policy.mAdminList.size();
3024 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3025 for (int i=0; i<N; i++) {
3026 res.add(policy.mAdminList.get(i).info.getComponent());
3033 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
3037 enforceFullCrossUsersPermission(userHandle);
3038 synchronized (this) {
3039 DevicePolicyData policy = getUserData(userHandle);
3040 final int N = policy.mAdminList.size();
3041 for (int i=0; i<N; i++) {
3042 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
3050 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
3054 Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
3055 enforceShell("forceRemoveActiveAdmin");
3056 long ident = mInjector.binderClearCallingIdentity();
3058 synchronized (this) {
3059 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
3060 throw new SecurityException("Attempt to remove non-test admin "
3061 + adminReceiver + " " + userHandle);
3064 // If admin is a device or profile owner tidy that up first.
3065 if (isDeviceOwner(adminReceiver, userHandle)) {
3066 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3068 if (isProfileOwner(adminReceiver, userHandle)) {
3069 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3070 userHandle, /* parent */ false);
3071 clearProfileOwnerLocked(admin, userHandle);
3074 // Remove the admin skipping sending the broadcast.
3075 removeAdminArtifacts(adminReceiver, userHandle);
3076 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3078 mInjector.binderRestoreCallingIdentity(ident);
3083 * Return if a given package has testOnly="true", in which case we'll relax certain rules
3086 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked}
3087 * to check wehter an active admin is test-only or not.
3089 * The system allows this flag to be changed when an app is updated, which is not good
3090 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3091 * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3093 private boolean isPackageTestOnly(String packageName, int userHandle) {
3094 final ApplicationInfo ai;
3096 ai = mIPackageManager.getApplicationInfo(packageName,
3097 (PackageManager.MATCH_DIRECT_BOOT_AWARE
3098 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3099 } catch (RemoteException e) {
3100 throw new IllegalStateException(e);
3103 throw new IllegalStateException("Couldn't find package: "
3104 + packageName + " on user " + userHandle);
3106 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3110 * See {@link #isPackageTestOnly}.
3112 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3113 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3114 return (admin != null) && admin.testOnlyAdmin;
3117 private void enforceShell(String method) {
3118 final int callingUid = Binder.getCallingUid();
3119 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3120 throw new SecurityException("Non-shell user attempted to call " + method);
3125 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3129 enforceFullCrossUsersPermission(userHandle);
3130 enforceUserUnlocked(userHandle);
3131 synchronized (this) {
3132 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3133 if (admin == null) {
3136 // Active device/profile owners must remain active admins.
3137 if (isDeviceOwner(adminReceiver, userHandle)
3138 || isProfileOwner(adminReceiver, userHandle)) {
3139 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3143 if (admin.getUid() != mInjector.binderGetCallingUid()) {
3144 mContext.enforceCallingOrSelfPermission(
3145 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3147 long ident = mInjector.binderClearCallingIdentity();
3149 removeActiveAdminLocked(adminReceiver, userHandle);
3151 mInjector.binderRestoreCallingIdentity(ident);
3157 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3158 ComponentName profileOwner = getProfileOwner(userHandle);
3159 // Profile challenge is supported on N or newer release.
3160 return profileOwner != null &&
3161 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3165 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3169 Preconditions.checkNotNull(who, "ComponentName is null");
3170 validateQualityConstant(quality);
3172 synchronized (this) {
3173 ActiveAdmin ap = getActiveAdminForCallerLocked(
3174 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3175 if (ap.passwordQuality != quality) {
3176 ap.passwordQuality = quality;
3177 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3183 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3185 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3187 enforceFullCrossUsersPermission(userHandle);
3188 synchronized (this) {
3189 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3192 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3193 return admin != null ? admin.passwordQuality : mode;
3196 // Return the strictest policy across all participating admins.
3197 List<ActiveAdmin> admins =
3198 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3199 final int N = admins.size();
3200 for (int i = 0; i < N; i++) {
3201 ActiveAdmin admin = admins.get(i);
3202 if (mode < admin.passwordQuality) {
3203 mode = admin.passwordQuality;
3210 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3211 int userHandle, boolean parent) {
3212 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3213 // If this user has a separate challenge, only return its restrictions.
3214 return getUserDataUnchecked(userHandle).mAdminList;
3216 // Return all admins for this user and the profiles that are visible from this
3217 // user that do not use a separate work challenge.
3218 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3219 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3220 DevicePolicyData policy = getUserData(userInfo.id);
3221 if (!userInfo.isManagedProfile()) {
3222 admins.addAll(policy.mAdminList);
3224 // For managed profiles, we always include the policies set on the parent
3225 // profile. Additionally, we include the ones set on the managed profile
3226 // if no separate challenge is in place.
3227 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3228 final int N = policy.mAdminList.size();
3229 for (int i = 0; i < N; i++) {
3230 ActiveAdmin admin = policy.mAdminList.get(i);
3231 if (admin.hasParentActiveAdmin()) {
3232 admins.add(admin.getParentActiveAdmin());
3234 if (!hasSeparateChallenge) {
3244 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3245 long ident = mInjector.binderClearCallingIdentity();
3247 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3249 mInjector.binderRestoreCallingIdentity(ident);
3254 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3258 Preconditions.checkNotNull(who, "ComponentName is null");
3259 synchronized (this) {
3260 ActiveAdmin ap = getActiveAdminForCallerLocked(
3261 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3262 if (ap.minimumPasswordLength != length) {
3263 ap.minimumPasswordLength = length;
3264 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3270 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3274 enforceFullCrossUsersPermission(userHandle);
3275 synchronized (this) {
3279 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3280 return admin != null ? admin.minimumPasswordLength : length;
3283 // Return the strictest policy across all participating admins.
3284 List<ActiveAdmin> admins =
3285 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3286 final int N = admins.size();
3287 for (int i = 0; i < N; i++) {
3288 ActiveAdmin admin = admins.get(i);
3289 if (length < admin.minimumPasswordLength) {
3290 length = admin.minimumPasswordLength;
3298 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3302 Preconditions.checkNotNull(who, "ComponentName is null");
3303 synchronized (this) {
3304 ActiveAdmin ap = getActiveAdminForCallerLocked(
3305 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3306 if (ap.passwordHistoryLength != length) {
3307 ap.passwordHistoryLength = length;
3308 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3314 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3318 enforceFullCrossUsersPermission(userHandle);
3319 synchronized (this) {
3323 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3324 return admin != null ? admin.passwordHistoryLength : length;
3327 // Return the strictest policy across all participating admins.
3328 List<ActiveAdmin> admins =
3329 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3330 final int N = admins.size();
3331 for (int i = 0; i < N; i++) {
3332 ActiveAdmin admin = admins.get(i);
3333 if (length < admin.passwordHistoryLength) {
3334 length = admin.passwordHistoryLength;
3343 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3347 Preconditions.checkNotNull(who, "ComponentName is null");
3348 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3349 final int userHandle = mInjector.userHandleGetCallingUserId();
3350 synchronized (this) {
3351 ActiveAdmin ap = getActiveAdminForCallerLocked(
3352 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3353 // Calling this API automatically bumps the expiration date
3354 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3355 ap.passwordExpirationDate = expiration;
3356 ap.passwordExpirationTimeout = timeout;
3358 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3359 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3360 .format(new Date(expiration)));
3362 saveSettingsLocked(userHandle);
3364 // in case this is the first one, set the alarm on the appropriate user.
3365 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3370 * Return a single admin's expiration cycle time, or the min of all cycle times.
3371 * Returns 0 if not configured.
3374 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3378 enforceFullCrossUsersPermission(userHandle);
3379 synchronized (this) {
3383 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3384 return admin != null ? admin.passwordExpirationTimeout : timeout;
3387 // Return the strictest policy across all participating admins.
3388 List<ActiveAdmin> admins =
3389 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3390 final int N = admins.size();
3391 for (int i = 0; i < N; i++) {
3392 ActiveAdmin admin = admins.get(i);
3393 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3394 && timeout > admin.passwordExpirationTimeout)) {
3395 timeout = admin.passwordExpirationTimeout;
3403 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3404 final int userId = UserHandle.getCallingUserId();
3405 List<String> changedProviders = null;
3407 synchronized (this) {
3408 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3409 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3410 if (activeAdmin.crossProfileWidgetProviders == null) {
3411 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3413 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3414 if (!providers.contains(packageName)) {
3415 providers.add(packageName);
3416 changedProviders = new ArrayList<>(providers);
3417 saveSettingsLocked(userId);
3421 if (changedProviders != null) {
3422 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3430 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3431 final int userId = UserHandle.getCallingUserId();
3432 List<String> changedProviders = null;
3434 synchronized (this) {
3435 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3436 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3437 if (activeAdmin.crossProfileWidgetProviders == null) {
3440 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3441 if (providers.remove(packageName)) {
3442 changedProviders = new ArrayList<>(providers);
3443 saveSettingsLocked(userId);
3447 if (changedProviders != null) {
3448 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3456 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3457 synchronized (this) {
3458 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3459 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3460 if (activeAdmin.crossProfileWidgetProviders == null
3461 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3464 if (mInjector.binderIsCallingUidMyUid()) {
3465 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3467 return activeAdmin.crossProfileWidgetProviders;
3473 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3474 * Returns 0 if not configured.
3476 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3480 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3481 return admin != null ? admin.passwordExpirationDate : timeout;
3484 // Return the strictest policy across all participating admins.
3485 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3486 final int N = admins.size();
3487 for (int i = 0; i < N; i++) {
3488 ActiveAdmin admin = admins.get(i);
3489 if (timeout == 0L || (admin.passwordExpirationDate != 0
3490 && timeout > admin.passwordExpirationDate)) {
3491 timeout = admin.passwordExpirationDate;
3498 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3502 enforceFullCrossUsersPermission(userHandle);
3503 synchronized (this) {
3504 return getPasswordExpirationLocked(who, userHandle, parent);
3509 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3513 Preconditions.checkNotNull(who, "ComponentName is null");
3514 synchronized (this) {
3515 ActiveAdmin ap = getActiveAdminForCallerLocked(
3516 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3517 if (ap.minimumPasswordUpperCase != length) {
3518 ap.minimumPasswordUpperCase = length;
3519 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3525 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3529 enforceFullCrossUsersPermission(userHandle);
3530 synchronized (this) {
3534 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3535 return admin != null ? admin.minimumPasswordUpperCase : length;
3538 // Return the strictest policy across all participating admins.
3539 List<ActiveAdmin> admins =
3540 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3541 final int N = admins.size();
3542 for (int i = 0; i < N; i++) {
3543 ActiveAdmin admin = admins.get(i);
3544 if (length < admin.minimumPasswordUpperCase) {
3545 length = admin.minimumPasswordUpperCase;
3553 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3554 Preconditions.checkNotNull(who, "ComponentName is null");
3555 synchronized (this) {
3556 ActiveAdmin ap = getActiveAdminForCallerLocked(
3557 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3558 if (ap.minimumPasswordLowerCase != length) {
3559 ap.minimumPasswordLowerCase = length;
3560 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3566 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3570 enforceFullCrossUsersPermission(userHandle);
3571 synchronized (this) {
3575 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3576 return admin != null ? admin.minimumPasswordLowerCase : length;
3579 // Return the strictest policy across all participating admins.
3580 List<ActiveAdmin> admins =
3581 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3582 final int N = admins.size();
3583 for (int i = 0; i < N; i++) {
3584 ActiveAdmin admin = admins.get(i);
3585 if (length < admin.minimumPasswordLowerCase) {
3586 length = admin.minimumPasswordLowerCase;
3594 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3598 Preconditions.checkNotNull(who, "ComponentName is null");
3599 synchronized (this) {
3600 ActiveAdmin ap = getActiveAdminForCallerLocked(
3601 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3602 if (ap.minimumPasswordLetters != length) {
3603 ap.minimumPasswordLetters = length;
3604 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3610 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3614 enforceFullCrossUsersPermission(userHandle);
3615 synchronized (this) {
3619 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3620 return admin != null ? admin.minimumPasswordLetters : length;
3623 // Return the strictest policy across all participating admins.
3624 List<ActiveAdmin> admins =
3625 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3626 final int N = admins.size();
3627 for (int i = 0; i < N; i++) {
3628 ActiveAdmin admin = admins.get(i);
3629 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3632 if (length < admin.minimumPasswordLetters) {
3633 length = admin.minimumPasswordLetters;
3641 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3645 Preconditions.checkNotNull(who, "ComponentName is null");
3646 synchronized (this) {
3647 ActiveAdmin ap = getActiveAdminForCallerLocked(
3648 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3649 if (ap.minimumPasswordNumeric != length) {
3650 ap.minimumPasswordNumeric = length;
3651 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3657 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3661 enforceFullCrossUsersPermission(userHandle);
3662 synchronized (this) {
3666 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3667 return admin != null ? admin.minimumPasswordNumeric : length;
3670 // Return the strictest policy across all participating admins.
3671 List<ActiveAdmin> admins =
3672 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3673 final int N = admins.size();
3674 for (int i = 0; i < N; i++) {
3675 ActiveAdmin admin = admins.get(i);
3676 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3679 if (length < admin.minimumPasswordNumeric) {
3680 length = admin.minimumPasswordNumeric;
3688 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3692 Preconditions.checkNotNull(who, "ComponentName is null");
3693 synchronized (this) {
3694 ActiveAdmin ap = getActiveAdminForCallerLocked(
3695 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3696 if (ap.minimumPasswordSymbols != length) {
3697 ap.minimumPasswordSymbols = length;
3698 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3704 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3708 enforceFullCrossUsersPermission(userHandle);
3709 synchronized (this) {
3713 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3714 return admin != null ? admin.minimumPasswordSymbols : length;
3717 // Return the strictest policy across all participating admins.
3718 List<ActiveAdmin> admins =
3719 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3720 final int N = admins.size();
3721 for (int i = 0; i < N; i++) {
3722 ActiveAdmin admin = admins.get(i);
3723 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3726 if (length < admin.minimumPasswordSymbols) {
3727 length = admin.minimumPasswordSymbols;
3735 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3739 Preconditions.checkNotNull(who, "ComponentName is null");
3740 synchronized (this) {
3741 ActiveAdmin ap = getActiveAdminForCallerLocked(
3742 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3743 if (ap.minimumPasswordNonLetter != length) {
3744 ap.minimumPasswordNonLetter = length;
3745 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3751 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3755 enforceFullCrossUsersPermission(userHandle);
3756 synchronized (this) {
3760 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3761 return admin != null ? admin.minimumPasswordNonLetter : length;
3764 // Return the strictest policy across all participating admins.
3765 List<ActiveAdmin> admins =
3766 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3767 final int N = admins.size();
3768 for (int i = 0; i < N; i++) {
3769 ActiveAdmin admin = admins.get(i);
3770 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3773 if (length < admin.minimumPasswordNonLetter) {
3774 length = admin.minimumPasswordNonLetter;
3782 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3786 enforceFullCrossUsersPermission(userHandle);
3788 synchronized (this) {
3789 // This API can only be called by an active device admin,
3790 // so try to retrieve it to check that the caller is one.
3791 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3792 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3793 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3798 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3802 enforceFullCrossUsersPermission(userHandle);
3803 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3805 synchronized (this) {
3806 int targetUser = getProfileParentId(userHandle);
3807 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3808 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3812 private boolean isActivePasswordSufficientForUserLocked(
3813 DevicePolicyData policy, int userHandle, boolean parent) {
3814 enforceUserUnlocked(userHandle, parent);
3816 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
3817 if (policy.mActivePasswordQuality < requiredPasswordQuality) {
3820 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
3821 && policy.mActivePasswordLength < getPasswordMinimumLength(
3822 null, userHandle, parent)) {
3825 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3828 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3829 null, userHandle, parent)
3830 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3831 null, userHandle, parent)
3832 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3833 null, userHandle, parent)
3834 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3835 null, userHandle, parent)
3836 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3837 null, userHandle, parent)
3838 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3839 null, userHandle, parent);
3843 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3844 enforceFullCrossUsersPermission(userHandle);
3845 synchronized (this) {
3846 if (!isCallerWithSystemUid()) {
3847 // This API can only be called by an active device admin,
3848 // so try to retrieve it to check that the caller is one.
3849 getActiveAdminForCallerLocked(
3850 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3853 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3855 return policy.mFailedPasswordAttempts;
3860 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3864 Preconditions.checkNotNull(who, "ComponentName is null");
3865 synchronized (this) {
3866 // This API can only be called by an active device admin,
3867 // so try to retrieve it to check that the caller is one.
3868 getActiveAdminForCallerLocked(
3869 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3870 ActiveAdmin ap = getActiveAdminForCallerLocked(
3871 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3872 if (ap.maximumFailedPasswordsForWipe != num) {
3873 ap.maximumFailedPasswordsForWipe = num;
3874 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3880 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3884 enforceFullCrossUsersPermission(userHandle);
3885 synchronized (this) {
3886 ActiveAdmin admin = (who != null)
3887 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3888 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3889 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3894 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3896 return UserHandle.USER_NULL;
3898 enforceFullCrossUsersPermission(userHandle);
3899 synchronized (this) {
3900 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3901 userHandle, parent);
3902 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3907 * Returns the admin with the strictest policy on maximum failed passwords for:
3909 * <li>this user if it has a separate profile challenge, or
3910 * <li>this user and all profiles that don't have their own challenge otherwise.
3912 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3913 * the primary profile.
3914 * Returns {@code null} if no participating admin has that policy set.
3916 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3917 int userHandle, boolean parent) {
3919 ActiveAdmin strictestAdmin = null;
3921 // Return the strictest policy across all participating admins.
3922 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3923 final int N = admins.size();
3924 for (int i = 0; i < N; i++) {
3925 ActiveAdmin admin = admins.get(i);
3926 if (admin.maximumFailedPasswordsForWipe ==
3927 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3928 continue; // No max number of failed passwords policy set for this profile.
3931 // We always favor the primary profile if several profiles have the same value set.
3932 int userId = admin.getUserHandle().getIdentifier();
3934 count > admin.maximumFailedPasswordsForWipe ||
3935 (count == admin.maximumFailedPasswordsForWipe &&
3936 getUserInfo(userId).isPrimary())) {
3937 count = admin.maximumFailedPasswordsForWipe;
3938 strictestAdmin = admin;
3941 return strictestAdmin;
3944 private UserInfo getUserInfo(@UserIdInt int userId) {
3945 final long token = mInjector.binderClearCallingIdentity();
3947 return mUserManager.getUserInfo(userId);
3949 mInjector.binderRestoreCallingIdentity(token);
3954 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3958 final int callingUid = mInjector.binderGetCallingUid();
3959 final int userHandle = mInjector.userHandleGetCallingUserId();
3961 String password = passwordOrNull != null ? passwordOrNull : "";
3963 // Password resetting to empty/null is not allowed for managed profiles.
3964 if (TextUtils.isEmpty(password)) {
3965 enforceNotManagedProfile(userHandle, "clear the active password");
3969 synchronized (this) {
3970 // If caller has PO (or DO) it can change the password, so see if that's the case first.
3971 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3972 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3974 if (admin != null) {
3975 preN = getTargetSdk(admin.info.getPackageName(),
3976 userHandle) <= android.os.Build.VERSION_CODES.M;
3978 // Otherwise, make sure the caller has any active admin with the right policy.
3979 admin = getActiveAdminForCallerLocked(null,
3980 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3981 preN = getTargetSdk(admin.info.getPackageName(),
3982 userHandle) <= android.os.Build.VERSION_CODES.M;
3984 // As of N, password resetting to empty/null is not allowed anymore.
3985 // TODO Should we allow DO/PO to set an empty password?
3986 if (TextUtils.isEmpty(password)) {
3988 throw new SecurityException("Cannot call with null password");
3990 Slog.e(LOG_TAG, "Cannot call with null password");
3994 // As of N, password cannot be changed by the admin if it is already set.
3995 if (isLockScreenSecureUnchecked(userHandle)) {
3997 throw new SecurityException("Admin cannot change current password");
3999 Slog.e(LOG_TAG, "Admin cannot change current password");
4004 // Do not allow to reset password when current user has a managed profile
4005 if (!isManagedProfile(userHandle)) {
4006 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4007 if (userInfo.isManagedProfile()) {
4009 throw new IllegalStateException(
4010 "Cannot reset password on user has managed profile");
4012 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
4018 // Do not allow to reset password when user is locked
4019 if (!mUserManager.isUserUnlocked(userHandle)) {
4021 throw new IllegalStateException("Cannot reset password when user is locked");
4023 Slog.e(LOG_TAG, "Cannot reset password when user is locked");
4028 quality = getPasswordQuality(null, userHandle, /* parent */ false);
4029 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
4030 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4032 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
4033 int realQuality = LockPatternUtils.computePasswordQuality(password);
4034 if (realQuality < quality
4035 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4036 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
4037 + Integer.toHexString(realQuality)
4038 + " does not meet required quality 0x"
4039 + Integer.toHexString(quality));
4042 quality = Math.max(realQuality, quality);
4044 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
4045 if (password.length() < length) {
4046 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
4047 + " does not meet required length " + length);
4050 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4057 for (int i = 0; i < password.length(); i++) {
4058 char c = password.charAt(i);
4059 if (c >= 'A' && c <= 'Z') {
4062 } else if (c >= 'a' && c <= 'z') {
4065 } else if (c >= '0' && c <= '9') {
4073 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4074 if(letters < neededLetters) {
4075 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
4076 + " does not meet required number of letters " + neededLetters);
4079 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4080 if (numbers < neededNumbers) {
4081 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
4082 + " does not meet required number of numerical digits "
4086 int neededLowerCase = getPasswordMinimumLowerCase(
4087 null, userHandle, /* parent */ false);
4088 if (lowercase < neededLowerCase) {
4089 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
4090 + " does not meet required number of lowercase letters "
4094 int neededUpperCase = getPasswordMinimumUpperCase(
4095 null, userHandle, /* parent */ false);
4096 if (uppercase < neededUpperCase) {
4097 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
4098 + " does not meet required number of uppercase letters "
4102 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4103 if (symbols < neededSymbols) {
4104 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
4105 + " does not meet required number of special symbols " + neededSymbols);
4108 int neededNonLetter = getPasswordMinimumNonLetter(
4109 null, userHandle, /* parent */ false);
4110 if (nonletter < neededNonLetter) {
4111 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
4112 + " does not meet required number of non-letter characters "
4119 DevicePolicyData policy = getUserData(userHandle);
4120 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4121 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4125 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4126 boolean doNotAskCredentialsOnBoot =
4127 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4128 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4129 setDoNotAskCredentialsOnBoot();
4132 // Don't do this with the lock held, because it is going to call
4133 // back in to the service.
4134 final long ident = mInjector.binderClearCallingIdentity();
4136 if (!TextUtils.isEmpty(password)) {
4137 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4139 mLockPatternUtils.clearLock(userHandle);
4141 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4143 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4144 UserHandle.USER_ALL);
4146 synchronized (this) {
4147 int newOwner = requireEntry ? callingUid : -1;
4148 if (policy.mPasswordOwner != newOwner) {
4149 policy.mPasswordOwner = newOwner;
4150 saveSettingsLocked(userHandle);
4154 mInjector.binderRestoreCallingIdentity(ident);
4160 private boolean isLockScreenSecureUnchecked(int userId) {
4161 long ident = mInjector.binderClearCallingIdentity();
4163 return mLockPatternUtils.isSecure(userId);
4165 mInjector.binderRestoreCallingIdentity(ident);
4169 private void setDoNotAskCredentialsOnBoot() {
4170 synchronized (this) {
4171 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4172 if (!policyData.doNotAskCredentialsOnBoot) {
4173 policyData.doNotAskCredentialsOnBoot = true;
4174 saveSettingsLocked(UserHandle.USER_SYSTEM);
4180 public boolean getDoNotAskCredentialsOnBoot() {
4181 mContext.enforceCallingOrSelfPermission(
4182 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4183 synchronized (this) {
4184 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4185 return policyData.doNotAskCredentialsOnBoot;
4190 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4194 Preconditions.checkNotNull(who, "ComponentName is null");
4195 final int userHandle = mInjector.userHandleGetCallingUserId();
4196 synchronized (this) {
4197 ActiveAdmin ap = getActiveAdminForCallerLocked(
4198 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4199 if (ap.maximumTimeToUnlock != timeMs) {
4200 ap.maximumTimeToUnlock = timeMs;
4201 saveSettingsLocked(userHandle);
4202 updateMaximumTimeToLockLocked(userHandle);
4207 void updateMaximumTimeToLockLocked(int userHandle) {
4208 // Calculate the min timeout for all profiles - including the ones with a separate
4209 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4210 // challenge only and keep the screen on. However there is no easy way of doing that at the
4211 // moment so we set the screen off timeout regardless of whether it affects the parent user
4212 // or the profile challenge only.
4213 long timeMs = Long.MAX_VALUE;
4214 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4215 for (int profileId : profileIds) {
4216 DevicePolicyData policy = getUserDataUnchecked(profileId);
4217 final int N = policy.mAdminList.size();
4218 for (int i = 0; i < N; i++) {
4219 ActiveAdmin admin = policy.mAdminList.get(i);
4220 if (admin.maximumTimeToUnlock > 0
4221 && timeMs > admin.maximumTimeToUnlock) {
4222 timeMs = admin.maximumTimeToUnlock;
4224 // If userInfo.id is a managed profile, we also need to look at
4225 // the policies set on the parent.
4226 if (admin.hasParentActiveAdmin()) {
4227 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4228 if (parentAdmin.maximumTimeToUnlock > 0
4229 && timeMs > parentAdmin.maximumTimeToUnlock) {
4230 timeMs = parentAdmin.maximumTimeToUnlock;
4236 // We only store the last maximum time to lock on the parent profile. So if calling from a
4237 // managed profile, retrieve the policy for the parent.
4238 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4239 if (policy.mLastMaximumTimeToLock == timeMs) {
4242 policy.mLastMaximumTimeToLock = timeMs;
4244 final long ident = mInjector.binderClearCallingIdentity();
4246 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4247 // Make sure KEEP_SCREEN_ON is disabled, since that
4248 // would allow bypassing of the maximum time to lock.
4249 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4252 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4253 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4255 mInjector.binderRestoreCallingIdentity(ident);
4260 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4264 enforceFullCrossUsersPermission(userHandle);
4265 synchronized (this) {
4267 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4268 return admin != null ? admin.maximumTimeToUnlock : 0;
4270 // Return the strictest policy across all participating admins.
4271 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4272 userHandle, parent);
4273 return getMaximumTimeToLockPolicyFromAdmins(admins);
4278 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4282 enforceFullCrossUsersPermission(userHandle);
4283 synchronized (this) {
4284 // All admins for this user.
4285 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4286 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4287 DevicePolicyData policy = getUserData(userInfo.id);
4288 admins.addAll(policy.mAdminList);
4289 // If it is a managed profile, it may have parent active admins
4290 if (userInfo.isManagedProfile()) {
4291 for (ActiveAdmin admin : policy.mAdminList) {
4292 if (admin.hasParentActiveAdmin()) {
4293 admins.add(admin.getParentActiveAdmin());
4298 return getMaximumTimeToLockPolicyFromAdmins(admins);
4302 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4304 final int N = admins.size();
4305 for (int i = 0; i < N; i++) {
4306 ActiveAdmin admin = admins.get(i);
4308 time = admin.maximumTimeToUnlock;
4309 } else if (admin.maximumTimeToUnlock != 0
4310 && time > admin.maximumTimeToUnlock) {
4311 time = admin.maximumTimeToUnlock;
4318 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
4323 Preconditions.checkNotNull(who, "ComponentName is null");
4324 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
4325 // timeoutMs with value 0 means that the admin doesn't participate
4326 // timeoutMs is clamped to the interval in case the internal constants change in the future
4327 if (timeoutMs != 0 && timeoutMs < MINIMUM_STRONG_AUTH_TIMEOUT_MS) {
4328 timeoutMs = MINIMUM_STRONG_AUTH_TIMEOUT_MS;
4330 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
4331 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4334 final int userHandle = mInjector.userHandleGetCallingUserId();
4335 synchronized (this) {
4336 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4337 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4338 if (ap.strongAuthUnlockTimeout != timeoutMs) {
4339 ap.strongAuthUnlockTimeout = timeoutMs;
4340 saveSettingsLocked(userHandle);
4346 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
4347 * admins if who is null.
4348 * Returns 0 if not configured for the provided admin.
4351 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
4353 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4355 enforceFullCrossUsersPermission(userId);
4356 synchronized (this) {
4358 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
4359 return admin != null ? admin.strongAuthUnlockTimeout : 0;
4362 // Return the strictest policy across all participating admins.
4363 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
4365 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4366 for (int i = 0; i < admins.size(); i++) {
4367 final long timeout = admins.get(i).strongAuthUnlockTimeout;
4368 if (timeout != 0) { // take only participating admins into account
4369 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
4372 return Math.max(strongAuthUnlockTimeout, MINIMUM_STRONG_AUTH_TIMEOUT_MS);
4377 public void lockNow(boolean parent) {
4381 synchronized (this) {
4382 // This API can only be called by an active device admin,
4383 // so try to retrieve it to check that the caller is one.
4384 getActiveAdminForCallerLocked(
4385 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4387 int userToLock = mInjector.userHandleGetCallingUserId();
4389 // Unless this is a managed profile with work challenge enabled, lock all users.
4390 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4391 userToLock = UserHandle.USER_ALL;
4393 final long ident = mInjector.binderClearCallingIdentity();
4395 mLockPatternUtils.requireStrongAuth(
4396 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4397 if (userToLock == UserHandle.USER_ALL) {
4398 // Power off the display
4399 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4400 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4401 mInjector.getIWindowManager().lockNow(null);
4403 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4405 } catch (RemoteException e) {
4407 mInjector.binderRestoreCallingIdentity(ident);
4413 public void enforceCanManageCaCerts(ComponentName who) {
4415 if (!isCallerDelegatedCertInstaller()) {
4416 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4419 synchronized (this) {
4420 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4425 private void enforceCanManageInstalledKeys(ComponentName who) {
4427 if (!isCallerDelegatedCertInstaller()) {
4428 throw new SecurityException("who == null, but caller is not cert installer");
4431 synchronized (this) {
4432 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4437 private boolean isCallerDelegatedCertInstaller() {
4438 final int callingUid = mInjector.binderGetCallingUid();
4439 final int userHandle = UserHandle.getUserId(callingUid);
4440 synchronized (this) {
4441 final DevicePolicyData policy = getUserData(userHandle);
4442 if (policy.mDelegatedCertInstallerPackage == null) {
4447 int uid = mContext.getPackageManager().getPackageUidAsUser(
4448 policy.mDelegatedCertInstallerPackage, userHandle);
4449 return uid == callingUid;
4450 } catch (NameNotFoundException e) {
4457 public boolean approveCaCert(String alias, int userId, boolean approval) {
4458 enforceManageUsers();
4459 synchronized (this) {
4460 Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4461 boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4465 saveSettingsLocked(userId);
4467 new MonitoringCertNotificationTask().execute(userId);
4472 public boolean isCaCertApproved(String alias, int userId) {
4473 enforceManageUsers();
4474 synchronized (this) {
4475 return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4479 private void removeCaApprovalsIfNeeded(int userId) {
4480 for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4481 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4482 if (userInfo.isManagedProfile()){
4483 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4486 synchronized (this) {
4487 getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4488 saveSettingsLocked(userInfo.id);
4491 new MonitoringCertNotificationTask().execute(userInfo.id);
4497 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4498 enforceCanManageCaCerts(admin);
4502 X509Certificate cert = parseCert(certBuffer);
4503 pemCert = Credentials.convertToPem(cert);
4504 } catch (CertificateException ce) {
4505 Log.e(LOG_TAG, "Problem converting cert", ce);
4507 } catch (IOException ioe) {
4508 Log.e(LOG_TAG, "Problem reading cert", ioe);
4512 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4513 final long id = mInjector.binderClearCallingIdentity();
4515 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4517 keyChainConnection.getService().installCaCertificate(pemCert);
4519 } catch (RemoteException e) {
4520 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4522 keyChainConnection.close();
4524 } catch (InterruptedException e1) {
4525 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4526 Thread.currentThread().interrupt();
4528 mInjector.binderRestoreCallingIdentity(id);
4533 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4534 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4535 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4540 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4541 enforceCanManageCaCerts(admin);
4543 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4544 final long id = mInjector.binderClearCallingIdentity();
4546 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4548 for (int i = 0 ; i < aliases.length; i++) {
4549 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4551 } catch (RemoteException e) {
4552 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4554 keyChainConnection.close();
4556 } catch (InterruptedException ie) {
4557 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4558 Thread.currentThread().interrupt();
4560 mInjector.binderRestoreCallingIdentity(id);
4565 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4566 String alias, boolean requestAccess) {
4567 enforceCanManageInstalledKeys(who);
4569 final int callingUid = mInjector.binderGetCallingUid();
4570 final long id = mInjector.binderClearCallingIdentity();
4572 final KeyChainConnection keyChainConnection =
4573 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4575 IKeyChainService keyChain = keyChainConnection.getService();
4576 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4579 if (requestAccess) {
4580 keyChain.setGrant(callingUid, alias, true);
4583 } catch (RemoteException e) {
4584 Log.e(LOG_TAG, "Installing certificate", e);
4586 keyChainConnection.close();
4588 } catch (InterruptedException e) {
4589 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4590 Thread.currentThread().interrupt();
4592 mInjector.binderRestoreCallingIdentity(id);
4598 public boolean removeKeyPair(ComponentName who, String alias) {
4599 enforceCanManageInstalledKeys(who);
4601 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4602 final long id = Binder.clearCallingIdentity();
4604 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4606 IKeyChainService keyChain = keyChainConnection.getService();
4607 return keyChain.removeKeyPair(alias);
4608 } catch (RemoteException e) {
4609 Log.e(LOG_TAG, "Removing keypair", e);
4611 keyChainConnection.close();
4613 } catch (InterruptedException e) {
4614 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4615 Thread.currentThread().interrupt();
4617 Binder.restoreCallingIdentity(id);
4623 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4624 final IBinder response) {
4625 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4626 if (!isCallerWithSystemUid()) {
4630 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4631 // If there is a profile owner, redirect to that; otherwise query the device owner.
4632 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4633 if (aliasChooser == null && caller.isSystem()) {
4634 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4635 if (deviceOwnerAdmin != null) {
4636 aliasChooser = deviceOwnerAdmin.info.getComponent();
4639 if (aliasChooser == null) {
4640 sendPrivateKeyAliasResponse(null, response);
4644 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4645 intent.setComponent(aliasChooser);
4646 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4647 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4648 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4649 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4650 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4652 final long id = mInjector.binderClearCallingIdentity();
4654 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4656 public void onReceive(Context context, Intent intent) {
4657 final String chosenAlias = getResultData();
4658 sendPrivateKeyAliasResponse(chosenAlias, response);
4660 }, null, Activity.RESULT_OK, null, null);
4662 mInjector.binderRestoreCallingIdentity(id);
4666 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4667 final IKeyChainAliasCallback keyChainAliasResponse =
4668 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4669 new AsyncTask<Void, Void, Void>() {
4671 protected Void doInBackground(Void... unused) {
4673 keyChainAliasResponse.alias(alias);
4674 } catch (Exception e) {
4675 // Catch everything (not just RemoteException): caller could throw a
4676 // RuntimeException back across processes.
4677 Log.e(LOG_TAG, "error while responding to callback", e);
4685 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4686 throws SecurityException {
4687 int userHandle = UserHandle.getCallingUserId();
4688 synchronized (this) {
4689 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4690 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4691 if (installerPackage != null &&
4692 !isPackageInstalledForUser(installerPackage, userHandle)) {
4693 throw new IllegalArgumentException("Package " + installerPackage
4694 + " is not installed on the current user");
4697 DevicePolicyData policy = getUserData(userHandle);
4698 policy.mDelegatedCertInstallerPackage = installerPackage;
4699 saveSettingsLocked(userHandle);
4704 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4705 int userHandle = UserHandle.getCallingUserId();
4706 synchronized (this) {
4707 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4708 DevicePolicyData policy = getUserData(userHandle);
4709 return policy.mDelegatedCertInstallerPackage;
4714 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4715 * not installed and therefore not available.
4717 * @throws SecurityException if the caller is not a profile or device owner.
4718 * @throws UnsupportedOperationException if the package does not support being set as always-on.
4721 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4722 throws SecurityException {
4723 synchronized (this) {
4724 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4727 final int userId = mInjector.userHandleGetCallingUserId();
4728 final long token = mInjector.binderClearCallingIdentity();
4730 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4733 ConnectivityManager connectivityManager = (ConnectivityManager)
4734 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4735 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4736 throw new UnsupportedOperationException();
4739 mInjector.binderRestoreCallingIdentity(token);
4745 public String getAlwaysOnVpnPackage(ComponentName admin)
4746 throws SecurityException {
4747 synchronized (this) {
4748 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4751 final int userId = mInjector.userHandleGetCallingUserId();
4752 final long token = mInjector.binderClearCallingIdentity();
4754 ConnectivityManager connectivityManager = (ConnectivityManager)
4755 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4756 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4758 mInjector.binderRestoreCallingIdentity(token);
4762 private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
4763 if (wipeExtRequested) {
4764 StorageManager sm = (StorageManager) mContext.getSystemService(
4765 Context.STORAGE_SERVICE);
4766 sm.wipeAdoptableDisks();
4769 RecoverySystem.rebootWipeUserData(mContext, reason);
4770 } catch (IOException | SecurityException e) {
4771 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4776 public void wipeData(int flags) {
4780 final int userHandle = mInjector.userHandleGetCallingUserId();
4781 enforceFullCrossUsersPermission(userHandle);
4783 final String source;
4784 synchronized (this) {
4785 // This API can only be called by an active device admin,
4786 // so try to retrieve it to check that the caller is one.
4787 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4788 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4789 source = admin.info.getComponent().flattenToShortString();
4791 long ident = mInjector.binderClearCallingIdentity();
4793 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4794 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4795 throw new SecurityException(
4796 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4798 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4799 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4800 if (manager != null) {
4805 mInjector.binderRestoreCallingIdentity(ident);
4808 final boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4809 wipeDeviceNoLock(wipeExtRequested, userHandle,
4810 "DevicePolicyManager.wipeData() from " + source);
4813 private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
4814 final long ident = mInjector.binderClearCallingIdentity();
4816 if (userHandle == UserHandle.USER_SYSTEM) {
4817 wipeDataNoLock(wipeExtRequested, reason);
4819 mHandler.post(new Runnable() {
4823 IActivityManager am = mInjector.getIActivityManager();
4824 if (am.getCurrentUser().id == userHandle) {
4825 am.switchUser(UserHandle.USER_SYSTEM);
4828 boolean isManagedProfile = isManagedProfile(userHandle);
4829 if (!mUserManager.removeUser(userHandle)) {
4830 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4831 } else if (isManagedProfile) {
4832 sendWipeProfileNotification();
4834 } catch (RemoteException re) {
4841 mInjector.binderRestoreCallingIdentity(ident);
4845 private void sendWipeProfileNotification() {
4846 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4847 Notification notification = new Notification.Builder(mContext)
4848 .setSmallIcon(android.R.drawable.stat_sys_warning)
4849 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4850 .setContentText(contentText)
4851 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4852 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4854 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4857 private void clearWipeProfileNotification() {
4858 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4862 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4866 enforceFullCrossUsersPermission(userHandle);
4867 mContext.enforceCallingOrSelfPermission(
4868 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4870 synchronized (this) {
4871 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4872 if (admin == null) {
4873 result.sendResult(null);
4876 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4877 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4878 intent.setComponent(admin.info.getComponent());
4879 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4880 null, new BroadcastReceiver() {
4882 public void onReceive(Context context, Intent intent) {
4883 result.sendResult(getResultExtras(false));
4885 }, null, Activity.RESULT_OK, null, null);
4890 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4891 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4895 enforceFullCrossUsersPermission(userHandle);
4896 mContext.enforceCallingOrSelfPermission(
4897 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4899 // If the managed profile doesn't have a separate password, set the metrics to default
4900 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
4901 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4911 validateQualityConstant(quality);
4912 DevicePolicyData policy = getUserData(userHandle);
4913 synchronized (this) {
4914 policy.mActivePasswordQuality = quality;
4915 policy.mActivePasswordLength = length;
4916 policy.mActivePasswordLetters = letters;
4917 policy.mActivePasswordLowerCase = lowercase;
4918 policy.mActivePasswordUpperCase = uppercase;
4919 policy.mActivePasswordNumeric = numbers;
4920 policy.mActivePasswordSymbols = symbols;
4921 policy.mActivePasswordNonLetter = nonletter;
4926 public void reportPasswordChanged(int userId) {
4930 enforceFullCrossUsersPermission(userId);
4932 // Managed Profile password can only be changed when it has a separate challenge.
4933 if (!isSeparateProfileChallengeEnabled(userId)) {
4934 enforceNotManagedProfile(userId, "set the active password");
4937 mContext.enforceCallingOrSelfPermission(
4938 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4940 DevicePolicyData policy = getUserData(userId);
4942 long ident = mInjector.binderClearCallingIdentity();
4944 synchronized (this) {
4945 policy.mFailedPasswordAttempts = 0;
4946 saveSettingsLocked(userId);
4947 updatePasswordExpirationsLocked(userId);
4948 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
4950 // Send a broadcast to each profile using this password as its primary unlock.
4951 sendAdminCommandForLockscreenPoliciesLocked(
4952 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4953 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
4955 removeCaApprovalsIfNeeded(userId);
4957 mInjector.binderRestoreCallingIdentity(ident);
4962 * Called any time the device password is updated. Resets all password expiration clocks.
4964 private void updatePasswordExpirationsLocked(int userHandle) {
4965 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4966 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4967 userHandle, /* parent */ false);
4968 final int N = admins.size();
4969 for (int i = 0; i < N; i++) {
4970 ActiveAdmin admin = admins.get(i);
4971 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4972 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4973 long timeout = admin.passwordExpirationTimeout;
4974 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4975 admin.passwordExpirationDate = expiration;
4978 for (int affectedUserId : affectedUserIds) {
4979 saveSettingsLocked(affectedUserId);
4984 public void reportFailedPasswordAttempt(int userHandle) {
4985 enforceFullCrossUsersPermission(userHandle);
4986 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4987 enforceNotManagedProfile(userHandle,
4988 "report failed password attempt if separate profile challenge is not in place");
4990 mContext.enforceCallingOrSelfPermission(
4991 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4993 final long ident = mInjector.binderClearCallingIdentity();
4995 boolean wipeData = false;
4997 synchronized (this) {
4998 DevicePolicyData policy = getUserData(userHandle);
4999 policy.mFailedPasswordAttempts++;
5000 saveSettingsLocked(userHandle);
5002 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
5003 userHandle, /* parent */ false);
5004 int max = strictestAdmin != null
5005 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
5006 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
5007 // Wipe the user/profile associated with the policy that was violated. This
5008 // is not necessarily calling user: if the policy that fired was from a
5009 // managed profile rather than the main user profile, we wipe former only.
5011 identifier = strictestAdmin.getUserHandle().getIdentifier();
5014 sendAdminCommandForLockscreenPoliciesLocked(
5015 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
5016 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5020 // Call without holding lock.
5021 wipeDeviceNoLock(false, identifier,
5022 "reportFailedPasswordAttempt()");
5025 mInjector.binderRestoreCallingIdentity(ident);
5028 if (mInjector.securityLogIsLoggingEnabled()) {
5029 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5030 /*method strength*/ 1);
5035 public void reportSuccessfulPasswordAttempt(int userHandle) {
5036 enforceFullCrossUsersPermission(userHandle);
5037 mContext.enforceCallingOrSelfPermission(
5038 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5040 synchronized (this) {
5041 DevicePolicyData policy = getUserData(userHandle);
5042 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
5043 long ident = mInjector.binderClearCallingIdentity();
5045 policy.mFailedPasswordAttempts = 0;
5046 policy.mPasswordOwner = -1;
5047 saveSettingsLocked(userHandle);
5049 sendAdminCommandForLockscreenPoliciesLocked(
5050 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
5051 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5054 mInjector.binderRestoreCallingIdentity(ident);
5059 if (mInjector.securityLogIsLoggingEnabled()) {
5060 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5061 /*method strength*/ 1);
5066 public void reportFailedFingerprintAttempt(int userHandle) {
5067 enforceFullCrossUsersPermission(userHandle);
5068 mContext.enforceCallingOrSelfPermission(
5069 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5070 if (mInjector.securityLogIsLoggingEnabled()) {
5071 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5072 /*method strength*/ 0);
5077 public void reportSuccessfulFingerprintAttempt(int userHandle) {
5078 enforceFullCrossUsersPermission(userHandle);
5079 mContext.enforceCallingOrSelfPermission(
5080 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5081 if (mInjector.securityLogIsLoggingEnabled()) {
5082 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5083 /*method strength*/ 0);
5088 public void reportKeyguardDismissed(int userHandle) {
5089 enforceFullCrossUsersPermission(userHandle);
5090 mContext.enforceCallingOrSelfPermission(
5091 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5093 if (mInjector.securityLogIsLoggingEnabled()) {
5094 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
5099 public void reportKeyguardSecured(int userHandle) {
5100 enforceFullCrossUsersPermission(userHandle);
5101 mContext.enforceCallingOrSelfPermission(
5102 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5104 if (mInjector.securityLogIsLoggingEnabled()) {
5105 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
5110 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
5111 String exclusionList) {
5115 synchronized(this) {
5116 Preconditions.checkNotNull(who, "ComponentName is null");
5118 // Only check if system user has set global proxy. We don't allow other users to set it.
5119 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5120 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5121 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
5123 // Scan through active admins and find if anyone has already
5124 // set the global proxy.
5125 Set<ComponentName> compSet = policy.mAdminMap.keySet();
5126 for (ComponentName component : compSet) {
5127 ActiveAdmin ap = policy.mAdminMap.get(component);
5128 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
5129 // Another admin already sets the global proxy
5130 // Return it to the caller.
5135 // If the user is not system, don't set the global proxy. Fail silently.
5136 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
5137 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
5138 + UserHandle.getCallingUserId() + " is not permitted.");
5141 if (proxySpec == null) {
5142 admin.specifiesGlobalProxy = false;
5143 admin.globalProxySpec = null;
5144 admin.globalProxyExclusionList = null;
5147 admin.specifiesGlobalProxy = true;
5148 admin.globalProxySpec = proxySpec;
5149 admin.globalProxyExclusionList = exclusionList;
5152 // Reset the global proxy accordingly
5153 // Do this using system permissions, as apps cannot write to secure settings
5154 long origId = mInjector.binderClearCallingIdentity();
5156 resetGlobalProxyLocked(policy);
5158 mInjector.binderRestoreCallingIdentity(origId);
5165 public ComponentName getGlobalProxyAdmin(int userHandle) {
5169 enforceFullCrossUsersPermission(userHandle);
5170 synchronized(this) {
5171 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5172 // Scan through active admins and find if anyone has already
5173 // set the global proxy.
5174 final int N = policy.mAdminList.size();
5175 for (int i = 0; i < N; i++) {
5176 ActiveAdmin ap = policy.mAdminList.get(i);
5177 if (ap.specifiesGlobalProxy) {
5178 // Device admin sets the global proxy
5179 // Return it to the caller.
5180 return ap.info.getComponent();
5184 // No device admin sets the global proxy.
5189 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5190 synchronized (this) {
5191 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5193 long token = mInjector.binderClearCallingIdentity();
5195 ConnectivityManager connectivityManager = (ConnectivityManager)
5196 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5197 connectivityManager.setGlobalProxy(proxyInfo);
5199 mInjector.binderRestoreCallingIdentity(token);
5203 private void resetGlobalProxyLocked(DevicePolicyData policy) {
5204 final int N = policy.mAdminList.size();
5205 for (int i = 0; i < N; i++) {
5206 ActiveAdmin ap = policy.mAdminList.get(i);
5207 if (ap.specifiesGlobalProxy) {
5208 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5212 // No device admins defining global proxies - reset global proxy settings to none
5213 saveGlobalProxyLocked(null, null);
5216 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5217 if (exclusionList == null) {
5220 if (proxySpec == null) {
5223 // Remove white spaces
5224 proxySpec = proxySpec.trim();
5225 String data[] = proxySpec.split(":");
5226 int proxyPort = 8080;
5227 if (data.length > 1) {
5229 proxyPort = Integer.parseInt(data[1]);
5230 } catch (NumberFormatException e) {}
5232 exclusionList = exclusionList.trim();
5234 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5235 if (!proxyProperties.isValid()) {
5236 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5239 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5240 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5241 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5246 * Set the storage encryption request for a single admin. Returns the new total request
5247 * status (for all admins).
5250 public int setStorageEncryption(ComponentName who, boolean encrypt) {
5252 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5254 Preconditions.checkNotNull(who, "ComponentName is null");
5255 final int userHandle = UserHandle.getCallingUserId();
5256 synchronized (this) {
5257 // Check for permissions
5258 // Only system user can set storage encryption
5259 if (userHandle != UserHandle.USER_SYSTEM) {
5260 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5261 + UserHandle.getCallingUserId() + " is not permitted.");
5265 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5266 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5268 // Quick exit: If the filesystem does not support encryption, we can exit early.
5269 if (!isEncryptionSupported()) {
5270 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5273 // (1) Record the value for the admin so it's sticky
5274 if (ap.encryptionRequested != encrypt) {
5275 ap.encryptionRequested = encrypt;
5276 saveSettingsLocked(userHandle);
5279 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5280 // (2) Compute "max" for all admins
5281 boolean newRequested = false;
5282 final int N = policy.mAdminList.size();
5283 for (int i = 0; i < N; i++) {
5284 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5287 // Notify OS of new request
5288 setEncryptionRequested(newRequested);
5290 // Return the new global request status
5292 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5293 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5298 * Get the current storage encryption request status for a given admin, or aggregate of all
5302 public boolean getStorageEncryption(ComponentName who, int userHandle) {
5306 enforceFullCrossUsersPermission(userHandle);
5307 synchronized (this) {
5308 // Check for permissions if a particular caller is specified
5310 // When checking for a single caller, status is based on caller's request
5311 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5312 return ap != null ? ap.encryptionRequested : false;
5315 // If no particular caller is specified, return the aggregate set of requests.
5316 // This is short circuited by returning true on the first hit.
5317 DevicePolicyData policy = getUserData(userHandle);
5318 final int N = policy.mAdminList.size();
5319 for (int i = 0; i < N; i++) {
5320 if (policy.mAdminList.get(i).encryptionRequested) {
5329 * Get the current encryption status of the device.
5332 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5334 // Ok to return current status.
5336 enforceFullCrossUsersPermission(userHandle);
5338 // It's not critical here, but let's make sure the package name is correct, in case
5339 // we start using it for different purposes.
5340 ensureCallerPackage(callerPackage);
5342 final ApplicationInfo ai;
5344 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5345 } catch (RemoteException e) {
5346 throw new SecurityException(e);
5349 boolean legacyApp = false;
5350 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5354 final int rawStatus = getEncryptionStatus();
5355 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5356 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5362 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
5364 private boolean isEncryptionSupported() {
5365 // Note, this can be implemented as
5366 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5367 // But is provided as a separate internal method if there's a faster way to do a
5368 // simple check for supported-or-not.
5369 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5373 * Hook to low-levels: Reporting the current status of encryption.
5374 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5375 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5376 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5377 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5378 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5380 private int getEncryptionStatus() {
5381 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5382 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5383 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5384 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5385 } else if (mInjector.storageManagerIsEncrypted()) {
5386 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5387 } else if (mInjector.storageManagerIsEncryptable()) {
5388 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5390 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5395 * Hook to low-levels: If needed, record the new admin setting for encryption.
5397 private void setEncryptionRequested(boolean encrypt) {
5401 * Set whether the screen capture is disabled for the user managed by the specified admin.
5404 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5408 Preconditions.checkNotNull(who, "ComponentName is null");
5409 final int userHandle = UserHandle.getCallingUserId();
5410 synchronized (this) {
5411 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5412 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5413 if (ap.disableScreenCapture != disabled) {
5414 ap.disableScreenCapture = disabled;
5415 saveSettingsLocked(userHandle);
5416 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5422 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5423 * active admin (if given admin is null).
5426 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5430 synchronized (this) {
5432 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5433 return (admin != null) ? admin.disableScreenCapture : false;
5436 DevicePolicyData policy = getUserData(userHandle);
5437 final int N = policy.mAdminList.size();
5438 for (int i = 0; i < N; i++) {
5439 ActiveAdmin admin = policy.mAdminList.get(i);
5440 if (admin.disableScreenCapture) {
5448 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5449 final boolean disabled) {
5450 mHandler.post(new Runnable() {
5454 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5455 } catch (RemoteException e) {
5456 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5463 * Set whether auto time is required by the specified admin (must be device owner).
5466 public void setAutoTimeRequired(ComponentName who, boolean required) {
5470 Preconditions.checkNotNull(who, "ComponentName is null");
5471 final int userHandle = UserHandle.getCallingUserId();
5472 synchronized (this) {
5473 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5474 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5475 if (admin.requireAutoTime != required) {
5476 admin.requireAutoTime = required;
5477 saveSettingsLocked(userHandle);
5481 // Turn AUTO_TIME on in settings if it is required
5483 long ident = mInjector.binderClearCallingIdentity();
5485 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5487 mInjector.binderRestoreCallingIdentity(ident);
5493 * Returns whether or not auto time is required by the device owner.
5496 public boolean getAutoTimeRequired() {
5500 synchronized (this) {
5501 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5502 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5507 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5511 Preconditions.checkNotNull(who, "ComponentName is null");
5512 // Allow setting this policy to true only if there is a split system user.
5513 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5514 throw new UnsupportedOperationException(
5515 "Cannot force ephemeral users on systems without split system user.");
5517 boolean removeAllUsers = false;
5518 synchronized (this) {
5519 final ActiveAdmin deviceOwner =
5520 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5521 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5522 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5523 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5524 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5525 removeAllUsers = forceEphemeralUsers;
5528 if (removeAllUsers) {
5529 long identitity = mInjector.binderClearCallingIdentity();
5531 mUserManagerInternal.removeAllUsers();
5533 mInjector.binderRestoreCallingIdentity(identitity);
5539 public boolean getForceEphemeralUsers(ComponentName who) {
5543 Preconditions.checkNotNull(who, "ComponentName is null");
5544 synchronized (this) {
5545 final ActiveAdmin deviceOwner =
5546 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5547 return deviceOwner.forceEphemeralUsers;
5551 private boolean isDeviceOwnerManagedSingleUserDevice() {
5552 synchronized (this) {
5553 if (!mOwners.hasDeviceOwner()) {
5557 final long callingIdentity = mInjector.binderClearCallingIdentity();
5559 if (mInjector.userManagerIsSplitSystemUser()) {
5560 // In split system user mode, only allow the case where the device owner is managing
5561 // the only non-system user of the device
5562 return (mUserManager.getUserCount() == 2
5563 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5565 return mUserManager.getUserCount() == 1;
5568 mInjector.binderRestoreCallingIdentity(callingIdentity);
5572 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5573 synchronized (this) {
5574 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5576 if (!isDeviceOwnerManagedSingleUserDevice()) {
5577 throw new SecurityException(
5578 "There should only be one user, managed by Device Owner");
5583 public boolean requestBugreport(ComponentName who) {
5587 Preconditions.checkNotNull(who, "ComponentName is null");
5588 ensureDeviceOwnerManagingSingleUser(who);
5590 if (mRemoteBugreportServiceIsActive.get()
5591 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5592 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5596 final long callingIdentity = mInjector.binderClearCallingIdentity();
5598 ActivityManagerNative.getDefault().requestBugReport(
5599 ActivityManager.BUGREPORT_OPTION_REMOTE);
5601 mRemoteBugreportServiceIsActive.set(true);
5602 mRemoteBugreportSharingAccepted.set(false);
5603 registerRemoteBugreportReceivers();
5604 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5605 RemoteBugreportUtils.buildNotification(mContext,
5606 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5607 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5608 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5610 } catch (RemoteException re) {
5611 // should never happen
5612 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5615 mInjector.binderRestoreCallingIdentity(callingIdentity);
5619 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5620 Intent intent = new Intent(action);
5621 intent.setComponent(mOwners.getDeviceOwnerComponent());
5622 if (extras != null) {
5623 intent.putExtras(extras);
5625 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5628 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5629 return mOwners.getDeviceOwnerRemoteBugreportUri();
5632 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5633 String bugreportHash) {
5634 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5637 private void registerRemoteBugreportReceivers() {
5639 IntentFilter filterFinished = new IntentFilter(
5640 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5641 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5642 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5643 } catch (IntentFilter.MalformedMimeTypeException e) {
5644 // should never happen, as setting a constant
5645 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5647 IntentFilter filterConsent = new IntentFilter();
5648 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5649 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5650 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5653 private void onBugreportFinished(Intent intent) {
5654 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5655 mRemoteBugreportServiceIsActive.set(false);
5656 Uri bugreportUri = intent.getData();
5657 String bugreportUriString = null;
5658 if (bugreportUri != null) {
5659 bugreportUriString = bugreportUri.toString();
5661 String bugreportHash = intent.getStringExtra(
5662 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5663 if (mRemoteBugreportSharingAccepted.get()) {
5664 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5665 mInjector.getNotificationManager().cancel(LOG_TAG,
5666 RemoteBugreportUtils.NOTIFICATION_ID);
5668 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5669 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5670 RemoteBugreportUtils.buildNotification(mContext,
5671 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5674 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5677 private void onBugreportFailed() {
5678 mRemoteBugreportServiceIsActive.set(false);
5679 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5680 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5681 mRemoteBugreportSharingAccepted.set(false);
5682 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5683 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5684 Bundle extras = new Bundle();
5685 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5686 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5687 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5688 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5689 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5692 private void onBugreportSharingAccepted() {
5693 mRemoteBugreportSharingAccepted.set(true);
5694 String bugreportUriString = null;
5695 String bugreportHash = null;
5696 synchronized (this) {
5697 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5698 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5700 if (bugreportUriString != null) {
5701 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5702 } else if (mRemoteBugreportServiceIsActive.get()) {
5703 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5704 RemoteBugreportUtils.buildNotification(mContext,
5705 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5710 private void onBugreportSharingDeclined() {
5711 if (mRemoteBugreportServiceIsActive.get()) {
5712 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5713 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5714 mRemoteBugreportServiceIsActive.set(false);
5715 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5716 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5718 mRemoteBugreportSharingAccepted.set(false);
5719 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5720 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5723 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5724 String bugreportHash) {
5725 ParcelFileDescriptor pfd = null;
5727 if (bugreportUriString == null) {
5728 throw new FileNotFoundException();
5730 Uri bugreportUri = Uri.parse(bugreportUriString);
5731 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5733 synchronized (this) {
5734 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5735 intent.setComponent(mOwners.getDeviceOwnerComponent());
5736 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5737 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5738 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
5740 LocalServices.getService(ActivityManagerInternal.class)
5741 .grantUriPermissionFromIntent(Process.SHELL_UID,
5742 mOwners.getDeviceOwnerComponent().getPackageName(),
5743 intent, mOwners.getDeviceOwnerUserId());
5744 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5746 } catch (FileNotFoundException e) {
5747 Bundle extras = new Bundle();
5748 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5749 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5750 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5756 } catch (IOException ex) {
5759 mRemoteBugreportSharingAccepted.set(false);
5760 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5765 * Disables all device cameras according to the specified admin.
5768 public void setCameraDisabled(ComponentName who, boolean disabled) {
5772 Preconditions.checkNotNull(who, "ComponentName is null");
5773 final int userHandle = mInjector.userHandleGetCallingUserId();
5774 synchronized (this) {
5775 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5776 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5777 if (ap.disableCamera != disabled) {
5778 ap.disableCamera = disabled;
5779 saveSettingsLocked(userHandle);
5782 // Tell the user manager that the restrictions have changed.
5783 pushUserRestrictions(userHandle);
5787 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5791 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5792 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5795 private boolean getCameraDisabled(ComponentName who, int userHandle,
5796 boolean mergeDeviceOwnerRestriction) {
5800 synchronized (this) {
5802 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5803 return (admin != null) ? admin.disableCamera : false;
5805 // First, see if DO has set it. If so, it's device-wide.
5806 if (mergeDeviceOwnerRestriction) {
5807 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5808 if (deviceOwner != null && deviceOwner.disableCamera) {
5813 // Then check each device admin on the user.
5814 DevicePolicyData policy = getUserData(userHandle);
5815 // Determine whether or not the device camera is disabled for any active admins.
5816 final int N = policy.mAdminList.size();
5817 for (int i = 0; i < N; i++) {
5818 ActiveAdmin admin = policy.mAdminList.get(i);
5819 if (admin.disableCamera) {
5828 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5832 Preconditions.checkNotNull(who, "ComponentName is null");
5833 final int userHandle = mInjector.userHandleGetCallingUserId();
5834 if (isManagedProfile(userHandle)) {
5836 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5838 which = which & PROFILE_KEYGUARD_FEATURES;
5841 synchronized (this) {
5842 ActiveAdmin ap = getActiveAdminForCallerLocked(
5843 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5844 if (ap.disabledKeyguardFeatures != which) {
5845 ap.disabledKeyguardFeatures = which;
5846 saveSettingsLocked(userHandle);
5852 * Gets the disabled state for features in keyguard for the given admin,
5853 * or the aggregate of all active admins if who is null.
5856 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5860 enforceFullCrossUsersPermission(userHandle);
5861 final long ident = mInjector.binderClearCallingIdentity();
5863 synchronized (this) {
5865 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5866 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5869 final List<ActiveAdmin> admins;
5870 if (!parent && isManagedProfile(userHandle)) {
5871 // If we are being asked about a managed profile, just return keyguard features
5872 // disabled by admins in the profile.
5873 admins = getUserDataUnchecked(userHandle).mAdminList;
5875 // Otherwise return those set by admins in the user and its profiles.
5876 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5879 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5880 final int N = admins.size();
5881 for (int i = 0; i < N; i++) {
5882 ActiveAdmin admin = admins.get(i);
5883 int userId = admin.getUserHandle().getIdentifier();
5884 boolean isRequestedUser = !parent && (userId == userHandle);
5885 if (isRequestedUser || !isManagedProfile(userId)) {
5886 // If we are being asked explicitly about this user
5887 // return all disabled features even if its a managed profile.
5888 which |= admin.disabledKeyguardFeatures;
5890 // Otherwise a managed profile is only allowed to disable
5891 // some features on the parent user.
5892 which |= (admin.disabledKeyguardFeatures
5893 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5899 mInjector.binderRestoreCallingIdentity(ident);
5904 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5908 Preconditions.checkNotNull(who, "ComponentName is null");
5909 Preconditions.checkNotNull(packageList, "packageList is null");
5910 final int userHandle = UserHandle.getCallingUserId();
5911 synchronized (this) {
5912 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5913 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5914 admin.keepUninstalledPackages = packageList;
5915 saveSettingsLocked(userHandle);
5916 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5921 public List<String> getKeepUninstalledPackages(ComponentName who) {
5922 Preconditions.checkNotNull(who, "ComponentName is null");
5926 // TODO In split system user mode, allow apps on user 0 to query the list
5927 synchronized (this) {
5928 // Check if this is the device owner who is calling
5929 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5930 return getKeepUninstalledPackagesLocked();
5934 private List<String> getKeepUninstalledPackagesLocked() {
5935 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5936 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5940 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5945 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5946 throw new IllegalArgumentException("Invalid component " + admin
5947 + " for device owner");
5949 final boolean hasIncompatibleAccountsOrNonAdb =
5950 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin);
5951 synchronized (this) {
5952 enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb);
5953 if (getActiveAdminUncheckedLocked(admin, userId) == null
5954 || getUserData(userId).mRemovingAdmins.contains(admin)) {
5955 throw new IllegalArgumentException("Not active admin: " + admin);
5958 // Shutting down backup manager service permanently.
5959 long ident = mInjector.binderClearCallingIdentity();
5961 if (mInjector.getIBackupManager() != null) {
5962 mInjector.getIBackupManager()
5963 .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5965 } catch (RemoteException e) {
5966 throw new IllegalStateException("Failed deactivating backup service.", e);
5968 mInjector.binderRestoreCallingIdentity(ident);
5971 mOwners.setDeviceOwner(admin, ownerName, userId);
5972 mOwners.writeDeviceOwner();
5973 updateDeviceOwnerLocked();
5974 setDeviceOwnerSystemPropertyLocked();
5975 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5977 ident = mInjector.binderClearCallingIdentity();
5979 // TODO Send to system too?
5980 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5982 mInjector.binderRestoreCallingIdentity(ident);
5984 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
5989 public boolean isDeviceOwner(ComponentName who, int userId) {
5990 synchronized (this) {
5991 return mOwners.hasDeviceOwner()
5992 && mOwners.getDeviceOwnerUserId() == userId
5993 && mOwners.getDeviceOwnerComponent().equals(who);
5997 public boolean isProfileOwner(ComponentName who, int userId) {
5998 final ComponentName profileOwner = getProfileOwner(userId);
5999 return who != null && who.equals(profileOwner);
6003 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
6007 if (!callingUserOnly) {
6008 enforceManageUsers();
6010 synchronized (this) {
6011 if (!mOwners.hasDeviceOwner()) {
6014 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
6015 mOwners.getDeviceOwnerUserId()) {
6018 return mOwners.getDeviceOwnerComponent();
6023 public int getDeviceOwnerUserId() {
6025 return UserHandle.USER_NULL;
6027 enforceManageUsers();
6028 synchronized (this) {
6029 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
6034 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
6038 public String getDeviceOwnerName() {
6042 enforceManageUsers();
6043 synchronized (this) {
6044 if (!mOwners.hasDeviceOwner()) {
6047 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
6048 // Should setDeviceOwner/ProfileOwner still take a name?
6049 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
6050 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
6054 // Returns the active device owner or null if there is no device owner.
6056 ActiveAdmin getDeviceOwnerAdminLocked() {
6057 ComponentName component = mOwners.getDeviceOwnerComponent();
6058 if (component == null) {
6062 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
6063 final int n = policy.mAdminList.size();
6064 for (int i = 0; i < n; i++) {
6065 ActiveAdmin admin = policy.mAdminList.get(i);
6066 if (component.equals(admin.info.getComponent())) {
6070 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
6075 public void clearDeviceOwner(String packageName) {
6076 Preconditions.checkNotNull(packageName, "packageName is null");
6077 final int callingUid = mInjector.binderGetCallingUid();
6079 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
6080 UserHandle.getUserId(callingUid));
6081 if (uid != callingUid) {
6082 throw new SecurityException("Invalid packageName");
6084 } catch (NameNotFoundException e) {
6085 throw new SecurityException(e);
6087 synchronized (this) {
6088 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6089 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6090 if (!mOwners.hasDeviceOwner()
6091 || !deviceOwnerComponent.getPackageName().equals(packageName)
6092 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
6093 throw new SecurityException(
6094 "clearDeviceOwner can only be called by the device owner");
6096 enforceUserUnlocked(deviceOwnerUserId);
6098 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
6099 long ident = mInjector.binderClearCallingIdentity();
6101 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
6102 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
6104 mInjector.binderRestoreCallingIdentity(ident);
6106 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
6110 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
6111 if (admin != null) {
6112 admin.disableCamera = false;
6113 admin.userRestrictions = null;
6114 admin.forceEphemeralUsers = false;
6115 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
6117 clearUserPoliciesLocked(userId);
6119 mOwners.clearDeviceOwner();
6120 mOwners.writeDeviceOwner();
6121 updateDeviceOwnerLocked();
6122 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
6124 if (mInjector.getIBackupManager() != null) {
6125 // Reactivate backup service.
6126 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6128 } catch (RemoteException e) {
6129 throw new IllegalStateException("Failed reactivating backup service.", e);
6134 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6139 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6140 throw new IllegalArgumentException("Component " + who
6141 + " not installed for userId:" + userHandle);
6143 final boolean hasIncompatibleAccountsOrNonAdb =
6144 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who);
6145 synchronized (this) {
6146 enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb);
6148 if (getActiveAdminUncheckedLocked(who, userHandle) == null
6149 || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6150 throw new IllegalArgumentException("Not active admin: " + who);
6153 mOwners.setProfileOwner(who, ownerName, userHandle);
6154 mOwners.writeProfileOwner(userHandle);
6155 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6161 public void clearProfileOwner(ComponentName who) {
6165 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
6166 final int userId = callingUser.getIdentifier();
6167 enforceNotManagedProfile(userId, "clear profile owner");
6168 enforceUserUnlocked(userId);
6169 // Check if this is the profile owner who is calling
6170 final ActiveAdmin admin =
6171 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6172 synchronized (this) {
6173 final long ident = mInjector.binderClearCallingIdentity();
6175 clearProfileOwnerLocked(admin, userId);
6176 removeActiveAdminLocked(who, userId);
6178 mInjector.binderRestoreCallingIdentity(ident);
6180 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6184 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6185 if (admin != null) {
6186 admin.disableCamera = false;
6187 admin.userRestrictions = null;
6189 clearUserPoliciesLocked(userId);
6190 mOwners.removeProfileOwner(userId);
6191 mOwners.writeProfileOwner(userId);
6195 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6196 Preconditions.checkNotNull(who, "ComponentName is null");
6201 synchronized (this) {
6202 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6203 long token = mInjector.binderClearCallingIdentity();
6205 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6207 mInjector.binderRestoreCallingIdentity(token);
6213 public CharSequence getDeviceOwnerLockScreenInfo() {
6214 return mLockPatternUtils.getDeviceOwnerInfo();
6217 private void clearUserPoliciesLocked(int userId) {
6218 // Reset some of the user-specific policies
6219 DevicePolicyData policy = getUserData(userId);
6220 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6221 policy.mDelegatedCertInstallerPackage = null;
6222 policy.mApplicationRestrictionsManagingPackage = null;
6223 policy.mStatusBarDisabled = false;
6224 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6225 saveSettingsLocked(userId);
6228 mIPackageManager.updatePermissionFlagsForAllApps(
6229 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6230 0 /* flagValues */, userId);
6231 pushUserRestrictions(userId);
6232 } catch (RemoteException re) {
6233 // Shouldn't happen.
6238 public boolean hasUserSetupCompleted() {
6239 return hasUserSetupCompleted(UserHandle.getCallingUserId());
6242 // This checks only if the Setup Wizard has run. Since Wear devices pair before
6243 // completing Setup Wizard, and pairing involves transferring user data, calling
6244 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
6245 private boolean hasUserSetupCompleted(int userHandle) {
6249 return getUserData(userHandle).mUserSetupComplete;
6252 private boolean hasPaired(int userHandle) {
6256 return getUserData(userHandle).mPaired;
6260 public int getUserProvisioningState() {
6262 return DevicePolicyManager.STATE_USER_UNMANAGED;
6264 int userHandle = mInjector.userHandleGetCallingUserId();
6265 return getUserProvisioningState(userHandle);
6268 private int getUserProvisioningState(int userHandle) {
6269 return getUserData(userHandle).mUserProvisioningState;
6273 public void setUserProvisioningState(int newState, int userHandle) {
6278 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6279 && getManagedUserId(userHandle) == -1) {
6280 // No managed device, user or profile, so setting provisioning state makes no sense.
6281 throw new IllegalStateException("Not allowed to change provisioning state unless a "
6282 + "device or profile owner is set.");
6285 synchronized (this) {
6286 boolean transitionCheckNeeded = true;
6288 // Calling identity/permission checks.
6289 final int callingUid = mInjector.binderGetCallingUid();
6290 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6291 // ADB shell can only move directly from un-managed to finalized as part of directly
6292 // setting profile-owner or device-owner.
6293 if (getUserProvisioningState(userHandle) !=
6294 DevicePolicyManager.STATE_USER_UNMANAGED
6295 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6296 throw new IllegalStateException("Not allowed to change provisioning state "
6297 + "unless current provisioning state is unmanaged, and new state is "
6300 transitionCheckNeeded = false;
6302 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6303 enforceCanManageProfileAndDeviceOwners();
6306 final DevicePolicyData policyData = getUserData(userHandle);
6307 if (transitionCheckNeeded) {
6308 // Optional state transition check for non-ADB case.
6309 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6311 policyData.mUserProvisioningState = newState;
6312 saveSettingsLocked(userHandle);
6316 private void checkUserProvisioningStateTransition(int currentState, int newState) {
6317 // Valid transitions for normal use-cases.
6318 switch (currentState) {
6319 case DevicePolicyManager.STATE_USER_UNMANAGED:
6320 // Can move to any state from unmanaged (except itself as an edge case)..
6321 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6325 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6326 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6327 // Can only move to finalized from these states.
6328 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6332 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6333 // Current user has a managed-profile, but current user is not managed, so
6334 // rather than moving to finalized state, go back to unmanaged once
6335 // profile provisioning is complete.
6336 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6340 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6341 // Cannot transition out of finalized.
6345 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6346 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6347 + "from state [" + currentState + "]");
6351 public void setProfileEnabled(ComponentName who) {
6355 Preconditions.checkNotNull(who, "ComponentName is null");
6356 synchronized (this) {
6357 // Check if this is the profile owner who is calling
6358 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6359 final int userId = UserHandle.getCallingUserId();
6360 enforceManagedProfile(userId, "enable the profile");
6362 long id = mInjector.binderClearCallingIdentity();
6364 mUserManager.setUserEnabled(userId);
6365 UserInfo parent = mUserManager.getProfileParent(userId);
6366 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6367 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6368 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6369 Intent.FLAG_RECEIVER_FOREGROUND);
6370 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6372 mInjector.binderRestoreCallingIdentity(id);
6378 public void setProfileName(ComponentName who, String profileName) {
6379 Preconditions.checkNotNull(who, "ComponentName is null");
6380 int userId = UserHandle.getCallingUserId();
6381 // Check if this is the profile owner (includes device owner).
6382 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6384 long id = mInjector.binderClearCallingIdentity();
6386 mUserManager.setUserName(userId, profileName);
6388 mInjector.binderRestoreCallingIdentity(id);
6393 public ComponentName getProfileOwner(int userHandle) {
6398 synchronized (this) {
6399 return mOwners.getProfileOwnerComponent(userHandle);
6403 // Returns the active profile owner for this user or null if the current user has no
6406 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6407 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6408 if (profileOwner == null) {
6411 DevicePolicyData policy = getUserData(userHandle);
6412 final int n = policy.mAdminList.size();
6413 for (int i = 0; i < n; i++) {
6414 ActiveAdmin admin = policy.mAdminList.get(i);
6415 if (profileOwner.equals(admin.info.getComponent())) {
6423 public String getProfileOwnerName(int userHandle) {
6427 enforceManageUsers();
6428 ComponentName profileOwner = getProfileOwner(userHandle);
6429 if (profileOwner == null) {
6432 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6436 * Canonical name for a given package.
6438 private String getApplicationLabel(String packageName, int userHandle) {
6439 long token = mInjector.binderClearCallingIdentity();
6441 final Context userContext;
6443 UserHandle handle = new UserHandle(userHandle);
6444 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6445 } catch (PackageManager.NameNotFoundException nnfe) {
6446 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6449 ApplicationInfo appInfo = userContext.getApplicationInfo();
6450 CharSequence result = null;
6451 if (appInfo != null) {
6452 PackageManager pm = userContext.getPackageManager();
6453 result = pm.getApplicationLabel(appInfo);
6455 return result != null ? result.toString() : null;
6457 mInjector.binderRestoreCallingIdentity(token);
6462 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6464 * The profile owner can only be set before the user setup phase has completed,
6467 * - adb unless hasIncompatibleAccountsOrNonAdb is true.
6469 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle,
6470 boolean hasIncompatibleAccountsOrNonAdb) {
6471 UserInfo info = getUserInfo(userHandle);
6473 // User doesn't exist.
6474 throw new IllegalArgumentException(
6475 "Attempted to set profile owner for invalid userId: " + userHandle);
6477 if (info.isGuest()) {
6478 throw new IllegalStateException("Cannot set a profile owner on a guest");
6480 if (mOwners.hasProfileOwner(userHandle)) {
6481 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6482 + "is already set.");
6484 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6485 throw new IllegalStateException("Trying to set the profile owner, but the user "
6486 + "already has a device owner.");
6488 int callingUid = mInjector.binderGetCallingUid();
6489 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6490 if ((mIsWatch || hasUserSetupCompleted(userHandle))
6491 && hasIncompatibleAccountsOrNonAdb) {
6492 throw new IllegalStateException("Not allowed to set the profile owner because "
6493 + "there are already some accounts on the profile");
6497 enforceCanManageProfileAndDeviceOwners();
6498 if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
6499 throw new IllegalStateException("Cannot set the profile owner on a user which is "
6500 + "already set-up");
6505 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6508 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId,
6509 boolean hasIncompatibleAccountsOrNonAdb) {
6510 int callingUid = mInjector.binderGetCallingUid();
6511 boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6513 enforceCanManageProfileAndDeviceOwners();
6516 final int code = checkSetDeviceOwnerPreConditionLocked(owner, userId, isAdb,
6517 hasIncompatibleAccountsOrNonAdb);
6521 case CODE_HAS_DEVICE_OWNER:
6522 throw new IllegalStateException(
6523 "Trying to set the device owner, but device owner is already set.");
6524 case CODE_USER_HAS_PROFILE_OWNER:
6525 throw new IllegalStateException("Trying to set the device owner, but the user "
6526 + "already has a profile owner.");
6527 case CODE_USER_NOT_RUNNING:
6528 throw new IllegalStateException("User not running: " + userId);
6529 case CODE_NOT_SYSTEM_USER:
6530 throw new IllegalStateException("User is not system user");
6531 case CODE_USER_SETUP_COMPLETED:
6532 throw new IllegalStateException(
6533 "Cannot set the device owner if the device is already set-up");
6534 case CODE_NONSYSTEM_USER_EXISTS:
6535 throw new IllegalStateException("Not allowed to set the device owner because there "
6536 + "are already several users on the device");
6537 case CODE_ACCOUNTS_NOT_EMPTY:
6538 throw new IllegalStateException("Not allowed to set the device owner because there "
6539 + "are already some accounts on the device");
6540 case CODE_HAS_PAIRED:
6541 throw new IllegalStateException("Not allowed to set the device owner because this "
6542 + "device has already paired");
6544 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6548 private void enforceUserUnlocked(int userId) {
6549 // Since we're doing this operation on behalf of an app, we only
6550 // want to use the actual "unlocked" state.
6551 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6552 "User must be running and unlocked");
6555 private void enforceUserUnlocked(int userId, boolean parent) {
6557 enforceUserUnlocked(getProfileParentId(userId));
6559 enforceUserUnlocked(userId);
6563 private void enforceManageUsers() {
6564 final int callingUid = mInjector.binderGetCallingUid();
6565 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6566 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6570 private void enforceFullCrossUsersPermission(int userHandle) {
6571 enforceSystemUserOrPermission(userHandle,
6572 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6575 private void enforceCrossUsersPermission(int userHandle) {
6576 enforceSystemUserOrPermission(userHandle,
6577 android.Manifest.permission.INTERACT_ACROSS_USERS);
6580 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6581 if (userHandle < 0) {
6582 throw new IllegalArgumentException("Invalid userId " + userHandle);
6584 final int callingUid = mInjector.binderGetCallingUid();
6585 if (userHandle == UserHandle.getUserId(callingUid)) {
6588 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6589 mContext.enforceCallingOrSelfPermission(permission,
6590 "Must be system or have " + permission + " permission");
6594 private void enforceManagedProfile(int userHandle, String message) {
6595 if(!isManagedProfile(userHandle)) {
6596 throw new SecurityException("You can not " + message + " outside a managed profile.");
6600 private void enforceNotManagedProfile(int userHandle, String message) {
6601 if(isManagedProfile(userHandle)) {
6602 throw new SecurityException("You can not " + message + " for a managed profile.");
6606 private void enforceDeviceOwnerOrManageUsers() {
6607 synchronized (this) {
6608 if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6609 mInjector.binderGetCallingUid()) != null) {
6613 enforceManageUsers();
6616 private void ensureCallerPackage(@Nullable String packageName) {
6617 if (packageName == null) {
6618 Preconditions.checkState(isCallerWithSystemUid(),
6619 "Only caller can omit package name");
6621 final int callingUid = mInjector.binderGetCallingUid();
6622 final int userId = mInjector.userHandleGetCallingUserId();
6624 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6625 packageName, 0, userId);
6626 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6627 } catch (RemoteException e) {
6633 private boolean isCallerWithSystemUid() {
6634 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6637 private int getProfileParentId(int userHandle) {
6638 final long ident = mInjector.binderClearCallingIdentity();
6640 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6641 return parentUser != null ? parentUser.id : userHandle;
6643 mInjector.binderRestoreCallingIdentity(ident);
6647 private int getCredentialOwner(int userHandle, boolean parent) {
6648 final long ident = mInjector.binderClearCallingIdentity();
6651 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6652 if (parentProfile != null) {
6653 userHandle = parentProfile.id;
6656 return mUserManager.getCredentialOwnerProfile(userHandle);
6658 mInjector.binderRestoreCallingIdentity(ident);
6662 private boolean isManagedProfile(int userHandle) {
6663 return getUserInfo(userHandle).isManagedProfile();
6666 private void enableIfNecessary(String packageName, int userId) {
6668 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6669 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6671 if (ai.enabledSetting
6672 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6673 mIPackageManager.setApplicationEnabledSetting(packageName,
6674 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6675 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6677 } catch (RemoteException e) {
6682 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6683 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6684 != PackageManager.PERMISSION_GRANTED) {
6686 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6687 + mInjector.binderGetCallingPid()
6688 + ", uid=" + mInjector.binderGetCallingUid());
6692 synchronized (this) {
6693 pw.println("Current Device Policy Manager state:");
6694 mOwners.dump(" ", pw);
6695 int userCount = mUserData.size();
6696 for (int u = 0; u < userCount; u++) {
6697 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6699 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6700 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6701 final int N = policy.mAdminList.size();
6702 for (int i=0; i<N; i++) {
6703 ActiveAdmin ap = policy.mAdminList.get(i);
6705 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6710 if (!policy.mRemovingAdmins.isEmpty()) {
6711 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6712 + policy.mRemovingAdmins);
6716 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6719 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6723 private String getEncryptionStatusName(int encryptionStatus) {
6724 switch (encryptionStatus) {
6725 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6727 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6728 return "block default key";
6729 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6731 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6733 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6734 return "unsupported";
6735 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6736 return "activating";
6743 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6744 ComponentName activity) {
6745 Preconditions.checkNotNull(who, "ComponentName is null");
6746 final int userHandle = UserHandle.getCallingUserId();
6747 synchronized (this) {
6748 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6750 long id = mInjector.binderClearCallingIdentity();
6752 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6753 } catch (RemoteException re) {
6756 mInjector.binderRestoreCallingIdentity(id);
6762 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6763 Preconditions.checkNotNull(who, "ComponentName is null");
6764 final int userHandle = UserHandle.getCallingUserId();
6765 synchronized (this) {
6766 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6768 long id = mInjector.binderClearCallingIdentity();
6770 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6771 } catch (RemoteException re) {
6774 mInjector.binderRestoreCallingIdentity(id);
6780 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6781 String packageName) {
6782 Preconditions.checkNotNull(admin, "ComponentName is null");
6784 final int userHandle = mInjector.userHandleGetCallingUserId();
6785 synchronized (this) {
6786 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6787 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6790 DevicePolicyData policy = getUserData(userHandle);
6791 policy.mApplicationRestrictionsManagingPackage = packageName;
6792 saveSettingsLocked(userHandle);
6798 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6799 Preconditions.checkNotNull(admin, "ComponentName is null");
6801 final int userHandle = mInjector.userHandleGetCallingUserId();
6802 synchronized (this) {
6803 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6804 DevicePolicyData policy = getUserData(userHandle);
6805 return policy.mApplicationRestrictionsManagingPackage;
6810 public boolean isCallerApplicationRestrictionsManagingPackage() {
6811 final int callingUid = mInjector.binderGetCallingUid();
6812 final int userHandle = UserHandle.getUserId(callingUid);
6813 synchronized (this) {
6814 final DevicePolicyData policy = getUserData(userHandle);
6815 if (policy.mApplicationRestrictionsManagingPackage == null) {
6820 int uid = mContext.getPackageManager().getPackageUidAsUser(
6821 policy.mApplicationRestrictionsManagingPackage, userHandle);
6822 return uid == callingUid;
6823 } catch (NameNotFoundException e) {
6829 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6831 synchronized (this) {
6832 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6834 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6835 throw new SecurityException(
6836 "No admin component given, and caller cannot manage application restrictions "
6837 + "for other apps.");
6842 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6843 enforceCanManageApplicationRestrictions(who);
6845 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6846 final long id = mInjector.binderClearCallingIdentity();
6848 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6850 mInjector.binderRestoreCallingIdentity(id);
6855 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6856 PersistableBundle args, boolean parent) {
6860 Preconditions.checkNotNull(admin, "admin is null");
6861 Preconditions.checkNotNull(agent, "agent is null");
6862 final int userHandle = UserHandle.getCallingUserId();
6863 synchronized (this) {
6864 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6865 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6866 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6867 saveSettingsLocked(userHandle);
6872 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6873 ComponentName agent, int userHandle, boolean parent) {
6877 Preconditions.checkNotNull(agent, "agent null");
6878 enforceFullCrossUsersPermission(userHandle);
6880 synchronized (this) {
6881 final String componentName = agent.flattenToString();
6882 if (admin != null) {
6883 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6884 if (ap == null) return null;
6885 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6886 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6887 List<PersistableBundle> result = new ArrayList<>();
6888 result.add(trustAgentInfo.options);
6892 // Return strictest policy for this user and profiles that are visible from this user.
6893 List<PersistableBundle> result = null;
6894 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6895 // of the options. If any admin doesn't have options, discard options for the rest
6897 List<ActiveAdmin> admins =
6898 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6899 boolean allAdminsHaveOptions = true;
6900 final int N = admins.size();
6901 for (int i = 0; i < N; i++) {
6902 final ActiveAdmin active = admins.get(i);
6904 final boolean disablesTrust = (active.disabledKeyguardFeatures
6905 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6906 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6907 if (info != null && info.options != null && !info.options.isEmpty()) {
6908 if (disablesTrust) {
6909 if (result == null) {
6910 result = new ArrayList<>();
6912 result.add(info.options);
6914 Log.w(LOG_TAG, "Ignoring admin " + active.info
6915 + " because it has trust options but doesn't declare "
6916 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6918 } else if (disablesTrust) {
6919 allAdminsHaveOptions = false;
6923 return allAdminsHaveOptions ? result : null;
6928 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6929 Preconditions.checkNotNull(who, "ComponentName is null");
6930 synchronized (this) {
6931 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6933 int userHandle = UserHandle.getCallingUserId();
6934 DevicePolicyData userData = getUserData(userHandle);
6935 userData.mRestrictionsProvider = permissionProvider;
6936 saveSettingsLocked(userHandle);
6941 public ComponentName getRestrictionsProvider(int userHandle) {
6942 synchronized (this) {
6943 if (!isCallerWithSystemUid()) {
6944 throw new SecurityException("Only the system can query the permission provider");
6946 DevicePolicyData userData = getUserData(userHandle);
6947 return userData != null ? userData.mRestrictionsProvider : null;
6952 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6953 Preconditions.checkNotNull(who, "ComponentName is null");
6954 int callingUserId = UserHandle.getCallingUserId();
6955 synchronized (this) {
6956 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6958 long id = mInjector.binderClearCallingIdentity();
6960 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6961 if (parent == null) {
6962 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6966 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6967 mIPackageManager.addCrossProfileIntentFilter(
6968 filter, who.getPackageName(), callingUserId, parent.id, 0);
6970 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6971 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6972 parent.id, callingUserId, 0);
6974 } catch (RemoteException re) {
6977 mInjector.binderRestoreCallingIdentity(id);
6983 public void clearCrossProfileIntentFilters(ComponentName who) {
6984 Preconditions.checkNotNull(who, "ComponentName is null");
6985 int callingUserId = UserHandle.getCallingUserId();
6986 synchronized (this) {
6987 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6988 long id = mInjector.binderClearCallingIdentity();
6990 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6991 if (parent == null) {
6992 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6996 // Removing those that go from the managed profile to the parent.
6997 mIPackageManager.clearCrossProfileIntentFilters(
6998 callingUserId, who.getPackageName());
6999 // And those that go from the parent to the managed profile.
7000 // If we want to support multiple managed profiles, we will have to only remove
7001 // those that have callingUserId as their target.
7002 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
7003 } catch (RemoteException re) {
7006 mInjector.binderRestoreCallingIdentity(id);
7012 * @return true if all packages in enabledPackages are either in the list
7013 * permittedList or are a system app.
7015 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
7016 List<String> permittedList, int userIdToCheck) {
7017 long id = mInjector.binderClearCallingIdentity();
7019 // If we have an enabled packages list for a managed profile the packages
7020 // we should check are installed for the parent user.
7021 UserInfo user = getUserInfo(userIdToCheck);
7022 if (user.isManagedProfile()) {
7023 userIdToCheck = user.profileGroupId;
7026 for (String enabledPackage : enabledPackages) {
7027 boolean systemService = false;
7029 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
7030 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
7031 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7032 } catch (RemoteException e) {
7033 Log.i(LOG_TAG, "Can't talk to package managed", e);
7035 if (!systemService && !permittedList.contains(enabledPackage)) {
7040 mInjector.binderRestoreCallingIdentity(id);
7045 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
7046 // Not using AccessibilityManager.getInstance because that guesses
7047 // at the user you require based on callingUid and caches for a given
7049 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
7050 IAccessibilityManager service = iBinder == null
7051 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
7052 return new AccessibilityManager(mContext, service, userId);
7056 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
7060 Preconditions.checkNotNull(who, "ComponentName is null");
7062 if (packageList != null) {
7063 int userId = UserHandle.getCallingUserId();
7064 List<AccessibilityServiceInfo> enabledServices = null;
7065 long id = mInjector.binderClearCallingIdentity();
7067 UserInfo user = getUserInfo(userId);
7068 if (user.isManagedProfile()) {
7069 userId = user.profileGroupId;
7071 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
7072 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
7073 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
7075 mInjector.binderRestoreCallingIdentity(id);
7078 if (enabledServices != null) {
7079 List<String> enabledPackages = new ArrayList<String>();
7080 for (AccessibilityServiceInfo service : enabledServices) {
7081 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
7083 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7085 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
7086 + "because it contains already enabled accesibility services.");
7092 synchronized (this) {
7093 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7094 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7095 admin.permittedAccessiblityServices = packageList;
7096 saveSettingsLocked(UserHandle.getCallingUserId());
7102 public List getPermittedAccessibilityServices(ComponentName who) {
7106 Preconditions.checkNotNull(who, "ComponentName is null");
7108 synchronized (this) {
7109 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7110 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7111 return admin.permittedAccessiblityServices;
7116 public List getPermittedAccessibilityServicesForUser(int userId) {
7120 synchronized (this) {
7121 List<String> result = null;
7122 // If we have multiple profiles we return the intersection of the
7123 // permitted lists. This can happen in cases where we have a device
7124 // and profile owner.
7125 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7126 for (int profileId : profileIds) {
7127 // Just loop though all admins, only device or profiles
7128 // owners can have permitted lists set.
7129 DevicePolicyData policy = getUserDataUnchecked(profileId);
7130 final int N = policy.mAdminList.size();
7131 for (int j = 0; j < N; j++) {
7132 ActiveAdmin admin = policy.mAdminList.get(j);
7133 List<String> fromAdmin = admin.permittedAccessiblityServices;
7134 if (fromAdmin != null) {
7135 if (result == null) {
7136 result = new ArrayList<>(fromAdmin);
7138 result.retainAll(fromAdmin);
7144 // If we have a permitted list add all system accessibility services.
7145 if (result != null) {
7146 long id = mInjector.binderClearCallingIdentity();
7148 UserInfo user = getUserInfo(userId);
7149 if (user.isManagedProfile()) {
7150 userId = user.profileGroupId;
7152 AccessibilityManager accessibilityManager =
7153 getAccessibilityManagerForUser(userId);
7154 List<AccessibilityServiceInfo> installedServices =
7155 accessibilityManager.getInstalledAccessibilityServiceList();
7157 if (installedServices != null) {
7158 for (AccessibilityServiceInfo service : installedServices) {
7159 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7160 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7161 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7162 result.add(serviceInfo.packageName);
7167 mInjector.binderRestoreCallingIdentity(id);
7176 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7181 Preconditions.checkNotNull(who, "ComponentName is null");
7182 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7183 if (!isCallerWithSystemUid()){
7184 throw new SecurityException(
7185 "Only the system can query if an accessibility service is disabled by admin");
7187 synchronized (this) {
7188 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7189 if (admin == null) {
7192 if (admin.permittedAccessiblityServices == null) {
7195 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7196 admin.permittedAccessiblityServices, userHandle);
7200 private boolean checkCallerIsCurrentUserOrProfile() {
7201 int callingUserId = UserHandle.getCallingUserId();
7202 long token = mInjector.binderClearCallingIdentity();
7204 UserInfo currentUser;
7205 UserInfo callingUser = getUserInfo(callingUserId);
7207 currentUser = mInjector.getIActivityManager().getCurrentUser();
7208 } catch (RemoteException e) {
7209 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7213 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7214 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7215 + "of a user that isn't the foreground user.");
7218 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7219 Slog.e(LOG_TAG, "Cannot set permitted input methods "
7220 + "of a user that isn't the foreground user.");
7224 mInjector.binderRestoreCallingIdentity(token);
7230 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7234 Preconditions.checkNotNull(who, "ComponentName is null");
7236 // TODO When InputMethodManager supports per user calls remove
7237 // this restriction.
7238 if (!checkCallerIsCurrentUserOrProfile()) {
7242 if (packageList != null) {
7243 // InputMethodManager fetches input methods for current user.
7244 // So this can only be set when calling user is the current user
7245 // or parent is current user in case of managed profiles.
7246 InputMethodManager inputMethodManager =
7247 mContext.getSystemService(InputMethodManager.class);
7248 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7250 if (enabledImes != null) {
7251 List<String> enabledPackages = new ArrayList<String>();
7252 for (InputMethodInfo ime : enabledImes) {
7253 enabledPackages.add(ime.getPackageName());
7255 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7256 mInjector.binderGetCallingUserHandle().getIdentifier())) {
7257 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7258 + "because it contains already enabled input method.");
7264 synchronized (this) {
7265 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7266 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7267 admin.permittedInputMethods = packageList;
7268 saveSettingsLocked(UserHandle.getCallingUserId());
7274 public List getPermittedInputMethods(ComponentName who) {
7278 Preconditions.checkNotNull(who, "ComponentName is null");
7280 synchronized (this) {
7281 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7282 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7283 return admin.permittedInputMethods;
7288 public List getPermittedInputMethodsForCurrentUser() {
7289 UserInfo currentUser;
7291 currentUser = mInjector.getIActivityManager().getCurrentUser();
7292 } catch (RemoteException e) {
7293 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7294 // Activity managed is dead, just allow all IMEs
7298 int userId = currentUser.id;
7299 synchronized (this) {
7300 List<String> result = null;
7301 // If we have multiple profiles we return the intersection of the
7302 // permitted lists. This can happen in cases where we have a device
7303 // and profile owner.
7304 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7305 for (int profileId : profileIds) {
7306 // Just loop though all admins, only device or profiles
7307 // owners can have permitted lists set.
7308 DevicePolicyData policy = getUserDataUnchecked(profileId);
7309 final int N = policy.mAdminList.size();
7310 for (int j = 0; j < N; j++) {
7311 ActiveAdmin admin = policy.mAdminList.get(j);
7312 List<String> fromAdmin = admin.permittedInputMethods;
7313 if (fromAdmin != null) {
7314 if (result == null) {
7315 result = new ArrayList<String>(fromAdmin);
7317 result.retainAll(fromAdmin);
7323 // If we have a permitted list add all system input methods.
7324 if (result != null) {
7325 InputMethodManager inputMethodManager =
7326 mContext.getSystemService(InputMethodManager.class);
7327 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7328 long id = mInjector.binderClearCallingIdentity();
7331 for (InputMethodInfo ime : imes) {
7332 ServiceInfo serviceInfo = ime.getServiceInfo();
7333 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7334 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7335 result.add(serviceInfo.packageName);
7340 mInjector.binderRestoreCallingIdentity(id);
7348 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7353 Preconditions.checkNotNull(who, "ComponentName is null");
7354 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7355 if (!isCallerWithSystemUid()) {
7356 throw new SecurityException(
7357 "Only the system can query if an input method is disabled by admin");
7359 synchronized (this) {
7360 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7361 if (admin == null) {
7364 if (admin.permittedInputMethods == null) {
7367 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7368 admin.permittedInputMethods, userHandle);
7372 private void sendAdminEnabledBroadcastLocked(int userHandle) {
7373 DevicePolicyData policyData = getUserData(userHandle);
7374 if (policyData.mAdminBroadcastPending) {
7375 // Send the initialization data to profile owner and delete the data
7376 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7377 if (admin != null) {
7378 PersistableBundle initBundle = policyData.mInitBundle;
7379 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7380 initBundle == null ? null : new Bundle(initBundle), null);
7382 policyData.mInitBundle = null;
7383 policyData.mAdminBroadcastPending = false;
7384 saveSettingsLocked(userHandle);
7389 public UserHandle createAndManageUser(ComponentName admin, String name,
7390 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7391 Preconditions.checkNotNull(admin, "admin is null");
7392 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7393 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7394 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7395 + admin + " are not in the same package");
7397 // Only allow the system user to use this method
7398 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7399 throw new SecurityException("createAndManageUser was called from non-system user");
7401 if (!mInjector.userManagerIsSplitSystemUser()
7402 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7403 throw new IllegalArgumentException(
7404 "Ephemeral users are only supported on systems with a split system user.");
7407 UserHandle user = null;
7408 synchronized (this) {
7409 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7411 final long id = mInjector.binderClearCallingIdentity();
7413 int userInfoFlags = 0;
7414 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7415 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7417 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7419 if (userInfo != null) {
7420 user = userInfo.getUserHandle();
7423 mInjector.binderRestoreCallingIdentity(id);
7430 final long id = mInjector.binderClearCallingIdentity();
7432 final String adminPkg = admin.getPackageName();
7434 final int userHandle = user.getIdentifier();
7436 // Install the profile owner if not present.
7437 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7438 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7440 } catch (RemoteException e) {
7441 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7442 + "removing created user", e);
7443 mUserManager.removeUser(user.getIdentifier());
7447 setActiveAdmin(profileOwner, true, userHandle);
7448 // User is not started yet, the broadcast by setActiveAdmin will not be received.
7449 // So we store adminExtras for broadcasting when the user starts for first time.
7450 synchronized(this) {
7451 DevicePolicyData policyData = getUserData(userHandle);
7452 policyData.mInitBundle = adminExtras;
7453 policyData.mAdminBroadcastPending = true;
7454 saveSettingsLocked(userHandle);
7456 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7457 setProfileOwner(profileOwner, ownerName, userHandle);
7459 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7460 Settings.Secure.putIntForUser(mContext.getContentResolver(),
7461 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7466 mInjector.binderRestoreCallingIdentity(id);
7471 public boolean removeUser(ComponentName who, UserHandle userHandle) {
7472 Preconditions.checkNotNull(who, "ComponentName is null");
7473 synchronized (this) {
7474 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7476 long id = mInjector.binderClearCallingIdentity();
7478 return mUserManager.removeUser(userHandle.getIdentifier());
7480 mInjector.binderRestoreCallingIdentity(id);
7486 public boolean switchUser(ComponentName who, UserHandle userHandle) {
7487 Preconditions.checkNotNull(who, "ComponentName is null");
7488 synchronized (this) {
7489 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7491 long id = mInjector.binderClearCallingIdentity();
7493 int userId = UserHandle.USER_SYSTEM;
7494 if (userHandle != null) {
7495 userId = userHandle.getIdentifier();
7497 return mInjector.getIActivityManager().switchUser(userId);
7498 } catch (RemoteException e) {
7499 Log.e(LOG_TAG, "Couldn't switch user", e);
7502 mInjector.binderRestoreCallingIdentity(id);
7508 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7509 enforceCanManageApplicationRestrictions(who);
7511 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7512 final long id = mInjector.binderClearCallingIdentity();
7514 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7515 // if no restrictions were saved, mUserManager.getApplicationRestrictions
7516 // returns null, but DPM method should return an empty Bundle as per JavaDoc
7517 return bundle != null ? bundle : Bundle.EMPTY;
7519 mInjector.binderRestoreCallingIdentity(id);
7524 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7525 boolean suspended) {
7526 Preconditions.checkNotNull(who, "ComponentName is null");
7527 int callingUserId = UserHandle.getCallingUserId();
7528 synchronized (this) {
7529 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7531 long id = mInjector.binderClearCallingIdentity();
7533 return mIPackageManager.setPackagesSuspendedAsUser(
7534 packageNames, suspended, callingUserId);
7535 } catch (RemoteException re) {
7536 // Shouldn't happen.
7537 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7539 mInjector.binderRestoreCallingIdentity(id);
7541 return packageNames;
7546 public boolean isPackageSuspended(ComponentName who, String packageName) {
7547 Preconditions.checkNotNull(who, "ComponentName is null");
7548 int callingUserId = UserHandle.getCallingUserId();
7549 synchronized (this) {
7550 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7552 long id = mInjector.binderClearCallingIdentity();
7554 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7555 } catch (RemoteException re) {
7556 // Shouldn't happen.
7557 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7559 mInjector.binderRestoreCallingIdentity(id);
7566 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7567 Preconditions.checkNotNull(who, "ComponentName is null");
7568 if (!UserRestrictionsUtils.isValidRestriction(key)) {
7572 final int userHandle = mInjector.userHandleGetCallingUserId();
7573 synchronized (this) {
7574 ActiveAdmin activeAdmin =
7575 getActiveAdminForCallerLocked(who,
7576 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7577 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7578 if (isDeviceOwner) {
7579 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7580 throw new SecurityException("Device owner cannot set user restriction " + key);
7582 } else { // profile owner
7583 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7584 throw new SecurityException("Profile owner cannot set user restriction " + key);
7588 // Save the restriction to ActiveAdmin.
7589 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7590 saveSettingsLocked(userHandle);
7592 pushUserRestrictions(userHandle);
7594 sendChangedNotification(userHandle);
7598 private void pushUserRestrictions(int userId) {
7599 synchronized (this) {
7600 final Bundle global;
7601 final Bundle local = new Bundle();
7602 if (mOwners.isDeviceOwnerUserId(userId)) {
7603 global = new Bundle();
7605 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7606 if (deviceOwner == null) {
7607 return; // Shouldn't happen.
7610 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7612 // DO can disable camera globally.
7613 if (deviceOwner.disableCamera) {
7614 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7619 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7620 if (profileOwner != null) {
7621 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7624 // Also merge in *local* camera restriction.
7625 if (getCameraDisabled(/* who= */ null,
7626 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7627 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7629 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7634 public Bundle getUserRestrictions(ComponentName who) {
7638 Preconditions.checkNotNull(who, "ComponentName is null");
7639 synchronized (this) {
7640 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7641 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7642 return activeAdmin.userRestrictions;
7647 public boolean setApplicationHidden(ComponentName who, String packageName,
7649 Preconditions.checkNotNull(who, "ComponentName is null");
7650 int callingUserId = UserHandle.getCallingUserId();
7651 synchronized (this) {
7652 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7654 long id = mInjector.binderClearCallingIdentity();
7656 return mIPackageManager.setApplicationHiddenSettingAsUser(
7657 packageName, hidden, callingUserId);
7658 } catch (RemoteException re) {
7660 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7662 mInjector.binderRestoreCallingIdentity(id);
7669 public boolean isApplicationHidden(ComponentName who, String packageName) {
7670 Preconditions.checkNotNull(who, "ComponentName is null");
7671 int callingUserId = UserHandle.getCallingUserId();
7672 synchronized (this) {
7673 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7675 long id = mInjector.binderClearCallingIdentity();
7677 return mIPackageManager.getApplicationHiddenSettingAsUser(
7678 packageName, callingUserId);
7679 } catch (RemoteException re) {
7681 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7683 mInjector.binderRestoreCallingIdentity(id);
7690 public void enableSystemApp(ComponentName who, String packageName) {
7691 Preconditions.checkNotNull(who, "ComponentName is null");
7692 synchronized (this) {
7693 // This API can only be called by an active device admin,
7694 // so try to retrieve it to check that the caller is one.
7695 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7697 int userId = UserHandle.getCallingUserId();
7698 long id = mInjector.binderClearCallingIdentity();
7702 Slog.v(LOG_TAG, "installing " + packageName + " for "
7706 int parentUserId = getProfileParentId(userId);
7707 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7708 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7712 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7714 } catch (RemoteException re) {
7716 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7718 mInjector.binderRestoreCallingIdentity(id);
7724 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7725 Preconditions.checkNotNull(who, "ComponentName is null");
7726 synchronized (this) {
7727 // This API can only be called by an active device admin,
7728 // so try to retrieve it to check that the caller is one.
7729 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7731 int userId = UserHandle.getCallingUserId();
7732 long id = mInjector.binderClearCallingIdentity();
7735 int parentUserId = getProfileParentId(userId);
7736 List<ResolveInfo> activitiesToEnable = mIPackageManager
7737 .queryIntentActivities(intent,
7738 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7739 PackageManager.MATCH_DIRECT_BOOT_AWARE
7740 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7745 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7747 int numberOfAppsInstalled = 0;
7748 if (activitiesToEnable != null) {
7749 for (ResolveInfo info : activitiesToEnable) {
7750 if (info.activityInfo != null) {
7751 String packageName = info.activityInfo.packageName;
7752 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7753 numberOfAppsInstalled++;
7754 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7756 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7762 return numberOfAppsInstalled;
7763 } catch (RemoteException e) {
7765 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7768 mInjector.binderRestoreCallingIdentity(id);
7773 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7774 throws RemoteException {
7775 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7777 if (appInfo == null) {
7778 throw new IllegalArgumentException("The application " + packageName +
7779 " is not present on this device");
7781 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7785 public void setAccountManagementDisabled(ComponentName who, String accountType,
7790 Preconditions.checkNotNull(who, "ComponentName is null");
7791 synchronized (this) {
7792 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7793 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7795 ap.accountTypesWithManagementDisabled.add(accountType);
7797 ap.accountTypesWithManagementDisabled.remove(accountType);
7799 saveSettingsLocked(UserHandle.getCallingUserId());
7804 public String[] getAccountTypesWithManagementDisabled() {
7805 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7809 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7810 enforceFullCrossUsersPermission(userId);
7814 synchronized (this) {
7815 DevicePolicyData policy = getUserData(userId);
7816 final int N = policy.mAdminList.size();
7817 ArraySet<String> resultSet = new ArraySet<>();
7818 for (int i = 0; i < N; i++) {
7819 ActiveAdmin admin = policy.mAdminList.get(i);
7820 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7822 return resultSet.toArray(new String[resultSet.size()]);
7827 public void setUninstallBlocked(ComponentName who, String packageName,
7828 boolean uninstallBlocked) {
7829 Preconditions.checkNotNull(who, "ComponentName is null");
7830 final int userId = UserHandle.getCallingUserId();
7831 synchronized (this) {
7832 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7834 long id = mInjector.binderClearCallingIdentity();
7836 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7837 } catch (RemoteException re) {
7838 // Shouldn't happen.
7839 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7841 mInjector.binderRestoreCallingIdentity(id);
7847 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7848 // This function should return true if and only if the package is blocked by
7849 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7850 // when the package is a system app, or when it is an active device admin.
7851 final int userId = UserHandle.getCallingUserId();
7853 synchronized (this) {
7855 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7858 long id = mInjector.binderClearCallingIdentity();
7860 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7861 } catch (RemoteException re) {
7862 // Shouldn't happen.
7863 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7865 mInjector.binderRestoreCallingIdentity(id);
7872 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7876 Preconditions.checkNotNull(who, "ComponentName is null");
7877 synchronized (this) {
7878 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7879 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7880 if (admin.disableCallerId != disabled) {
7881 admin.disableCallerId = disabled;
7882 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7888 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7892 Preconditions.checkNotNull(who, "ComponentName is null");
7893 synchronized (this) {
7894 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7895 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7896 return admin.disableCallerId;
7901 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7902 enforceCrossUsersPermission(userId);
7903 synchronized (this) {
7904 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7905 return (admin != null) ? admin.disableCallerId : false;
7910 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7914 Preconditions.checkNotNull(who, "ComponentName is null");
7915 synchronized (this) {
7916 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7917 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7918 if (admin.disableContactsSearch != disabled) {
7919 admin.disableContactsSearch = disabled;
7920 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7926 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7930 Preconditions.checkNotNull(who, "ComponentName is null");
7931 synchronized (this) {
7932 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7933 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7934 return admin.disableContactsSearch;
7939 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7940 enforceCrossUsersPermission(userId);
7941 synchronized (this) {
7942 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7943 return (admin != null) ? admin.disableContactsSearch : false;
7948 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7949 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7950 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7951 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7952 final int callingUserId = UserHandle.getCallingUserId();
7954 final long ident = mInjector.binderClearCallingIdentity();
7956 synchronized (this) {
7957 final int managedUserId = getManagedUserId(callingUserId);
7958 if (managedUserId < 0) {
7961 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7964 "Cross-profile contacts access disabled for user " + managedUserId);
7968 ContactsInternal.startQuickContactWithErrorToastForUser(
7969 mContext, intent, new UserHandle(managedUserId));
7972 mInjector.binderRestoreCallingIdentity(ident);
7977 * @return true if cross-profile QuickContact is disabled
7979 private boolean isCrossProfileQuickContactDisabled(int userId) {
7980 return getCrossProfileCallerIdDisabledForUser(userId)
7981 && getCrossProfileContactsSearchDisabledForUser(userId);
7985 * @return the user ID of the managed user that is linked to the current user, if any.
7988 public int getManagedUserId(int callingUserId) {
7990 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7993 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7994 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7995 continue; // Caller user self, or not a managed profile. Skip.
7998 Log.v(LOG_TAG, "Managed user=" + ui.id);
8003 Log.v(LOG_TAG, "Managed user not found.");
8009 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
8013 Preconditions.checkNotNull(who, "ComponentName is null");
8014 synchronized (this) {
8015 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8016 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8017 if (admin.disableBluetoothContactSharing != disabled) {
8018 admin.disableBluetoothContactSharing = disabled;
8019 saveSettingsLocked(UserHandle.getCallingUserId());
8025 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
8029 Preconditions.checkNotNull(who, "ComponentName is null");
8030 synchronized (this) {
8031 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8032 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8033 return admin.disableBluetoothContactSharing;
8038 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
8039 // TODO: Should there be a check to make sure this relationship is
8040 // within a profile group?
8041 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
8042 synchronized (this) {
8043 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8044 return (admin != null) ? admin.disableBluetoothContactSharing : false;
8049 * Sets which packages may enter lock task mode.
8051 * <p>This function can only be called by the device owner or alternatively by the profile owner
8052 * in case the user is affiliated.
8054 * @param packages The list of packages allowed to enter lock task mode.
8057 public void setLockTaskPackages(ComponentName who, String[] packages)
8058 throws SecurityException {
8059 Preconditions.checkNotNull(who, "ComponentName is null");
8060 synchronized (this) {
8061 ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
8062 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
8063 ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
8064 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
8065 if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
8066 int userHandle = mInjector.userHandleGetCallingUserId();
8067 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
8069 throw new SecurityException("Admin " + who +
8070 " is neither the device owner or affiliated user's profile owner.");
8075 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
8076 DevicePolicyData policy = getUserData(userHandle);
8077 policy.mLockTaskPackages = packages;
8079 // Store the settings persistently.
8080 saveSettingsLocked(userHandle);
8081 updateLockTaskPackagesLocked(packages, userHandle);
8085 * This function returns the list of components allowed to start the task lock mode.
8088 public String[] getLockTaskPackages(ComponentName who) {
8089 Preconditions.checkNotNull(who, "ComponentName is null");
8090 synchronized (this) {
8091 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8092 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
8093 final List<String> packages = getLockTaskPackagesLocked(userHandle);
8094 return packages.toArray(new String[packages.size()]);
8098 private List<String> getLockTaskPackagesLocked(int userHandle) {
8099 final DevicePolicyData policy = getUserData(userHandle);
8100 return policy.mLockTaskPackages;
8104 * This function lets the caller know whether the given package is allowed to start the
8106 * @param pkg The package to check
8109 public boolean isLockTaskPermitted(String pkg) {
8110 // Get current user's devicepolicy
8111 int uid = mInjector.binderGetCallingUid();
8112 int userHandle = UserHandle.getUserId(uid);
8113 DevicePolicyData policy = getUserData(userHandle);
8114 synchronized (this) {
8115 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
8116 String lockTaskPackage = policy.mLockTaskPackages.get(i);
8118 // If the given package equals one of the packages stored our list,
8119 // we allow this package to start lock task mode.
8120 if (lockTaskPackage.equals(pkg)) {
8129 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
8130 if (!isCallerWithSystemUid()) {
8131 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
8133 synchronized (this) {
8134 final DevicePolicyData policy = getUserData(userHandle);
8135 Bundle adminExtras = new Bundle();
8136 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
8137 for (ActiveAdmin admin : policy.mAdminList) {
8138 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
8139 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
8140 if (ownsDevice || ownsProfile) {
8142 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
8145 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
8153 public void setGlobalSetting(ComponentName who, String setting, String value) {
8154 Preconditions.checkNotNull(who, "ComponentName is null");
8156 synchronized (this) {
8157 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8159 // Some settings are no supported any more. However we do not want to throw a
8160 // SecurityException to avoid breaking apps.
8161 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
8162 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
8166 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
8167 throw new SecurityException(String.format(
8168 "Permission denial: device owners cannot update %1$s", setting));
8171 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
8172 // ignore if it contradicts an existing policy
8173 long timeMs = getMaximumTimeToLock(
8174 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
8175 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
8180 long id = mInjector.binderClearCallingIdentity();
8182 mInjector.settingsGlobalPutString(setting, value);
8184 mInjector.binderRestoreCallingIdentity(id);
8190 public void setSecureSetting(ComponentName who, String setting, String value) {
8191 Preconditions.checkNotNull(who, "ComponentName is null");
8192 int callingUserId = mInjector.userHandleGetCallingUserId();
8194 synchronized (this) {
8195 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8197 if (isDeviceOwner(who, callingUserId)) {
8198 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
8199 throw new SecurityException(String.format(
8200 "Permission denial: Device owners cannot update %1$s", setting));
8202 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
8203 throw new SecurityException(String.format(
8204 "Permission denial: Profile owners cannot update %1$s", setting));
8207 long id = mInjector.binderClearCallingIdentity();
8209 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
8211 mInjector.binderRestoreCallingIdentity(id);
8217 public void setMasterVolumeMuted(ComponentName who, boolean on) {
8218 Preconditions.checkNotNull(who, "ComponentName is null");
8219 synchronized (this) {
8220 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8221 setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
8226 public boolean isMasterVolumeMuted(ComponentName who) {
8227 Preconditions.checkNotNull(who, "ComponentName is null");
8228 synchronized (this) {
8229 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8231 AudioManager audioManager =
8232 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
8233 return audioManager.isMasterMute();
8238 public void setUserIcon(ComponentName who, Bitmap icon) {
8239 synchronized (this) {
8240 Preconditions.checkNotNull(who, "ComponentName is null");
8241 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8243 int userId = UserHandle.getCallingUserId();
8244 long id = mInjector.binderClearCallingIdentity();
8246 mUserManagerInternal.setUserIcon(userId, icon);
8248 mInjector.binderRestoreCallingIdentity(id);
8254 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8255 Preconditions.checkNotNull(who, "ComponentName is null");
8256 synchronized (this) {
8257 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8259 final int userId = UserHandle.getCallingUserId();
8261 long ident = mInjector.binderClearCallingIdentity();
8263 // disallow disabling the keyguard if a password is currently set
8264 if (disabled && mLockPatternUtils.isSecure(userId)) {
8267 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8269 mInjector.binderRestoreCallingIdentity(ident);
8275 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8276 int userId = UserHandle.getCallingUserId();
8277 synchronized (this) {
8278 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8279 DevicePolicyData policy = getUserData(userId);
8280 if (policy.mStatusBarDisabled != disabled) {
8281 if (!setStatusBarDisabledInternal(disabled, userId)) {
8284 policy.mStatusBarDisabled = disabled;
8285 saveSettingsLocked(userId);
8291 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8292 long ident = mInjector.binderClearCallingIdentity();
8294 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8295 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8296 if (statusBarService != null) {
8297 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8298 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8299 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8300 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8303 } catch (RemoteException e) {
8304 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8306 mInjector.binderRestoreCallingIdentity(ident);
8312 * We need to update the internal state of whether a user has completed setup or a
8313 * device has paired once. After that, we ignore any changes that reset the
8314 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
8315 * as we don't trust any apps that might try to reset them.
8317 * Unfortunately, we don't know which user's setup state was changed, so we write all of
8320 void updateUserSetupCompleteAndPaired() {
8321 List<UserInfo> users = mUserManager.getUsers(true);
8322 final int N = users.size();
8323 for (int i = 0; i < N; i++) {
8324 int userHandle = users.get(i).id;
8325 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8327 DevicePolicyData policy = getUserData(userHandle);
8328 if (!policy.mUserSetupComplete) {
8329 policy.mUserSetupComplete = true;
8330 synchronized (this) {
8331 saveSettingsLocked(userHandle);
8335 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
8337 DevicePolicyData policy = getUserData(userHandle);
8338 if (!policy.mPaired) {
8339 policy.mPaired = true;
8340 synchronized (this) {
8341 saveSettingsLocked(userHandle);
8348 private class SetupContentObserver extends ContentObserver {
8350 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8351 Settings.Secure.USER_SETUP_COMPLETE);
8352 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8353 Settings.Global.DEVICE_PROVISIONED);
8354 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
8356 public SetupContentObserver(Handler handler) {
8361 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8362 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8364 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
8369 public void onChange(boolean selfChange, Uri uri) {
8370 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
8371 updateUserSetupCompleteAndPaired();
8372 } else if (mDeviceProvisioned.equals(uri)) {
8373 synchronized (DevicePolicyManagerService.this) {
8374 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8375 // is delayed until device is marked as provisioned.
8376 setDeviceOwnerSystemPropertyLocked();
8383 final class LocalService extends DevicePolicyManagerInternal {
8384 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8387 public List<String> getCrossProfileWidgetProviders(int profileId) {
8388 synchronized (DevicePolicyManagerService.this) {
8389 if (mOwners == null) {
8390 return Collections.emptyList();
8392 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8393 if (ownerComponent == null) {
8394 return Collections.emptyList();
8397 DevicePolicyData policy = getUserDataUnchecked(profileId);
8398 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8400 if (admin == null || admin.crossProfileWidgetProviders == null
8401 || admin.crossProfileWidgetProviders.isEmpty()) {
8402 return Collections.emptyList();
8405 return admin.crossProfileWidgetProviders;
8410 public void addOnCrossProfileWidgetProvidersChangeListener(
8411 OnCrossProfileWidgetProvidersChangeListener listener) {
8412 synchronized (DevicePolicyManagerService.this) {
8413 if (mWidgetProviderListeners == null) {
8414 mWidgetProviderListeners = new ArrayList<>();
8416 if (!mWidgetProviderListeners.contains(listener)) {
8417 mWidgetProviderListeners.add(listener);
8423 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8424 synchronized(DevicePolicyManagerService.this) {
8425 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8429 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8430 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8431 synchronized (DevicePolicyManagerService.this) {
8432 listeners = new ArrayList<>(mWidgetProviderListeners);
8434 final int listenerCount = listeners.size();
8435 for (int i = 0; i < listenerCount; i++) {
8436 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8437 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8442 public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
8443 Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8444 intent.putExtra(Intent.EXTRA_USER_ID, userId);
8445 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8447 // This method is called from AM with its lock held, so don't take the DPMS lock.
8450 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8451 if (profileOwner != null) {
8452 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
8456 final Pair<Integer, ComponentName> deviceOwner =
8457 mOwners.getDeviceOwnerUserIdAndComponent();
8458 if (deviceOwner != null && deviceOwner.first == userId) {
8459 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
8463 // We're not specifying the device admin because there isn't one.
8469 * Returns true if specified admin is allowed to limit passwords and has a
8470 * {@code passwordQuality} of at least {@code minPasswordQuality}
8472 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8473 if (admin.passwordQuality < minPasswordQuality) {
8476 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8480 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8481 if (policy != null && !policy.isValid()) {
8482 throw new IllegalArgumentException("Invalid system update policy.");
8484 synchronized (this) {
8485 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8486 if (policy == null) {
8487 mOwners.clearSystemUpdatePolicy();
8489 mOwners.setSystemUpdatePolicy(policy);
8491 mOwners.writeDeviceOwner();
8493 mContext.sendBroadcastAsUser(
8494 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8499 public SystemUpdatePolicy getSystemUpdatePolicy() {
8500 if (UserManager.isDeviceInDemoMode(mContext)) {
8501 // Pretending to have an automatic update policy when the device is in retail demo
8502 // mode. This will allow the device to download and install an ota without
8503 // any user interaction.
8504 return SystemUpdatePolicy.createAutomaticInstallPolicy();
8506 synchronized (this) {
8507 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
8508 if (policy != null && !policy.isValid()) {
8509 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8517 * Checks if the caller of the method is the device owner app.
8519 * @param callerUid UID of the caller.
8520 * @return true if the caller is the device owner app
8523 boolean isCallerDeviceOwner(int callerUid) {
8524 synchronized (this) {
8525 if (!mOwners.hasDeviceOwner()) {
8528 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8531 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8533 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8535 for (String pkg : pkgs) {
8536 if (deviceOwnerPackageName.equals(pkg)) {
8546 public void notifyPendingSystemUpdate(long updateReceivedTime) {
8547 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8548 "Only the system update service can broadcast update information");
8550 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8551 Slog.w(LOG_TAG, "Only the system update service in the system user " +
8552 "can broadcast update information.");
8555 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8556 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8557 updateReceivedTime);
8559 synchronized (this) {
8560 final String deviceOwnerPackage =
8561 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8563 if (deviceOwnerPackage == null) {
8566 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8568 ActivityInfo[] receivers = null;
8570 receivers = mContext.getPackageManager().getPackageInfo(
8571 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8572 } catch (NameNotFoundException e) {
8573 Log.e(LOG_TAG, "Cannot find device owner package", e);
8575 if (receivers != null) {
8576 long ident = mInjector.binderClearCallingIdentity();
8578 for (int i = 0; i < receivers.length; i++) {
8579 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8580 intent.setComponent(new ComponentName(deviceOwnerPackage,
8581 receivers[i].name));
8582 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8586 mInjector.binderRestoreCallingIdentity(ident);
8593 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8594 int userId = UserHandle.getCallingUserId();
8595 synchronized (this) {
8596 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8597 DevicePolicyData userPolicy = getUserData(userId);
8598 if (userPolicy.mPermissionPolicy != policy) {
8599 userPolicy.mPermissionPolicy = policy;
8600 saveSettingsLocked(userId);
8606 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8607 int userId = UserHandle.getCallingUserId();
8608 synchronized (this) {
8609 DevicePolicyData userPolicy = getUserData(userId);
8610 return userPolicy.mPermissionPolicy;
8615 public boolean setPermissionGrantState(ComponentName admin, String packageName,
8616 String permission, int grantState) throws RemoteException {
8617 UserHandle user = mInjector.binderGetCallingUserHandle();
8618 synchronized (this) {
8619 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8620 long ident = mInjector.binderClearCallingIdentity();
8622 if (getTargetSdk(packageName, user.getIdentifier())
8623 < android.os.Build.VERSION_CODES.M) {
8626 if (!isRuntimePermission(permission)) {
8627 EventLog.writeEvent(0x534e4554, "62623498", user.getIdentifier(), "");
8630 final PackageManager packageManager = mContext.getPackageManager();
8631 switch (grantState) {
8632 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8633 packageManager.grantRuntimePermission(packageName, permission, user);
8634 packageManager.updatePermissionFlags(permission, packageName,
8635 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8636 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8639 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8640 packageManager.revokeRuntimePermission(packageName,
8642 packageManager.updatePermissionFlags(permission, packageName,
8643 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8644 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8647 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8648 packageManager.updatePermissionFlags(permission, packageName,
8649 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8653 } catch (SecurityException se) {
8655 } catch (NameNotFoundException e) {
8658 mInjector.binderRestoreCallingIdentity(ident);
8664 public int getPermissionGrantState(ComponentName admin, String packageName,
8665 String permission) throws RemoteException {
8666 PackageManager packageManager = mContext.getPackageManager();
8668 UserHandle user = mInjector.binderGetCallingUserHandle();
8669 synchronized (this) {
8670 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8671 long ident = mInjector.binderClearCallingIdentity();
8673 int granted = mIPackageManager.checkPermission(permission,
8674 packageName, user.getIdentifier());
8675 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8676 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8677 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8678 // Not controlled by policy
8679 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8681 // Policy controlled so return result based on permission grant state
8682 return granted == PackageManager.PERMISSION_GRANTED
8683 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8684 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8687 mInjector.binderRestoreCallingIdentity(ident);
8692 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8694 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8696 return (pi != null) && (pi.applicationInfo.flags != 0);
8697 } catch (RemoteException re) {
8698 throw new RuntimeException("Package manager has died", re);
8703 public boolean isProvisioningAllowed(String action) {
8708 final int callingUserId = mInjector.userHandleGetCallingUserId();
8709 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8710 if (!hasFeatureManagedUsers()) {
8713 synchronized (this) {
8714 if (mOwners.hasDeviceOwner()) {
8715 if (!mInjector.userManagerIsSplitSystemUser()) {
8716 // Only split-system-user systems support managed-profiles in combination with
8720 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8721 // Only system device-owner supports managed-profiles. Non-system device-owner
8725 if (callingUserId == UserHandle.USER_SYSTEM) {
8726 // Managed-profiles cannot be setup on the system user, only regular users.
8731 if (getProfileOwner(callingUserId) != null) {
8732 // Managed user cannot have a managed profile.
8735 final long ident = mInjector.binderClearCallingIdentity();
8737 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8741 mInjector.binderRestoreCallingIdentity(ident);
8744 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8745 return isDeviceOwnerProvisioningAllowed(callingUserId);
8746 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8747 if (!hasFeatureManagedUsers()) {
8750 if (!mInjector.userManagerIsSplitSystemUser()) {
8751 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8754 if (callingUserId == UserHandle.USER_SYSTEM) {
8755 // System user cannot be a managed user.
8758 if (hasUserSetupCompleted(callingUserId)) {
8761 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8765 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8766 if (!mInjector.userManagerIsSplitSystemUser()) {
8767 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8770 return isDeviceOwnerProvisioningAllowed(callingUserId);
8772 throw new IllegalArgumentException("Unknown provisioning action " + action);
8776 * The device owner can only be set before the setup phase of the primary user has completed,
8777 * except for adb command if no accounts or additional users are present on the device.
8779 private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreConditionLocked(
8780 @Nullable ComponentName owner, int deviceOwnerUserId, boolean isAdb,
8781 boolean hasIncompatibleAccountsOrNonAdb) {
8782 if (mOwners.hasDeviceOwner()) {
8783 return CODE_HAS_DEVICE_OWNER;
8785 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8786 return CODE_USER_HAS_PROFILE_OWNER;
8788 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8789 return CODE_USER_NOT_RUNNING;
8791 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8792 return CODE_HAS_PAIRED;
8795 // if shell command runs after user setup completed check device status. Otherwise, OK.
8796 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8797 if (!mInjector.userManagerIsSplitSystemUser()) {
8798 if (mUserManager.getUserCount() > 1) {
8799 return CODE_NONSYSTEM_USER_EXISTS;
8801 if (hasIncompatibleAccountsOrNonAdb) {
8802 return CODE_ACCOUNTS_NOT_EMPTY;
8805 // STOPSHIP Do proper check in split user mode
8810 if (!mInjector.userManagerIsSplitSystemUser()) {
8811 // In non-split user mode, DO has to be user 0
8812 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8813 return CODE_NOT_SYSTEM_USER;
8815 // In non-split user mode, only provision DO before setup wizard completes
8816 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8817 return CODE_USER_SETUP_COMPLETED;
8820 // STOPSHIP Do proper check in split user mode
8826 private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8827 synchronized (this) {
8828 return CODE_OK == checkSetDeviceOwnerPreConditionLocked(
8829 /* owner unknown */ null, deviceOwnerUserId, /* isAdb */ false,
8830 /* hasIncompatibleAccountsOrNonAdb=*/ true);
8834 private boolean hasFeatureManagedUsers() {
8836 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8837 } catch (RemoteException e) {
8843 public String getWifiMacAddress(ComponentName admin) {
8844 // Make sure caller has DO.
8845 synchronized (this) {
8846 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8849 final long ident = mInjector.binderClearCallingIdentity();
8851 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8852 if (wifiInfo == null) {
8855 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8857 mInjector.binderRestoreCallingIdentity(ident);
8862 * Returns the target sdk version number that the given packageName was built for
8863 * in the given user.
8865 private int getTargetSdk(String packageName, int userId) {
8866 final ApplicationInfo ai;
8868 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8869 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8870 return targetSdkVersion;
8871 } catch (RemoteException e) {
8878 public boolean isManagedProfile(ComponentName admin) {
8879 synchronized (this) {
8880 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8882 final int callingUserId = mInjector.userHandleGetCallingUserId();
8883 final UserInfo user = getUserInfo(callingUserId);
8884 return user != null && user.isManagedProfile();
8888 public boolean isSystemOnlyUser(ComponentName admin) {
8889 synchronized (this) {
8890 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8892 final int callingUserId = mInjector.userHandleGetCallingUserId();
8893 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8897 public void reboot(ComponentName admin) {
8898 Preconditions.checkNotNull(admin);
8899 // Make sure caller has DO.
8900 synchronized (this) {
8901 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8903 long ident = mInjector.binderClearCallingIdentity();
8905 // Make sure there are no ongoing calls on the device.
8906 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8907 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8909 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8911 mInjector.binderRestoreCallingIdentity(ident);
8916 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8920 Preconditions.checkNotNull(who, "ComponentName is null");
8921 final int userHandle = mInjector.userHandleGetCallingUserId();
8922 synchronized (this) {
8923 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8924 mInjector.binderGetCallingUid());
8925 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8926 admin.shortSupportMessage = message;
8927 saveSettingsLocked(userHandle);
8933 public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8937 Preconditions.checkNotNull(who, "ComponentName is null");
8938 synchronized (this) {
8939 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8940 mInjector.binderGetCallingUid());
8941 return admin.shortSupportMessage;
8946 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8950 Preconditions.checkNotNull(who, "ComponentName is null");
8951 final int userHandle = mInjector.userHandleGetCallingUserId();
8952 synchronized (this) {
8953 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8954 mInjector.binderGetCallingUid());
8955 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8956 admin.longSupportMessage = message;
8957 saveSettingsLocked(userHandle);
8963 public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8967 Preconditions.checkNotNull(who, "ComponentName is null");
8968 synchronized (this) {
8969 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8970 mInjector.binderGetCallingUid());
8971 return admin.longSupportMessage;
8976 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8980 Preconditions.checkNotNull(who, "ComponentName is null");
8981 if (!isCallerWithSystemUid()) {
8982 throw new SecurityException("Only the system can query support message for user");
8984 synchronized (this) {
8985 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8986 if (admin != null) {
8987 return admin.shortSupportMessage;
8994 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8998 Preconditions.checkNotNull(who, "ComponentName is null");
8999 if (!isCallerWithSystemUid()) {
9000 throw new SecurityException("Only the system can query support message for user");
9002 synchronized (this) {
9003 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
9004 if (admin != null) {
9005 return admin.longSupportMessage;
9012 public void setOrganizationColor(@NonNull ComponentName who, int color) {
9016 Preconditions.checkNotNull(who, "ComponentName is null");
9017 final int userHandle = mInjector.userHandleGetCallingUserId();
9018 enforceManagedProfile(userHandle, "set organization color");
9019 synchronized (this) {
9020 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9021 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9022 admin.organizationColor = color;
9023 saveSettingsLocked(userHandle);
9028 public void setOrganizationColorForUser(int color, int userId) {
9032 enforceFullCrossUsersPermission(userId);
9033 enforceManageUsers();
9034 enforceManagedProfile(userId, "set organization color");
9035 synchronized (this) {
9036 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9037 admin.organizationColor = color;
9038 saveSettingsLocked(userId);
9043 public int getOrganizationColor(@NonNull ComponentName who) {
9045 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9047 Preconditions.checkNotNull(who, "ComponentName is null");
9048 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
9049 synchronized (this) {
9050 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9051 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9052 return admin.organizationColor;
9057 public int getOrganizationColorForUser(int userHandle) {
9059 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9061 enforceFullCrossUsersPermission(userHandle);
9062 enforceManagedProfile(userHandle, "get organization color");
9063 synchronized (this) {
9064 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9065 return (profileOwner != null)
9066 ? profileOwner.organizationColor
9067 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
9072 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
9076 Preconditions.checkNotNull(who, "ComponentName is null");
9077 final int userHandle = mInjector.userHandleGetCallingUserId();
9078 enforceManagedProfile(userHandle, "set organization name");
9079 synchronized (this) {
9080 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9081 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9082 if (!TextUtils.equals(admin.organizationName, text)) {
9083 admin.organizationName = (text == null || text.length() == 0)
9084 ? null : text.toString();
9085 saveSettingsLocked(userHandle);
9091 public CharSequence getOrganizationName(@NonNull ComponentName who) {
9095 Preconditions.checkNotNull(who, "ComponentName is null");
9096 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
9097 synchronized(this) {
9098 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9099 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9100 return admin.organizationName;
9105 public CharSequence getOrganizationNameForUser(int userHandle) {
9109 enforceFullCrossUsersPermission(userHandle);
9110 enforceManagedProfile(userHandle, "get organization name");
9111 synchronized (this) {
9112 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9113 return (profileOwner != null)
9114 ? profileOwner.organizationName
9120 public void setAffiliationIds(ComponentName admin, List<String> ids) {
9121 final Set<String> affiliationIds = new ArraySet<String>(ids);
9122 final int callingUserId = mInjector.userHandleGetCallingUserId();
9124 synchronized (this) {
9125 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9126 getUserData(callingUserId).mAffiliationIds = affiliationIds;
9127 saveSettingsLocked(callingUserId);
9128 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
9129 // Affiliation ids specified by the device owner are additionally stored in
9130 // UserHandle.USER_SYSTEM's DevicePolicyData.
9131 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
9132 saveSettingsLocked(UserHandle.USER_SYSTEM);
9138 public boolean isAffiliatedUser() {
9139 final int callingUserId = mInjector.userHandleGetCallingUserId();
9141 synchronized (this) {
9142 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
9143 // The user that the DO is installed on is always affiliated.
9146 final ComponentName profileOwner = getProfileOwner(callingUserId);
9147 if (profileOwner == null
9148 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
9151 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
9152 final Set<String> deviceAffiliationIds =
9153 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
9154 for (String id : userAffiliationIds) {
9155 if (deviceAffiliationIds.contains(id)) {
9163 private synchronized void disableDeviceOwnerManagedSingleUserFeaturesIfNeeded() {
9164 final boolean isSingleUserManagedDevice = isDeviceOwnerManagedSingleUserDevice();
9166 // disable security logging if needed
9167 if (!isSingleUserManagedDevice) {
9168 mInjector.securityLogSetLoggingEnabledProperty(false);
9169 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user managed"
9173 // disable backup service if needed
9174 // note: when clearing DO, the backup service shouldn't be disabled if it was enabled by
9176 if (mOwners.hasDeviceOwner() && !isSingleUserManagedDevice) {
9177 setBackupServiceEnabledInternal(false);
9178 Slog.w(LOG_TAG, "Backup is off as it's a managed device that has more that one user.");
9181 // disable network logging if needed
9182 if (!isSingleUserManagedDevice) {
9183 setNetworkLoggingActiveInternal(false);
9184 Slog.w(LOG_TAG, "Network logging turned off as it's no longer a single user managed"
9186 // if there still is a device owner, disable logging policy, otherwise the admin
9188 if (mOwners.hasDeviceOwner()) {
9189 getDeviceOwnerAdminLocked().isNetworkLoggingEnabled = false;
9190 saveSettingsLocked(mOwners.getDeviceOwnerUserId());
9196 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
9197 Preconditions.checkNotNull(admin);
9198 ensureDeviceOwnerManagingSingleUser(admin);
9200 synchronized (this) {
9201 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
9204 mInjector.securityLogSetLoggingEnabledProperty(enabled);
9206 mSecurityLogMonitor.start();
9208 mSecurityLogMonitor.stop();
9214 public boolean isSecurityLoggingEnabled(ComponentName admin) {
9215 Preconditions.checkNotNull(admin);
9216 synchronized (this) {
9217 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9218 return mInjector.securityLogGetLoggingEnabledProperty();
9223 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
9224 Preconditions.checkNotNull(admin);
9225 ensureDeviceOwnerManagingSingleUser(admin);
9227 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
9231 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
9233 SecurityLog.readPreviousEvents(output);
9234 return new ParceledListSlice<SecurityEvent>(output);
9235 } catch (IOException e) {
9236 Slog.w(LOG_TAG, "Fail to read previous events" , e);
9237 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
9242 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
9243 Preconditions.checkNotNull(admin);
9244 ensureDeviceOwnerManagingSingleUser(admin);
9246 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
9247 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
9250 private void enforceCanManageDeviceAdmin() {
9251 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
9255 private void enforceCanManageProfileAndDeviceOwners() {
9256 mContext.enforceCallingOrSelfPermission(
9257 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
9261 public boolean isUninstallInQueue(final String packageName) {
9262 enforceCanManageDeviceAdmin();
9263 final int userId = mInjector.userHandleGetCallingUserId();
9264 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9265 synchronized (this) {
9266 return mPackagesToRemove.contains(packageUserPair);
9271 public void uninstallPackageWithActiveAdmins(final String packageName) {
9272 enforceCanManageDeviceAdmin();
9273 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
9275 final int userId = mInjector.userHandleGetCallingUserId();
9277 enforceUserUnlocked(userId);
9279 final ComponentName profileOwner = getProfileOwner(userId);
9280 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
9281 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
9284 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
9285 if (getDeviceOwnerUserId() == userId && deviceOwner != null
9286 && packageName.equals(deviceOwner.getPackageName())) {
9287 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
9290 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9291 synchronized (this) {
9292 mPackagesToRemove.add(packageUserPair);
9295 // All active admins on the user.
9296 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
9298 // Active admins in the target package.
9299 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
9300 if (allActiveAdmins != null) {
9301 for (ComponentName activeAdmin : allActiveAdmins) {
9302 if (packageName.equals(activeAdmin.getPackageName())) {
9303 packageActiveAdmins.add(activeAdmin);
9304 removeActiveAdmin(activeAdmin, userId);
9308 if (packageActiveAdmins.size() == 0) {
9309 startUninstallIntent(packageName, userId);
9311 mHandler.postDelayed(new Runnable() {
9314 for (ComponentName activeAdmin : packageActiveAdmins) {
9315 removeAdminArtifacts(activeAdmin, userId);
9317 startUninstallIntent(packageName, userId);
9319 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9324 public boolean isDeviceProvisioned() {
9325 return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9328 private void removePackageIfRequired(final String packageName, final int userId) {
9329 if (!packageHasActiveAdmins(packageName, userId)) {
9330 // Will not do anything if uninstall was not requested or was already started.
9331 startUninstallIntent(packageName, userId);
9335 private void startUninstallIntent(final String packageName, final int userId) {
9336 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9337 synchronized (this) {
9338 if (!mPackagesToRemove.contains(packageUserPair)) {
9339 // Do nothing if uninstall was not requested or was already started.
9342 mPackagesToRemove.remove(packageUserPair);
9345 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9346 // Package does not exist. Nothing to do.
9349 } catch (RemoteException re) {
9350 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9353 try { // force stop the package before uninstalling
9354 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9355 } catch (RemoteException re) {
9356 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9358 final Uri packageURI = Uri.parse("package:" + packageName);
9359 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9360 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9361 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9365 * Removes the admin from the policy. Ideally called after the admin's
9366 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9368 * @param adminReceiver The admin to remove
9369 * @param userHandle The user for which this admin has to be removed.
9371 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9372 synchronized (this) {
9373 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9374 if (admin == null) {
9377 final DevicePolicyData policy = getUserData(userHandle);
9378 final boolean doProxyCleanup = admin.info.usesPolicy(
9379 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9380 policy.mAdminList.remove(admin);
9381 policy.mAdminMap.remove(adminReceiver);
9382 validatePasswordOwnerLocked(policy);
9383 if (doProxyCleanup) {
9384 resetGlobalProxyLocked(policy);
9386 saveSettingsLocked(userHandle);
9387 updateMaximumTimeToLockLocked(userHandle);
9388 policy.mRemovingAdmins.remove(adminReceiver);
9390 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
9392 // The removed admin might have disabled camera, so update user
9394 pushUserRestrictions(userHandle);
9398 public void setDeviceProvisioningConfigApplied() {
9399 enforceManageUsers();
9400 synchronized (this) {
9401 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9402 policy.mDeviceProvisioningConfigApplied = true;
9403 saveSettingsLocked(UserHandle.USER_SYSTEM);
9408 public boolean isDeviceProvisioningConfigApplied() {
9409 enforceManageUsers();
9410 synchronized (this) {
9411 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9412 return policy.mDeviceProvisioningConfigApplied;
9417 * Return true if a given user has any accounts that'll prevent installing a device or profile
9418 * owner {@code owner}.
9419 * - If the user has no accounts, then return false.
9420 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
9421 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
9422 * ..._DISALLOWED, return true.
9423 * - Otherwise return false.
9425 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used
9426 * when the caller is not ADB.
9428 * DO NOT CALL IT WITH THE DPMS LOCK HELD.
9430 private boolean hasIncompatibleAccountsOrNonAdbNoLock(
9431 int userId, @Nullable ComponentName owner) {
9432 final boolean isAdb = (mInjector.binderGetCallingUid() == Process.SHELL_UID)
9433 || (mInjector.binderGetCallingUid() == Process.ROOT_UID);
9438 if (Thread.holdsLock(this)) {
9439 Slog.wtf(LOG_TAG, "hasIncompatibleAccountsNoLock() called with the DPMS lock held.");
9443 final long token = mInjector.binderClearCallingIdentity();
9445 final AccountManager am = AccountManager.get(mContext);
9446 final Account accounts[] = am.getAccountsAsUser(userId);
9447 if (accounts.length == 0) {
9450 synchronized (this) {
9451 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
9453 "Non test-only owner can't be installed with existing accounts.");
9458 final String[] feature_allow =
9459 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
9460 final String[] feature_disallow =
9461 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
9463 boolean compatible = true;
9464 for (Account account : accounts) {
9465 if (hasAccountFeatures(am, account, feature_disallow)) {
9466 Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
9470 if (!hasAccountFeatures(am, account, feature_allow)) {
9471 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
9477 Log.w(LOG_TAG, "All accounts are compatible");
9479 Log.e(LOG_TAG, "Found incompatible accounts");
9483 mInjector.binderRestoreCallingIdentity(token);
9487 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
9489 return am.hasFeatures(account, features, null, null).getResult();
9490 } catch (Exception e) {
9491 Log.w(LOG_TAG, "Failed to get account feature", e);
9497 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
9498 Preconditions.checkNotNull(admin);
9502 ensureDeviceOwnerManagingSingleUser(admin);
9503 setBackupServiceEnabledInternal(enabled);
9506 private synchronized void setBackupServiceEnabledInternal(boolean enabled) {
9507 long ident = mInjector.binderClearCallingIdentity();
9509 IBackupManager ibm = mInjector.getIBackupManager();
9511 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
9513 } catch (RemoteException e) {
9514 throw new IllegalStateException(
9515 "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
9517 mInjector.binderRestoreCallingIdentity(ident);
9522 public boolean isBackupServiceEnabled(ComponentName admin) {
9523 Preconditions.checkNotNull(admin);
9527 synchronized (this) {
9528 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9530 IBackupManager ibm = mInjector.getIBackupManager();
9531 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
9532 } catch (RemoteException e) {
9533 throw new IllegalStateException("Failed requesting backup service state.", e);
9539 public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
9543 Preconditions.checkNotNull(admin);
9544 ensureDeviceOwnerManagingSingleUser(admin);
9546 if (enabled == isNetworkLoggingEnabledInternalLocked()) {
9547 // already in the requested state
9550 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9551 deviceOwner.isNetworkLoggingEnabled = enabled;
9553 deviceOwner.numNetworkLoggingNotifications = 0;
9554 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
9556 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
9558 setNetworkLoggingActiveInternal(enabled);
9561 private synchronized void setNetworkLoggingActiveInternal(boolean active) {
9562 final long callingIdentity = mInjector.binderClearCallingIdentity();
9565 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
9566 if (!mNetworkLogger.startNetworkLogging()) {
9567 mNetworkLogger = null;
9568 Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
9569 + " service not being available yet.");
9571 sendNetworkLoggingNotificationLocked();
9573 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
9574 mNetworkLogger = null;
9575 Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
9576 + " service not being available yet.");
9578 mNetworkLogger = null;
9579 mInjector.getNotificationManager().cancel(NETWORK_LOGGING_NOTIFICATION_ID);
9582 mInjector.binderRestoreCallingIdentity(callingIdentity);
9586 public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
9587 final PackageManager packageManager = mContext.getPackageManager();
9588 PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
9589 return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
9590 == PermissionInfo.PROTECTION_DANGEROUS;
9594 public boolean isNetworkLoggingEnabled(ComponentName admin) {
9598 synchronized (this) {
9599 enforceDeviceOwnerOrManageUsers();
9600 return isNetworkLoggingEnabledInternalLocked();
9604 private boolean isNetworkLoggingEnabledInternalLocked() {
9605 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9606 return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
9610 * A maximum of 1200 events are returned, and the total marshalled size is in the order of
9611 * 100kB, so returning a List instead of ParceledListSlice is acceptable.
9612 * Ideally this would be done with ParceledList, however it only supports homogeneous types.
9614 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
9617 public synchronized List<NetworkEvent> retrieveNetworkLogs(ComponentName admin,
9622 Preconditions.checkNotNull(admin);
9623 ensureDeviceOwnerManagingSingleUser(admin);
9625 if (mNetworkLogger == null) {
9628 return isNetworkLoggingEnabledInternalLocked()
9629 ? mNetworkLogger.retrieveLogs(batchToken)
9633 private void sendNetworkLoggingNotificationLocked() {
9634 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9635 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
9638 if (deviceOwner.numNetworkLoggingNotifications >=
9639 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
9642 final long now = System.currentTimeMillis();
9643 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
9646 deviceOwner.numNetworkLoggingNotifications++;
9647 if (deviceOwner.numNetworkLoggingNotifications
9648 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
9649 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
9651 deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
9653 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
9654 intent.setPackage("com.android.systemui");
9655 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
9656 UserHandle.CURRENT);
9657 Notification notification = new Notification.Builder(mContext)
9658 .setSmallIcon(R.drawable.ic_qs_network_logging)
9659 .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
9660 .setContentText(mContext.getString(R.string.network_logging_notification_text))
9661 .setTicker(mContext.getString(R.string.network_logging_notification_title))
9663 .setContentIntent(pendingIntent)
9665 mInjector.getNotificationManager().notify(NETWORK_LOGGING_NOTIFICATION_ID, notification);
9666 saveSettingsLocked(mOwners.getDeviceOwnerUserId());