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.ResolveInfo;
75 import android.content.pm.ServiceInfo;
76 import android.content.pm.UserInfo;
77 import android.database.ContentObserver;
78 import android.graphics.Bitmap;
79 import android.graphics.Color;
80 import android.media.AudioManager;
81 import android.media.IAudioService;
82 import android.net.ConnectivityManager;
83 import android.net.IIpConnectivityMetrics;
84 import android.net.ProxyInfo;
85 import android.net.Uri;
86 import android.net.metrics.IpConnectivityLog;
87 import android.net.wifi.WifiInfo;
88 import android.net.wifi.WifiManager;
89 import android.os.AsyncTask;
90 import android.os.Binder;
91 import android.os.Build;
92 import android.os.Bundle;
93 import android.os.Environment;
94 import android.os.FileUtils;
95 import android.os.Handler;
96 import android.os.IBinder;
97 import android.os.Looper;
98 import android.os.ParcelFileDescriptor;
99 import android.os.PersistableBundle;
100 import android.os.PowerManager;
101 import android.os.PowerManagerInternal;
102 import android.os.Process;
103 import android.os.RecoverySystem;
104 import android.os.RemoteCallback;
105 import android.os.RemoteException;
106 import android.os.ServiceManager;
107 import android.os.SystemClock;
108 import android.os.SystemProperties;
109 import android.os.UserHandle;
110 import android.os.UserManager;
111 import android.os.UserManagerInternal;
112 import android.os.storage.StorageManager;
113 import android.provider.ContactsContract.QuickContact;
114 import android.provider.ContactsInternal;
115 import android.provider.Settings;
116 import android.security.Credentials;
117 import android.security.IKeyChainAliasCallback;
118 import android.security.IKeyChainService;
119 import android.security.KeyChain;
120 import android.security.KeyChain.KeyChainConnection;
121 import android.service.persistentdata.PersistentDataBlockManager;
122 import android.telephony.TelephonyManager;
123 import android.text.TextUtils;
124 import android.util.ArrayMap;
125 import android.util.ArraySet;
126 import android.util.Log;
127 import android.util.Pair;
128 import android.util.Slog;
129 import android.util.SparseArray;
130 import android.util.Xml;
131 import android.view.IWindowManager;
132 import android.view.accessibility.AccessibilityManager;
133 import android.view.accessibility.IAccessibilityManager;
134 import android.view.inputmethod.InputMethodInfo;
135 import android.view.inputmethod.InputMethodManager;
137 import com.android.internal.R;
138 import com.android.internal.annotations.VisibleForTesting;
139 import com.android.internal.statusbar.IStatusBarService;
140 import com.android.internal.util.FastXmlSerializer;
141 import com.android.internal.util.JournaledFile;
142 import com.android.internal.util.ParcelableString;
143 import com.android.internal.util.Preconditions;
144 import com.android.internal.util.XmlUtils;
145 import com.android.internal.widget.LockPatternUtils;
146 import com.android.server.LocalServices;
147 import com.android.server.SystemService;
148 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
149 import com.android.server.pm.UserRestrictionsUtils;
150 import com.google.android.collect.Sets;
152 import org.xmlpull.v1.XmlPullParser;
153 import org.xmlpull.v1.XmlPullParserException;
154 import org.xmlpull.v1.XmlSerializer;
156 import java.io.ByteArrayInputStream;
158 import java.io.FileDescriptor;
159 import java.io.FileInputStream;
160 import java.io.FileNotFoundException;
161 import java.io.FileOutputStream;
162 import java.io.IOException;
163 import java.io.PrintWriter;
164 import java.lang.annotation.Retention;
165 import java.lang.annotation.RetentionPolicy;
166 import java.nio.charset.StandardCharsets;
167 import java.security.cert.CertificateException;
168 import java.security.cert.CertificateFactory;
169 import java.security.cert.X509Certificate;
170 import java.text.DateFormat;
171 import java.util.ArrayList;
172 import java.util.Arrays;
173 import java.util.Collections;
174 import java.util.Date;
175 import java.util.List;
176 import java.util.Map.Entry;
177 import java.util.Set;
178 import java.util.concurrent.atomic.AtomicBoolean;
181 * Implementation of the device policy APIs.
183 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
185 private static final String LOG_TAG = "DevicePolicyManagerService";
187 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
189 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
191 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
193 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
195 private static final String TAG_STATUS_BAR = "statusbar";
197 private static final String ATTR_DISABLED = "disabled";
199 private static final String ATTR_NAME = "name";
201 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
202 "do-not-ask-credentials-on-boot";
204 private static final String TAG_AFFILIATION_ID = "affiliation-id";
206 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
208 private static final String ATTR_VALUE = "value";
210 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
212 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
214 private static final long MS_PER_DAY = 86400 * 1000;
216 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
218 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
219 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
221 private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
222 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
223 private static final int NETWORK_LOGGING_NOTIFICATION_ID = 1002;
225 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
226 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
227 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
228 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
229 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
230 "device-provisioning-config-applied";
231 private static final String ATTR_DEVICE_PAIRED = "device-paired";
233 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
234 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
235 = "application-restrictions-manager";
238 * System property whose value is either "true" or "false", indicating whether
240 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
242 private static final int STATUS_BAR_DISABLE_MASK =
243 StatusBarManager.DISABLE_EXPAND |
244 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
245 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
246 StatusBarManager.DISABLE_SEARCH;
248 private static final int STATUS_BAR_DISABLE2_MASK =
249 StatusBarManager.DISABLE2_QUICK_SETTINGS;
251 private static final Set<String> SECURE_SETTINGS_WHITELIST;
252 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
253 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
254 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
256 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
257 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
258 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
259 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
261 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
262 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
263 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
265 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
266 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
267 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
268 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
269 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
270 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
271 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
272 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
273 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
275 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
276 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
277 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
278 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
279 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
280 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
284 * Keyguard features that when set on a managed profile that doesn't have its own challenge will
285 * affect the profile's parent user. These can also be set on the managed profile's parent DPM
288 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
289 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
290 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
293 * Keyguard features that when set on a profile affect the profile content or challenge only.
294 * These cannot be set on the managed profile's parent DPM instance
296 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
297 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
299 /** Keyguard features that are allowed to be set on a managed profile */
300 private static final int PROFILE_KEYGUARD_FEATURES =
301 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
303 private static final int CODE_OK = 0;
304 private static final int CODE_HAS_DEVICE_OWNER = 1;
305 private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
306 private static final int CODE_USER_NOT_RUNNING = 3;
307 private static final int CODE_USER_SETUP_COMPLETED = 4;
308 private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
309 private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
310 private static final int CODE_NOT_SYSTEM_USER = 7;
311 private static final int CODE_HAS_PAIRED = 8;
313 @Retention(RetentionPolicy.SOURCE)
314 @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
315 CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
316 private @interface DeviceOwnerPreConditionCode {}
318 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
321 * Minimum timeout in milliseconds after which unlocking with weak auth times out,
322 * i.e. the user has to use a strong authentication method like password, PIN or pattern.
324 private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
326 final Context mContext;
327 final Injector mInjector;
328 final IPackageManager mIPackageManager;
329 final UserManager mUserManager;
330 final UserManagerInternal mUserManagerInternal;
331 final TelephonyManager mTelephonyManager;
332 private final LockPatternUtils mLockPatternUtils;
335 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
336 * is requested for user u.
338 private final Set<Pair<String, Integer>> mPackagesToRemove =
339 new ArraySet<Pair<String, Integer>>();
341 final LocalService mLocalService;
343 // Stores and loads state on device and profile owners.
345 final Owners mOwners;
347 private final Binder mToken = new Binder();
350 * Whether or not device admin feature is supported. If it isn't return defaults for all
356 * Whether or not this device is a watch.
360 private final SecurityLogMonitor mSecurityLogMonitor;
361 private NetworkLogger mNetworkLogger;
363 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
364 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
366 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
369 if(mRemoteBugreportServiceIsActive.get()) {
375 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
378 public void onReceive(Context context, Intent intent) {
379 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
380 && mRemoteBugreportServiceIsActive.get()) {
381 onBugreportFinished(intent);
386 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
389 public void onReceive(Context context, Intent intent) {
390 String action = intent.getAction();
391 mInjector.getNotificationManager().cancel(LOG_TAG,
392 RemoteBugreportUtils.NOTIFICATION_ID);
393 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
394 onBugreportSharingAccepted();
395 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
396 onBugreportSharingDeclined();
398 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
402 public static final class Lifecycle extends SystemService {
403 private DevicePolicyManagerService mService;
405 public Lifecycle(Context context) {
407 mService = new DevicePolicyManagerService(context);
411 public void onStart() {
412 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
416 public void onBootPhase(int phase) {
417 mService.systemReady(phase);
421 public void onStartUser(int userHandle) {
422 mService.onStartUser(userHandle);
426 public static class DevicePolicyData {
427 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
428 int mActivePasswordLength = 0;
429 int mActivePasswordUpperCase = 0;
430 int mActivePasswordLowerCase = 0;
431 int mActivePasswordLetters = 0;
432 int mActivePasswordNumeric = 0;
433 int mActivePasswordSymbols = 0;
434 int mActivePasswordNonLetter = 0;
435 int mFailedPasswordAttempts = 0;
438 int mPasswordOwner = -1;
439 long mLastMaximumTimeToLock = -1;
440 boolean mUserSetupComplete = false;
441 boolean mPaired = false;
442 int mUserProvisioningState;
443 int mPermissionPolicy;
445 boolean mDeviceProvisioningConfigApplied = false;
447 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
448 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
449 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
451 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
453 // This is the list of component allowed to start lock task mode.
454 List<String> mLockTaskPackages = new ArrayList<>();
456 boolean mStatusBarDisabled = false;
458 ComponentName mRestrictionsProvider;
460 String mDelegatedCertInstallerPackage;
462 boolean doNotAskCredentialsOnBoot = false;
464 String mApplicationRestrictionsManagingPackage;
466 Set<String> mAffiliationIds = new ArraySet<>();
468 // Used for initialization of users created by createAndManageUsers.
469 boolean mAdminBroadcastPending = false;
470 PersistableBundle mInitBundle = null;
472 public DevicePolicyData(int userHandle) {
473 mUserHandle = userHandle;
477 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
479 final Handler mHandler;
481 BroadcastReceiver mReceiver = new BroadcastReceiver() {
483 public void onReceive(Context context, Intent intent) {
484 final String action = intent.getAction();
485 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
489 * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
490 * however it's too early in the boot process to register with IIpConnectivityMetrics
491 * to listen for events.
493 if (Intent.ACTION_USER_STARTED.equals(action)
494 && userHandle == mOwners.getDeviceOwnerUserId()) {
495 synchronized (DevicePolicyManagerService.this) {
496 if (isNetworkLoggingEnabledInternalLocked()) {
497 setNetworkLoggingActiveInternal(true);
501 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
502 && userHandle == mOwners.getDeviceOwnerUserId()
503 && getDeviceOwnerRemoteBugreportUri() != null) {
504 IntentFilter filterConsent = new IntentFilter();
505 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
506 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
507 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
508 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
509 RemoteBugreportUtils.NOTIFICATION_ID,
510 RemoteBugreportUtils.buildNotification(mContext,
511 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
514 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
515 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
517 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
518 + action + " for user " + userHandle);
520 mHandler.post(new Runnable() {
523 handlePasswordExpirationNotification(userHandle);
527 if (Intent.ACTION_USER_UNLOCKED.equals(action)
528 || Intent.ACTION_USER_STARTED.equals(action)
529 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
530 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
531 new MonitoringCertNotificationTask().execute(userId);
533 if (Intent.ACTION_USER_ADDED.equals(action)) {
534 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
535 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
536 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
537 removeUserData(userHandle);
538 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
539 synchronized (DevicePolicyManagerService.this) {
540 // Reset the policy data
541 mUserData.remove(userHandle);
542 sendAdminEnabledBroadcastLocked(userHandle);
544 handlePackagesChanged(null /* check all admins */, userHandle);
545 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
546 handlePackagesChanged(null /* check all admins */, userHandle);
547 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
548 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
549 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
550 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
551 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
552 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
553 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
554 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
555 clearWipeProfileNotification();
560 static class ActiveAdmin {
561 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
562 private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
563 private static final String TAG_DISABLE_CAMERA = "disable-camera";
564 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
565 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
566 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
567 = "disable-bt-contacts-sharing";
568 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
569 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
570 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
571 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
572 private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled";
573 private static final String TAG_ACCOUNT_TYPE = "account-type";
574 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
575 = "permitted-accessiblity-services";
576 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
577 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
578 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
579 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
580 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
581 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
582 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
583 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
584 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
585 private static final String TAG_PERMITTED_IMES = "permitted-imes";
586 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
587 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
588 private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
589 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
590 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
591 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
592 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
593 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
594 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
595 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
596 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
597 private static final String ATTR_VALUE = "value";
598 private static final String TAG_PASSWORD_QUALITY = "password-quality";
599 private static final String TAG_POLICIES = "policies";
600 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
601 "cross-profile-widget-providers";
602 private static final String TAG_PROVIDER = "provider";
603 private static final String TAG_PACKAGE_LIST_ITEM = "item";
604 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
605 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
606 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
607 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
608 private static final String TAG_PARENT_ADMIN = "parent-admin";
609 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
610 private static final String TAG_ORGANIZATION_NAME = "organization-name";
611 private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification";
612 private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications";
614 final DeviceAdminInfo info;
616 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
618 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
619 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
621 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
622 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
624 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
625 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
627 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
628 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
630 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
631 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
633 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
634 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
636 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
637 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
639 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
640 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
642 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
643 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
645 long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
647 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
648 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
650 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
651 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
653 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
654 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
656 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
658 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
660 boolean encryptionRequested = false;
661 boolean testOnlyAdmin = false;
662 boolean disableCamera = false;
663 boolean disableCallerId = false;
664 boolean disableContactsSearch = false;
665 boolean disableBluetoothContactSharing = true;
666 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
667 boolean requireAutoTime = false; // Can only be set by a device owner.
668 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
669 boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner.
671 // one notification after enabling + 3 more after reboots
672 static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 4;
673 int numNetworkLoggingNotifications = 0;
674 long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch
676 ActiveAdmin parentAdmin;
677 final boolean isParent;
679 static class TrustAgentInfo {
680 public PersistableBundle options;
681 TrustAgentInfo(PersistableBundle bundle) {
686 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
688 // The list of permitted accessibility services package namesas set by a profile
689 // or device owner. Null means all accessibility services are allowed, empty means
690 // none except system services are allowed.
691 List<String> permittedAccessiblityServices;
693 // The list of permitted input methods package names as set by a profile or device owner.
694 // Null means all input methods are allowed, empty means none except system imes are
696 List<String> permittedInputMethods;
698 // List of package names to keep cached.
699 List<String> keepUninstalledPackages;
701 // TODO: review implementation decisions with frameworks team
702 boolean specifiesGlobalProxy = false;
703 String globalProxySpec = null;
704 String globalProxyExclusionList = null;
706 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
708 List<String> crossProfileWidgetProviders;
710 Bundle userRestrictions;
712 // Support text provided by the admin to display to the user.
713 CharSequence shortSupportMessage = null;
714 CharSequence longSupportMessage = null;
716 // Background color of confirm credentials screen. Default: teal.
717 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
718 int organizationColor = DEF_ORGANIZATION_COLOR;
720 // Default title of confirm credentials screen
721 String organizationName = null;
723 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
728 ActiveAdmin getParentActiveAdmin() {
729 Preconditions.checkState(!isParent);
731 if (parentAdmin == null) {
732 parentAdmin = new ActiveAdmin(info, /* parent */ true);
737 boolean hasParentActiveAdmin() {
738 return parentAdmin != null;
741 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
743 public UserHandle getUserHandle() {
744 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
747 void writeToXml(XmlSerializer out)
748 throws IllegalArgumentException, IllegalStateException, IOException {
749 out.startTag(null, TAG_POLICIES);
750 info.writePoliciesToXml(out);
751 out.endTag(null, TAG_POLICIES);
752 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
753 out.startTag(null, TAG_PASSWORD_QUALITY);
754 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
755 out.endTag(null, TAG_PASSWORD_QUALITY);
756 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
757 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
758 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
759 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
761 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
762 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
763 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
764 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
766 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
767 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
768 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
769 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
771 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
772 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
773 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
774 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
776 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
777 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
778 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
779 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
781 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
782 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
783 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
784 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
786 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
787 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
788 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
789 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
791 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
792 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
793 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
794 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
797 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
798 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
799 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
800 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
802 if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
803 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
804 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
805 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
807 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
808 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
809 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
810 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
812 if (specifiesGlobalProxy) {
813 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
814 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
815 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
816 if (globalProxySpec != null) {
817 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
818 out.attribute(null, ATTR_VALUE, globalProxySpec);
819 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
821 if (globalProxyExclusionList != null) {
822 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
823 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
824 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
827 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
828 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
829 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
830 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
832 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
833 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
834 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
835 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
837 if (encryptionRequested) {
838 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
839 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
840 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
843 out.startTag(null, TAG_TEST_ONLY_ADMIN);
844 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
845 out.endTag(null, TAG_TEST_ONLY_ADMIN);
848 out.startTag(null, TAG_DISABLE_CAMERA);
849 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
850 out.endTag(null, TAG_DISABLE_CAMERA);
852 if (disableCallerId) {
853 out.startTag(null, TAG_DISABLE_CALLER_ID);
854 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
855 out.endTag(null, TAG_DISABLE_CALLER_ID);
857 if (disableContactsSearch) {
858 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
859 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
860 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
862 if (!disableBluetoothContactSharing) {
863 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
864 out.attribute(null, ATTR_VALUE,
865 Boolean.toString(disableBluetoothContactSharing));
866 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
868 if (disableScreenCapture) {
869 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
870 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
871 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
873 if (requireAutoTime) {
874 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
875 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
876 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
878 if (forceEphemeralUsers) {
879 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
880 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
881 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
883 if (isNetworkLoggingEnabled) {
884 out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
885 out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled));
886 out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS,
887 Integer.toString(numNetworkLoggingNotifications));
888 out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION,
889 Long.toString(lastNetworkLoggingNotificationTimeMs));
890 out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
892 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
893 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
894 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
895 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
897 if (!accountTypesWithManagementDisabled.isEmpty()) {
898 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
899 for (String ac : accountTypesWithManagementDisabled) {
900 out.startTag(null, TAG_ACCOUNT_TYPE);
901 out.attribute(null, ATTR_VALUE, ac);
902 out.endTag(null, TAG_ACCOUNT_TYPE);
904 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
906 if (!trustAgentInfos.isEmpty()) {
907 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
908 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
909 for (Entry<String, TrustAgentInfo> entry : set) {
910 TrustAgentInfo trustAgentInfo = entry.getValue();
911 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
912 out.attribute(null, ATTR_VALUE, entry.getKey());
913 if (trustAgentInfo.options != null) {
914 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
916 trustAgentInfo.options.saveToXml(out);
917 } catch (XmlPullParserException e) {
918 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
920 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
922 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
924 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
926 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
927 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
928 final int providerCount = crossProfileWidgetProviders.size();
929 for (int i = 0; i < providerCount; i++) {
930 String provider = crossProfileWidgetProviders.get(i);
931 out.startTag(null, TAG_PROVIDER);
932 out.attribute(null, ATTR_VALUE, provider);
933 out.endTag(null, TAG_PROVIDER);
935 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
937 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
938 permittedAccessiblityServices);
939 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
940 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
941 if (hasUserRestrictions()) {
942 UserRestrictionsUtils.writeRestrictions(
943 out, userRestrictions, TAG_USER_RESTRICTIONS);
945 if (!TextUtils.isEmpty(shortSupportMessage)) {
946 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
947 out.text(shortSupportMessage.toString());
948 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
950 if (!TextUtils.isEmpty(longSupportMessage)) {
951 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
952 out.text(longSupportMessage.toString());
953 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
955 if (parentAdmin != null) {
956 out.startTag(null, TAG_PARENT_ADMIN);
957 parentAdmin.writeToXml(out);
958 out.endTag(null, TAG_PARENT_ADMIN);
960 if (organizationColor != DEF_ORGANIZATION_COLOR) {
961 out.startTag(null, TAG_ORGANIZATION_COLOR);
962 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
963 out.endTag(null, TAG_ORGANIZATION_COLOR);
965 if (organizationName != null) {
966 out.startTag(null, TAG_ORGANIZATION_NAME);
967 out.text(organizationName);
968 out.endTag(null, TAG_ORGANIZATION_NAME);
972 void writePackageListToXml(XmlSerializer out, String outerTag,
973 List<String> packageList)
974 throws IllegalArgumentException, IllegalStateException, IOException {
975 if (packageList == null) {
979 out.startTag(null, outerTag);
980 for (String packageName : packageList) {
981 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
982 out.attribute(null, ATTR_VALUE, packageName);
983 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
985 out.endTag(null, outerTag);
988 void readFromXml(XmlPullParser parser)
989 throws XmlPullParserException, IOException {
990 int outerDepth = parser.getDepth();
992 while ((type=parser.next()) != END_DOCUMENT
993 && (type != END_TAG || parser.getDepth() > outerDepth)) {
994 if (type == END_TAG || type == TEXT) {
997 String tag = parser.getName();
998 if (TAG_POLICIES.equals(tag)) {
999 info.readPoliciesFromXml(parser);
1000 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
1001 passwordQuality = Integer.parseInt(
1002 parser.getAttributeValue(null, ATTR_VALUE));
1003 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
1004 minimumPasswordLength = Integer.parseInt(
1005 parser.getAttributeValue(null, ATTR_VALUE));
1006 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
1007 passwordHistoryLength = Integer.parseInt(
1008 parser.getAttributeValue(null, ATTR_VALUE));
1009 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
1010 minimumPasswordUpperCase = Integer.parseInt(
1011 parser.getAttributeValue(null, ATTR_VALUE));
1012 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
1013 minimumPasswordLowerCase = Integer.parseInt(
1014 parser.getAttributeValue(null, ATTR_VALUE));
1015 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
1016 minimumPasswordLetters = Integer.parseInt(
1017 parser.getAttributeValue(null, ATTR_VALUE));
1018 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
1019 minimumPasswordNumeric = Integer.parseInt(
1020 parser.getAttributeValue(null, ATTR_VALUE));
1021 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
1022 minimumPasswordSymbols = Integer.parseInt(
1023 parser.getAttributeValue(null, ATTR_VALUE));
1024 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
1025 minimumPasswordNonLetter = Integer.parseInt(
1026 parser.getAttributeValue(null, ATTR_VALUE));
1027 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
1028 maximumTimeToUnlock = Long.parseLong(
1029 parser.getAttributeValue(null, ATTR_VALUE));
1030 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
1031 strongAuthUnlockTimeout = Long.parseLong(
1032 parser.getAttributeValue(null, ATTR_VALUE));
1033 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
1034 maximumFailedPasswordsForWipe = Integer.parseInt(
1035 parser.getAttributeValue(null, ATTR_VALUE));
1036 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
1037 specifiesGlobalProxy = Boolean.parseBoolean(
1038 parser.getAttributeValue(null, ATTR_VALUE));
1039 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1041 parser.getAttributeValue(null, ATTR_VALUE);
1042 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1043 globalProxyExclusionList =
1044 parser.getAttributeValue(null, ATTR_VALUE);
1045 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1046 passwordExpirationTimeout = Long.parseLong(
1047 parser.getAttributeValue(null, ATTR_VALUE));
1048 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1049 passwordExpirationDate = Long.parseLong(
1050 parser.getAttributeValue(null, ATTR_VALUE));
1051 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1052 encryptionRequested = Boolean.parseBoolean(
1053 parser.getAttributeValue(null, ATTR_VALUE));
1054 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1055 testOnlyAdmin = Boolean.parseBoolean(
1056 parser.getAttributeValue(null, ATTR_VALUE));
1057 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1058 disableCamera = Boolean.parseBoolean(
1059 parser.getAttributeValue(null, ATTR_VALUE));
1060 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1061 disableCallerId = Boolean.parseBoolean(
1062 parser.getAttributeValue(null, ATTR_VALUE));
1063 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1064 disableContactsSearch = Boolean.parseBoolean(
1065 parser.getAttributeValue(null, ATTR_VALUE));
1066 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1067 disableBluetoothContactSharing = Boolean.parseBoolean(parser
1068 .getAttributeValue(null, ATTR_VALUE));
1069 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1070 disableScreenCapture = Boolean.parseBoolean(
1071 parser.getAttributeValue(null, ATTR_VALUE));
1072 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1073 requireAutoTime = Boolean.parseBoolean(
1074 parser.getAttributeValue(null, ATTR_VALUE));
1075 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1076 forceEphemeralUsers = Boolean.parseBoolean(
1077 parser.getAttributeValue(null, ATTR_VALUE));
1078 } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) {
1079 isNetworkLoggingEnabled = Boolean.parseBoolean(
1080 parser.getAttributeValue(null, ATTR_VALUE));
1081 lastNetworkLoggingNotificationTimeMs = Long.parseLong(
1082 parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION));
1083 numNetworkLoggingNotifications = Integer.parseInt(
1084 parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS));
1085 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1086 disabledKeyguardFeatures = Integer.parseInt(
1087 parser.getAttributeValue(null, ATTR_VALUE));
1088 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1089 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
1090 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1091 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1092 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1093 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
1094 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1095 permittedAccessiblityServices = readPackageList(parser, tag);
1096 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1097 permittedInputMethods = readPackageList(parser, tag);
1098 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1099 keepUninstalledPackages = readPackageList(parser, tag);
1100 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1101 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
1102 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1103 type = parser.next();
1104 if (type == XmlPullParser.TEXT) {
1105 shortSupportMessage = parser.getText();
1107 Log.w(LOG_TAG, "Missing text when loading short support message");
1109 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1110 type = parser.next();
1111 if (type == XmlPullParser.TEXT) {
1112 longSupportMessage = parser.getText();
1114 Log.w(LOG_TAG, "Missing text when loading long support message");
1116 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1117 Preconditions.checkState(!isParent);
1119 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1120 parentAdmin.readFromXml(parser);
1121 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1122 organizationColor = Integer.parseInt(
1123 parser.getAttributeValue(null, ATTR_VALUE));
1124 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1125 type = parser.next();
1126 if (type == XmlPullParser.TEXT) {
1127 organizationName = parser.getText();
1129 Log.w(LOG_TAG, "Missing text when loading organization name");
1132 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1133 XmlUtils.skipCurrentTag(parser);
1138 private List<String> readPackageList(XmlPullParser parser,
1139 String tag) throws XmlPullParserException, IOException {
1140 List<String> result = new ArrayList<String>();
1141 int outerDepth = parser.getDepth();
1143 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1144 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1145 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1148 String outerTag = parser.getName();
1149 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1150 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1151 if (packageName != null) {
1152 result.add(packageName);
1154 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1157 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1163 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1164 throws XmlPullParserException, IOException {
1165 int outerDepthDAM = parser.getDepth();
1167 Set<String> result = new ArraySet<>();
1168 while ((typeDAM=parser.next()) != END_DOCUMENT
1169 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1170 if (typeDAM == END_TAG || typeDAM == TEXT) {
1173 String tagDAM = parser.getName();
1174 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1175 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1177 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1183 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1184 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1185 int outerDepthDAM = parser.getDepth();
1187 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1188 while ((typeDAM=parser.next()) != END_DOCUMENT
1189 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1190 if (typeDAM == END_TAG || typeDAM == TEXT) {
1193 String tagDAM = parser.getName();
1194 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1195 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1196 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1197 result.put(component, trustAgentInfo);
1199 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1205 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1206 throws XmlPullParserException, IOException {
1207 int outerDepthDAM = parser.getDepth();
1209 TrustAgentInfo result = new TrustAgentInfo(null);
1210 while ((typeDAM=parser.next()) != END_DOCUMENT
1211 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1212 if (typeDAM == END_TAG || typeDAM == TEXT) {
1215 String tagDAM = parser.getName();
1216 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1217 result.options = PersistableBundle.restoreFromXml(parser);
1219 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1225 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1226 throws XmlPullParserException, IOException {
1227 int outerDepthDAM = parser.getDepth();
1229 ArrayList<String> result = null;
1230 while ((typeDAM=parser.next()) != END_DOCUMENT
1231 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1232 if (typeDAM == END_TAG || typeDAM == TEXT) {
1235 String tagDAM = parser.getName();
1236 if (TAG_PROVIDER.equals(tagDAM)) {
1237 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1238 if (result == null) {
1239 result = new ArrayList<>();
1241 result.add(provider);
1243 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1249 boolean hasUserRestrictions() {
1250 return userRestrictions != null && userRestrictions.size() > 0;
1253 Bundle ensureUserRestrictions() {
1254 if (userRestrictions == null) {
1255 userRestrictions = new Bundle();
1257 return userRestrictions;
1260 void dump(String prefix, PrintWriter pw) {
1261 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1262 pw.print(prefix); pw.print("testOnlyAdmin=");
1263 pw.println(testOnlyAdmin);
1264 pw.print(prefix); pw.println("policies:");
1265 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1267 for (int i=0; i<pols.size(); i++) {
1268 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1271 pw.print(prefix); pw.print("passwordQuality=0x");
1272 pw.println(Integer.toHexString(passwordQuality));
1273 pw.print(prefix); pw.print("minimumPasswordLength=");
1274 pw.println(minimumPasswordLength);
1275 pw.print(prefix); pw.print("passwordHistoryLength=");
1276 pw.println(passwordHistoryLength);
1277 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1278 pw.println(minimumPasswordUpperCase);
1279 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1280 pw.println(minimumPasswordLowerCase);
1281 pw.print(prefix); pw.print("minimumPasswordLetters=");
1282 pw.println(minimumPasswordLetters);
1283 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1284 pw.println(minimumPasswordNumeric);
1285 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1286 pw.println(minimumPasswordSymbols);
1287 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1288 pw.println(minimumPasswordNonLetter);
1289 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1290 pw.println(maximumTimeToUnlock);
1291 pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1292 pw.println(strongAuthUnlockTimeout);
1293 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1294 pw.println(maximumFailedPasswordsForWipe);
1295 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1296 pw.println(specifiesGlobalProxy);
1297 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1298 pw.println(passwordExpirationTimeout);
1299 pw.print(prefix); pw.print("passwordExpirationDate=");
1300 pw.println(passwordExpirationDate);
1301 if (globalProxySpec != null) {
1302 pw.print(prefix); pw.print("globalProxySpec=");
1303 pw.println(globalProxySpec);
1305 if (globalProxyExclusionList != null) {
1306 pw.print(prefix); pw.print("globalProxyEclusionList=");
1307 pw.println(globalProxyExclusionList);
1309 pw.print(prefix); pw.print("encryptionRequested=");
1310 pw.println(encryptionRequested);
1311 pw.print(prefix); pw.print("disableCamera=");
1312 pw.println(disableCamera);
1313 pw.print(prefix); pw.print("disableCallerId=");
1314 pw.println(disableCallerId);
1315 pw.print(prefix); pw.print("disableContactsSearch=");
1316 pw.println(disableContactsSearch);
1317 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1318 pw.println(disableBluetoothContactSharing);
1319 pw.print(prefix); pw.print("disableScreenCapture=");
1320 pw.println(disableScreenCapture);
1321 pw.print(prefix); pw.print("requireAutoTime=");
1322 pw.println(requireAutoTime);
1323 pw.print(prefix); pw.print("forceEphemeralUsers=");
1324 pw.println(forceEphemeralUsers);
1325 pw.print(prefix); pw.print("isNetworkLoggingEnabled=");
1326 pw.println(isNetworkLoggingEnabled);
1327 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1328 pw.println(disabledKeyguardFeatures);
1329 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1330 pw.println(crossProfileWidgetProviders);
1331 if (permittedAccessiblityServices != null) {
1332 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1333 pw.println(permittedAccessiblityServices);
1335 if (permittedInputMethods != null) {
1336 pw.print(prefix); pw.print("permittedInputMethods=");
1337 pw.println(permittedInputMethods);
1339 if (keepUninstalledPackages != null) {
1340 pw.print(prefix); pw.print("keepUninstalledPackages=");
1341 pw.println(keepUninstalledPackages);
1343 pw.print(prefix); pw.print("organizationColor=");
1344 pw.println(organizationColor);
1345 if (organizationName != null) {
1346 pw.print(prefix); pw.print("organizationName=");
1347 pw.println(organizationName);
1349 pw.print(prefix); pw.println("userRestrictions:");
1350 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1351 pw.print(prefix); pw.print("isParent=");
1352 pw.println(isParent);
1353 if (parentAdmin != null) {
1354 pw.print(prefix); pw.println("parentAdmin:");
1355 parentAdmin.dump(prefix + " ", pw);
1360 private void handlePackagesChanged(String packageName, int userHandle) {
1361 boolean removed = false;
1362 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1363 DevicePolicyData policy = getUserData(userHandle);
1364 synchronized (this) {
1365 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1366 ActiveAdmin aa = policy.mAdminList.get(i);
1368 // If we're checking all packages or if the specific one we're checking matches,
1369 // then check if the package and receiver still exist.
1370 final String adminPackage = aa.info.getPackageName();
1371 if (packageName == null || packageName.equals(adminPackage)) {
1372 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1373 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1374 PackageManager.MATCH_DIRECT_BOOT_AWARE
1375 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1376 userHandle) == null) {
1378 policy.mAdminList.remove(i);
1379 policy.mAdminMap.remove(aa.info.getComponent());
1382 } catch (RemoteException re) {
1387 validatePasswordOwnerLocked(policy);
1388 saveSettingsLocked(policy.mUserHandle);
1391 // Check if delegated cert installer or app restrictions managing packages are removed.
1392 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1393 policy.mDelegatedCertInstallerPackage = null;
1394 saveSettingsLocked(policy.mUserHandle);
1396 if (isRemovedPackage(
1397 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1398 policy.mApplicationRestrictionsManagingPackage = null;
1399 saveSettingsLocked(policy.mUserHandle);
1403 // The removed admin might have disabled camera, so update user restrictions.
1404 pushUserRestrictions(userHandle);
1408 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1410 return targetPackage != null
1411 && (changedPackage == null || changedPackage.equals(targetPackage))
1412 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1413 } catch (RemoteException e) {
1421 * Unit test will subclass it to inject mocks.
1424 static class Injector {
1426 private final Context mContext;
1428 Injector(Context context) {
1432 Owners newOwners() {
1433 return new Owners(getUserManager(), getUserManagerInternal(),
1434 getPackageManagerInternal());
1437 UserManager getUserManager() {
1438 return UserManager.get(mContext);
1441 UserManagerInternal getUserManagerInternal() {
1442 return LocalServices.getService(UserManagerInternal.class);
1445 PackageManagerInternal getPackageManagerInternal() {
1446 return LocalServices.getService(PackageManagerInternal.class);
1449 NotificationManager getNotificationManager() {
1450 return mContext.getSystemService(NotificationManager.class);
1453 IIpConnectivityMetrics getIIpConnectivityMetrics() {
1454 return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1455 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1458 PowerManagerInternal getPowerManagerInternal() {
1459 return LocalServices.getService(PowerManagerInternal.class);
1462 TelephonyManager getTelephonyManager() {
1463 return TelephonyManager.from(mContext);
1466 TrustManager getTrustManager() {
1467 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1470 AlarmManager getAlarmManager() {
1471 return (AlarmManager) mContext.getSystemService(AlarmManager.class);
1474 IWindowManager getIWindowManager() {
1475 return IWindowManager.Stub
1476 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1479 IActivityManager getIActivityManager() {
1480 return ActivityManagerNative.getDefault();
1483 IPackageManager getIPackageManager() {
1484 return AppGlobals.getPackageManager();
1487 IBackupManager getIBackupManager() {
1488 return IBackupManager.Stub.asInterface(
1489 ServiceManager.getService(Context.BACKUP_SERVICE));
1492 IAudioService getIAudioService() {
1493 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1496 LockPatternUtils newLockPatternUtils() {
1497 return new LockPatternUtils(mContext);
1500 boolean storageManagerIsFileBasedEncryptionEnabled() {
1501 return StorageManager.isFileEncryptedNativeOnly();
1504 boolean storageManagerIsNonDefaultBlockEncrypted() {
1505 long identity = Binder.clearCallingIdentity();
1507 return StorageManager.isNonDefaultBlockEncrypted();
1509 Binder.restoreCallingIdentity(identity);
1513 boolean storageManagerIsEncrypted() {
1514 return StorageManager.isEncrypted();
1517 boolean storageManagerIsEncryptable() {
1518 return StorageManager.isEncryptable();
1521 Looper getMyLooper() {
1522 return Looper.myLooper();
1525 WifiManager getWifiManager() {
1526 return mContext.getSystemService(WifiManager.class);
1529 long binderClearCallingIdentity() {
1530 return Binder.clearCallingIdentity();
1533 void binderRestoreCallingIdentity(long token) {
1534 Binder.restoreCallingIdentity(token);
1537 int binderGetCallingUid() {
1538 return Binder.getCallingUid();
1541 int binderGetCallingPid() {
1542 return Binder.getCallingPid();
1545 UserHandle binderGetCallingUserHandle() {
1546 return Binder.getCallingUserHandle();
1549 boolean binderIsCallingUidMyUid() {
1550 return getCallingUid() == Process.myUid();
1553 final int userHandleGetCallingUserId() {
1554 return UserHandle.getUserId(binderGetCallingUid());
1557 File environmentGetUserSystemDirectory(int userId) {
1558 return Environment.getUserSystemDirectory(userId);
1561 void powerManagerGoToSleep(long time, int reason, int flags) {
1562 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1565 void powerManagerReboot(String reason) {
1566 mContext.getSystemService(PowerManager.class).reboot(reason);
1569 boolean systemPropertiesGetBoolean(String key, boolean def) {
1570 return SystemProperties.getBoolean(key, def);
1573 long systemPropertiesGetLong(String key, long def) {
1574 return SystemProperties.getLong(key, def);
1577 String systemPropertiesGet(String key, String def) {
1578 return SystemProperties.get(key, def);
1581 String systemPropertiesGet(String key) {
1582 return SystemProperties.get(key);
1585 void systemPropertiesSet(String key, String value) {
1586 SystemProperties.set(key, value);
1589 boolean userManagerIsSplitSystemUser() {
1590 return UserManager.isSplitSystemUser();
1593 String getDevicePolicyFilePathForSystemUser() {
1594 return "/data/system/";
1597 void registerContentObserver(Uri uri, boolean notifyForDescendents,
1598 ContentObserver observer, int userHandle) {
1599 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1600 observer, userHandle);
1603 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1604 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1605 name, def, userHandle);
1608 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1609 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1610 name, value, userHandle);
1613 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1614 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1615 name, value, userHandle);
1618 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1619 Settings.Global.putStringForUser(mContext.getContentResolver(),
1620 name, value, userHandle);
1623 void settingsSecurePutInt(String name, int value) {
1624 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1627 int settingsGlobalGetInt(String name, int def) {
1628 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1631 void settingsGlobalPutInt(String name, int value) {
1632 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1635 void settingsSecurePutString(String name, String value) {
1636 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1639 void settingsGlobalPutString(String name, String value) {
1640 Settings.Global.putString(mContext.getContentResolver(), name, value);
1643 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1644 SecurityLog.setLoggingEnabledProperty(enabled);
1647 boolean securityLogGetLoggingEnabledProperty() {
1648 return SecurityLog.getLoggingEnabledProperty();
1651 boolean securityLogIsLoggingEnabled() {
1652 return SecurityLog.isLoggingEnabled();
1657 * Instantiates the service.
1659 public DevicePolicyManagerService(Context context) {
1660 this(new Injector(context));
1664 DevicePolicyManagerService(Injector injector) {
1665 mInjector = injector;
1666 mContext = Preconditions.checkNotNull(injector.mContext);
1667 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1668 mOwners = Preconditions.checkNotNull(injector.newOwners());
1670 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1671 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1672 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1673 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1675 mLocalService = new LocalService();
1676 mLockPatternUtils = injector.newLockPatternUtils();
1678 mSecurityLogMonitor = new SecurityLogMonitor(this);
1680 mHasFeature = mContext.getPackageManager()
1681 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1682 mIsWatch = mContext.getPackageManager()
1683 .hasSystemFeature(PackageManager.FEATURE_WATCH);
1685 // Skip the rest of the initialization
1688 IntentFilter filter = new IntentFilter();
1689 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1690 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1691 filter.addAction(Intent.ACTION_USER_ADDED);
1692 filter.addAction(Intent.ACTION_USER_REMOVED);
1693 filter.addAction(Intent.ACTION_USER_STARTED);
1694 filter.addAction(Intent.ACTION_USER_UNLOCKED);
1695 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1696 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1697 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1698 filter = new IntentFilter();
1699 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1700 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1701 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1702 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1703 filter.addDataScheme("package");
1704 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1705 filter = new IntentFilter();
1706 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1707 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1709 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1713 * Creates and loads the policy data from xml.
1714 * @param userHandle the user for whom to load the policy data
1718 DevicePolicyData getUserData(int userHandle) {
1719 synchronized (this) {
1720 DevicePolicyData policy = mUserData.get(userHandle);
1721 if (policy == null) {
1722 policy = new DevicePolicyData(userHandle);
1723 mUserData.append(userHandle, policy);
1724 loadSettingsLocked(policy, userHandle);
1731 * Creates and loads the policy data from xml for data that is shared between
1732 * various profiles of a user. In contrast to {@link #getUserData(int)}
1733 * it allows access to data of users other than the calling user.
1735 * This function should only be used for shared data, e.g. everything regarding
1736 * passwords and should be removed once multiple screen locks are present.
1737 * @param userHandle the user for whom to load the policy data
1740 DevicePolicyData getUserDataUnchecked(int userHandle) {
1741 long ident = mInjector.binderClearCallingIdentity();
1743 return getUserData(userHandle);
1745 mInjector.binderRestoreCallingIdentity(ident);
1749 void removeUserData(int userHandle) {
1750 synchronized (this) {
1751 if (userHandle == UserHandle.USER_SYSTEM) {
1752 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1755 mOwners.removeProfileOwner(userHandle);
1756 mOwners.writeProfileOwner(userHandle);
1758 DevicePolicyData policy = mUserData.get(userHandle);
1759 if (policy != null) {
1760 mUserData.remove(userHandle);
1762 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1763 DEVICE_POLICIES_XML);
1764 policyFile.delete();
1765 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1767 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1771 synchronized (this) {
1773 setDeviceOwnerSystemPropertyLocked();
1774 findOwnerComponentIfNecessaryLocked();
1775 migrateUserRestrictionsIfNecessaryLocked();
1777 // TODO PO may not have a class name either due to b/17652534. Address that too.
1779 updateDeviceOwnerLocked();
1783 private void setDeviceOwnerSystemPropertyLocked() {
1784 final boolean deviceProvisioned =
1785 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0;
1786 // If the device is not provisioned and there is currently no device owner, do not set the
1787 // read-only system property yet, since Device owner may still be provisioned. For Wear
1788 // devices, if there is already a device owner then it's OK to set the property to true now,
1789 // regardless the provision state.
1790 final boolean isWatchWithDeviceOwner = mIsWatch && mOwners.hasDeviceOwner();
1791 if (!isWatchWithDeviceOwner && !deviceProvisioned) {
1794 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1795 // always false at this point.
1796 if (StorageManager.inCryptKeeperBounce()) {
1800 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1801 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1803 if (mOwners.hasDeviceOwner()) {
1804 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1805 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1806 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
1807 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1808 mSecurityLogMonitor.start();
1811 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1812 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1817 private void findOwnerComponentIfNecessaryLocked() {
1818 if (!mOwners.hasDeviceOwner()) {
1821 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1823 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1824 return; // Already a full component name.
1827 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1828 doComponentName.getPackageName(),
1829 mOwners.getDeviceOwnerUserId());
1830 if (doComponent == null) {
1831 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1833 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1835 mOwners.getDeviceOwnerName(),
1836 mOwners.getDeviceOwnerUserId(),
1837 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1838 mOwners.writeDeviceOwner();
1840 Log.v(LOG_TAG, "Device owner component filled in");
1846 * We didn't use to persist user restrictions for each owners but only persisted in user
1849 private void migrateUserRestrictionsIfNecessaryLocked() {
1850 boolean migrated = false;
1851 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1852 // except for the "system controlled" ones.
1853 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1855 Log.v(LOG_TAG, "Migrating DO user restrictions");
1859 // Migrate user 0 restrictions to DO.
1860 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1862 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1863 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1865 // Push DO user restrictions to user manager.
1866 pushUserRestrictions(UserHandle.USER_SYSTEM);
1868 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1873 // The following restrictions can be set on secondary users by the device owner, so we
1874 // assume they're not from the PO.
1875 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1876 UserManager.DISALLOW_OUTGOING_CALLS,
1877 UserManager.DISALLOW_SMS);
1879 for (UserInfo ui : mUserManager.getUsers()) {
1880 final int userId = ui.id;
1881 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1883 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1887 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1889 final Set<String> exceptionList =
1890 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1892 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1893 exceptionList, /* isDeviceOwner =*/ false);
1895 // Note if a secondary user has no PO but has a DA that disables camera, we
1896 // don't get here and won't push the camera user restriction to UserManager
1897 // here. That's okay because we'll push user restrictions anyway when a user
1898 // starts. But we still do it because we want to let user manager persist
1900 pushUserRestrictions(userId);
1902 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1905 if (VERBOSE_LOG && migrated) {
1906 Log.v(LOG_TAG, "User restrictions migrated.");
1910 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1911 Set<String> exceptionList, boolean isDeviceOwner) {
1912 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1913 user.getIdentifier());
1915 final Bundle newBaseRestrictions = new Bundle();
1916 final Bundle newOwnerRestrictions = new Bundle();
1918 for (String key : origRestrictions.keySet()) {
1919 if (!origRestrictions.getBoolean(key)) {
1922 final boolean canOwnerChange = isDeviceOwner
1923 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1924 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1926 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1927 newBaseRestrictions.putBoolean(key, true);
1929 newOwnerRestrictions.putBoolean(key, true);
1934 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1935 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1936 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1938 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1939 newBaseRestrictions);
1941 if (admin != null) {
1942 admin.ensureUserRestrictions().clear();
1943 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1945 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1947 saveSettingsLocked(user.getIdentifier());
1950 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1951 final DevicePolicyData policy = getUserData(userId);
1952 final int n = policy.mAdminList.size();
1953 ComponentName found = null;
1955 for (int i = 0; i < n; i++) {
1956 final ActiveAdmin admin = policy.mAdminList.get(i);
1957 if (packageName.equals(admin.info.getPackageName())) {
1960 found = admin.info.getComponent();
1966 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1972 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1973 * reminders. Clears alarm if no expirations are configured.
1975 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1976 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1977 final long now = System.currentTimeMillis();
1978 final long timeToExpire = expiration - now;
1979 final long alarmTime;
1980 if (expiration == 0) {
1981 // No expirations are currently configured: Cancel alarm.
1983 } else if (timeToExpire <= 0) {
1984 // The password has already expired: Repeat every 24 hours.
1985 alarmTime = now + MS_PER_DAY;
1987 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1988 // the expiration time.
1989 long alarmInterval = timeToExpire % MS_PER_DAY;
1990 if (alarmInterval == 0) {
1991 alarmInterval = MS_PER_DAY;
1993 alarmTime = now + alarmInterval;
1996 long token = mInjector.binderClearCallingIdentity();
1998 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1999 AlarmManager am = mInjector.getAlarmManager();
2000 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2001 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2002 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
2003 UserHandle.of(affectedUserHandle));
2005 if (alarmTime != 0) {
2006 am.set(AlarmManager.RTC, alarmTime, pi);
2009 mInjector.binderRestoreCallingIdentity(token);
2013 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2014 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2016 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2017 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2023 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2025 enforceManagedProfile(userHandle, "call APIs on the parent profile");
2027 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2028 if (admin != null && parent) {
2029 admin = admin.getParentActiveAdmin();
2034 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2035 throws SecurityException {
2036 final int callingUid = mInjector.binderGetCallingUid();
2038 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
2039 if (result != null) {
2044 final int userId = UserHandle.getUserId(callingUid);
2045 final DevicePolicyData policy = getUserData(userId);
2046 ActiveAdmin admin = policy.mAdminMap.get(who);
2047 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2048 throw new SecurityException("Admin " + admin.info.getComponent()
2049 + " does not own the device");
2051 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2052 throw new SecurityException("Admin " + admin.info.getComponent()
2053 + " does not own the profile");
2055 throw new SecurityException("Admin " + admin.info.getComponent()
2056 + " did not specify uses-policy for: "
2057 + admin.info.getTagForPolicy(reqPolicy));
2059 throw new SecurityException("No active admin owned by uid "
2060 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
2064 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2065 throws SecurityException {
2067 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2068 "call APIs on the parent profile");
2070 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2071 return parent ? admin.getParentActiveAdmin() : admin;
2074 * Find the admin for the component and userId bit of the uid, then check
2075 * the admin's uid matches the uid.
2077 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2078 final int userId = UserHandle.getUserId(uid);
2079 final DevicePolicyData policy = getUserData(userId);
2080 ActiveAdmin admin = policy.mAdminMap.get(who);
2081 if (admin == null) {
2082 throw new SecurityException("No active admin " + who);
2084 if (admin.getUid() != uid) {
2085 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2090 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2092 // Try to find an admin which can use reqPolicy
2093 final int userId = UserHandle.getUserId(uid);
2094 final DevicePolicyData policy = getUserData(userId);
2096 ActiveAdmin admin = policy.mAdminMap.get(who);
2097 if (admin == null) {
2098 throw new SecurityException("No active admin " + who);
2100 if (admin.getUid() != uid) {
2101 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2103 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2107 for (ActiveAdmin admin : policy.mAdminList) {
2108 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2119 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2121 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2122 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2124 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2126 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2127 // DO always has the PO power.
2128 return ownsDevice || ownsProfile;
2130 return admin.info.usesPolicy(reqPolicy);
2134 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2135 sendAdminCommandLocked(admin, action, null);
2138 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2139 sendAdminCommandLocked(admin, action, null, result);
2143 * Send an update to one specific admin, get notified when that admin returns a result.
2145 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2146 BroadcastReceiver result) {
2147 Intent intent = new Intent(action);
2148 intent.setComponent(admin.info.getComponent());
2149 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2150 intent.putExtra("expiration", admin.passwordExpirationDate);
2152 if (adminExtras != null) {
2153 intent.putExtras(adminExtras);
2155 if (result != null) {
2156 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2157 null, result, mHandler, Activity.RESULT_OK, null, null);
2159 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2164 * Send an update to all admins of a user that enforce a specified policy.
2166 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2167 final DevicePolicyData policy = getUserData(userHandle);
2168 final int count = policy.mAdminList.size();
2170 for (int i = 0; i < count; i++) {
2171 final ActiveAdmin admin = policy.mAdminList.get(i);
2172 if (admin.info.usesPolicy(reqPolicy)) {
2173 sendAdminCommandLocked(admin, action);
2180 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2181 * enforce a specified policy.
2183 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2185 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2186 for (int profileId : profileIds) {
2187 sendAdminCommandLocked(action, reqPolicy, profileId);
2192 * Sends a broadcast to each profile that share the password unlock with the given user id.
2194 private void sendAdminCommandForLockscreenPoliciesLocked(
2195 String action, int reqPolicy, int userHandle) {
2196 if (isSeparateProfileChallengeEnabled(userHandle)) {
2197 sendAdminCommandLocked(action, reqPolicy, userHandle);
2199 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2203 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2204 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2205 DevicePolicyData policy = getUserData(userHandle);
2206 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2207 policy.mRemovingAdmins.add(adminReceiver);
2208 sendAdminCommandLocked(admin,
2209 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2210 new BroadcastReceiver() {
2212 public void onReceive(Context context, Intent intent) {
2213 removeAdminArtifacts(adminReceiver, userHandle);
2214 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2221 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2222 boolean throwForMissiongPermission) {
2226 enforceFullCrossUsersPermission(userHandle);
2227 ActivityInfo ai = null;
2229 ai = mIPackageManager.getReceiverInfo(adminName,
2230 PackageManager.GET_META_DATA |
2231 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2232 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2233 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2234 } catch (RemoteException e) {
2235 // shouldn't happen.
2238 throw new IllegalArgumentException("Unknown admin: " + adminName);
2241 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2242 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2243 + permission.BIND_DEVICE_ADMIN;
2244 Slog.w(LOG_TAG, message);
2245 if (throwForMissiongPermission &&
2246 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2247 throw new IllegalArgumentException(message);
2252 return new DeviceAdminInfo(mContext, ai);
2253 } catch (XmlPullParserException | IOException e) {
2254 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2260 private JournaledFile makeJournaledFile(int userHandle) {
2261 final String base = userHandle == UserHandle.USER_SYSTEM
2262 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2263 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2264 DEVICE_POLICIES_XML).getAbsolutePath();
2266 Log.v(LOG_TAG, "Opening " + base);
2268 return new JournaledFile(new File(base), new File(base + ".tmp"));
2271 private void saveSettingsLocked(int userHandle) {
2272 DevicePolicyData policy = getUserData(userHandle);
2273 JournaledFile journal = makeJournaledFile(userHandle);
2274 FileOutputStream stream = null;
2276 stream = new FileOutputStream(journal.chooseForWrite(), false);
2277 XmlSerializer out = new FastXmlSerializer();
2278 out.setOutput(stream, StandardCharsets.UTF_8.name());
2279 out.startDocument(null, true);
2281 out.startTag(null, "policies");
2282 if (policy.mRestrictionsProvider != null) {
2283 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2284 policy.mRestrictionsProvider.flattenToString());
2286 if (policy.mUserSetupComplete) {
2287 out.attribute(null, ATTR_SETUP_COMPLETE,
2288 Boolean.toString(true));
2290 if (policy.mPaired) {
2291 out.attribute(null, ATTR_DEVICE_PAIRED,
2292 Boolean.toString(true));
2294 if (policy.mDeviceProvisioningConfigApplied) {
2295 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2296 Boolean.toString(true));
2298 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2299 out.attribute(null, ATTR_PROVISIONING_STATE,
2300 Integer.toString(policy.mUserProvisioningState));
2302 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2303 out.attribute(null, ATTR_PERMISSION_POLICY,
2304 Integer.toString(policy.mPermissionPolicy));
2306 if (policy.mDelegatedCertInstallerPackage != null) {
2307 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2308 policy.mDelegatedCertInstallerPackage);
2310 if (policy.mApplicationRestrictionsManagingPackage != null) {
2311 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2312 policy.mApplicationRestrictionsManagingPackage);
2315 final int N = policy.mAdminList.size();
2316 for (int i=0; i<N; i++) {
2317 ActiveAdmin ap = policy.mAdminList.get(i);
2319 out.startTag(null, "admin");
2320 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2322 out.endTag(null, "admin");
2326 if (policy.mPasswordOwner >= 0) {
2327 out.startTag(null, "password-owner");
2328 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2329 out.endTag(null, "password-owner");
2332 if (policy.mFailedPasswordAttempts != 0) {
2333 out.startTag(null, "failed-password-attempts");
2334 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2335 out.endTag(null, "failed-password-attempts");
2338 // Don't save metrics for FBE devices
2339 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
2340 && (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2341 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2342 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2343 || policy.mActivePasswordSymbols != 0
2344 || policy.mActivePasswordNonLetter != 0)) {
2345 out.startTag(null, "active-password");
2346 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2347 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2348 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2349 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2350 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2351 out.attribute(null, "numeric", Integer
2352 .toString(policy.mActivePasswordNumeric));
2353 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2354 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2355 out.endTag(null, "active-password");
2358 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2359 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2360 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2361 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2364 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2365 String component = policy.mLockTaskPackages.get(i);
2366 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2367 out.attribute(null, "name", component);
2368 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2371 if (policy.mStatusBarDisabled) {
2372 out.startTag(null, TAG_STATUS_BAR);
2373 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2374 out.endTag(null, TAG_STATUS_BAR);
2377 if (policy.doNotAskCredentialsOnBoot) {
2378 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2379 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2382 for (String id : policy.mAffiliationIds) {
2383 out.startTag(null, TAG_AFFILIATION_ID);
2384 out.attribute(null, "id", id);
2385 out.endTag(null, TAG_AFFILIATION_ID);
2388 if (policy.mAdminBroadcastPending) {
2389 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2390 out.attribute(null, ATTR_VALUE,
2391 Boolean.toString(policy.mAdminBroadcastPending));
2392 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2395 if (policy.mInitBundle != null) {
2396 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2397 policy.mInitBundle.saveToXml(out);
2398 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2401 out.endTag(null, "policies");
2405 FileUtils.sync(stream);
2408 sendChangedNotification(userHandle);
2409 } catch (XmlPullParserException | IOException e) {
2410 Slog.w(LOG_TAG, "failed writing file", e);
2412 if (stream != null) {
2415 } catch (IOException ex) {
2422 private void sendChangedNotification(int userHandle) {
2423 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2424 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2425 long ident = mInjector.binderClearCallingIdentity();
2427 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2429 mInjector.binderRestoreCallingIdentity(ident);
2433 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2434 JournaledFile journal = makeJournaledFile(userHandle);
2435 FileInputStream stream = null;
2436 File file = journal.chooseForRead();
2437 boolean needsRewrite = false;
2439 stream = new FileInputStream(file);
2440 XmlPullParser parser = Xml.newPullParser();
2441 parser.setInput(stream, StandardCharsets.UTF_8.name());
2444 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2445 && type != XmlPullParser.START_TAG) {
2447 String tag = parser.getName();
2448 if (!"policies".equals(tag)) {
2449 throw new XmlPullParserException(
2450 "Settings do not start with policies tag: found " + tag);
2453 // Extract the permission provider component name if available
2454 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2455 if (permissionProvider != null) {
2456 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2458 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2459 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2460 policy.mUserSetupComplete = true;
2462 String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
2463 if (paired != null && Boolean.toString(true).equals(paired)) {
2464 policy.mPaired = true;
2466 String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2467 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2468 if (deviceProvisioningConfigApplied != null
2469 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2470 policy.mDeviceProvisioningConfigApplied = true;
2472 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2473 if (!TextUtils.isEmpty(provisioningState)) {
2474 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2476 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2477 if (!TextUtils.isEmpty(permissionPolicy)) {
2478 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2480 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2481 ATTR_DELEGATED_CERT_INSTALLER);
2482 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2483 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2485 type = parser.next();
2486 int outerDepth = parser.getDepth();
2487 policy.mLockTaskPackages.clear();
2488 policy.mAdminList.clear();
2489 policy.mAdminMap.clear();
2490 policy.mAffiliationIds.clear();
2491 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2492 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2493 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2496 tag = parser.getName();
2497 if ("admin".equals(tag)) {
2498 String name = parser.getAttributeValue(null, "name");
2500 DeviceAdminInfo dai = findAdmin(
2501 ComponentName.unflattenFromString(name), userHandle,
2502 /* throwForMissionPermission= */ false);
2504 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2506 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2507 + dai.getActivityInfo().applicationInfo.uid + " for user "
2511 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2512 ap.readFromXml(parser);
2513 policy.mAdminMap.put(ap.info.getComponent(), ap);
2515 } catch (RuntimeException e) {
2516 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2518 } else if ("failed-password-attempts".equals(tag)) {
2519 policy.mFailedPasswordAttempts = Integer.parseInt(
2520 parser.getAttributeValue(null, "value"));
2521 } else if ("password-owner".equals(tag)) {
2522 policy.mPasswordOwner = Integer.parseInt(
2523 parser.getAttributeValue(null, "value"));
2524 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2525 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2526 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2527 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2528 } else if (TAG_STATUS_BAR.equals(tag)) {
2529 policy.mStatusBarDisabled = Boolean.parseBoolean(
2530 parser.getAttributeValue(null, ATTR_DISABLED));
2531 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2532 policy.doNotAskCredentialsOnBoot = true;
2533 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2534 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2535 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2536 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2537 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2538 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2539 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2540 } else if ("active-password".equals(tag)) {
2541 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2542 // Remove this from FBE devices
2543 needsRewrite = true;
2545 policy.mActivePasswordQuality = Integer.parseInt(
2546 parser.getAttributeValue(null, "quality"));
2547 policy.mActivePasswordLength = Integer.parseInt(
2548 parser.getAttributeValue(null, "length"));
2549 policy.mActivePasswordUpperCase = Integer.parseInt(
2550 parser.getAttributeValue(null, "uppercase"));
2551 policy.mActivePasswordLowerCase = Integer.parseInt(
2552 parser.getAttributeValue(null, "lowercase"));
2553 policy.mActivePasswordLetters = Integer.parseInt(
2554 parser.getAttributeValue(null, "letters"));
2555 policy.mActivePasswordNumeric = Integer.parseInt(
2556 parser.getAttributeValue(null, "numeric"));
2557 policy.mActivePasswordSymbols = Integer.parseInt(
2558 parser.getAttributeValue(null, "symbols"));
2559 policy.mActivePasswordNonLetter = Integer.parseInt(
2560 parser.getAttributeValue(null, "nonletter"));
2563 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2564 XmlUtils.skipCurrentTag(parser);
2567 } catch (FileNotFoundException e) {
2568 // Don't be noisy, this is normal if we haven't defined any policies.
2569 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2570 | IndexOutOfBoundsException e) {
2571 Slog.w(LOG_TAG, "failed parsing " + file, e);
2574 if (stream != null) {
2577 } catch (IOException e) {
2581 // Generate a list of admins from the admin map
2582 policy.mAdminList.addAll(policy.mAdminMap.values());
2584 // Might need to upgrade the file by rewriting it
2586 saveSettingsLocked(userHandle);
2589 validatePasswordOwnerLocked(policy);
2590 updateMaximumTimeToLockLocked(userHandle);
2591 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2592 if (policy.mStatusBarDisabled) {
2593 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2597 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2598 long ident = mInjector.binderClearCallingIdentity();
2600 mInjector.getIActivityManager()
2601 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2602 } catch (RemoteException e) {
2603 // Not gonna happen.
2605 mInjector.binderRestoreCallingIdentity(ident);
2609 private void updateDeviceOwnerLocked() {
2610 long ident = mInjector.binderClearCallingIdentity();
2612 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2613 // user id and also protect all other DAs too.
2614 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2615 if (deviceOwnerComponent != null) {
2616 mInjector.getIActivityManager()
2617 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2619 } catch (RemoteException e) {
2620 // Not gonna happen.
2622 mInjector.binderRestoreCallingIdentity(ident);
2626 static void validateQualityConstant(int quality) {
2628 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2629 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2630 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2631 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2632 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2633 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2634 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2635 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2636 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2639 throw new IllegalArgumentException("Invalid quality constant: 0x"
2640 + Integer.toHexString(quality));
2643 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2644 if (policy.mPasswordOwner >= 0) {
2645 boolean haveOwner = false;
2646 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2647 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2653 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2654 + " no longer active; disabling");
2655 policy.mPasswordOwner = -1;
2661 void systemReady(int phase) {
2666 case SystemService.PHASE_LOCK_SETTINGS_READY:
2667 onLockSettingsReady();
2669 case SystemService.PHASE_BOOT_COMPLETED:
2670 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2675 private void onLockSettingsReady() {
2676 getUserData(UserHandle.USER_SYSTEM);
2680 onStartUser(UserHandle.USER_SYSTEM);
2682 // Register an observer for watching for user setup complete.
2683 new SetupContentObserver(mHandler).register();
2684 // Initialize the user setup state, to handle the upgrade case.
2685 updateUserSetupCompleteAndPaired();
2687 List<String> packageList;
2688 synchronized (this) {
2689 packageList = getKeepUninstalledPackagesLocked();
2691 if (packageList != null) {
2692 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2695 synchronized (this) {
2696 // push the force-ephemeral-users policy to the user manager.
2697 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2698 if (deviceOwner != null) {
2699 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2704 private void ensureDeviceOwnerUserStarted() {
2706 synchronized (this) {
2707 if (!mOwners.hasDeviceOwner()) {
2710 userId = mOwners.getDeviceOwnerUserId();
2713 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2715 if (userId != UserHandle.USER_SYSTEM) {
2717 mInjector.getIActivityManager().startUserInBackground(userId);
2719 // STOPSHIP Prevent the DO user from being killed.
2721 } catch (RemoteException e) {
2722 Slog.w(LOG_TAG, "Exception starting user", e);
2727 private void onStartUser(int userId) {
2728 updateScreenCaptureDisabledInWindowManager(userId,
2729 getScreenCaptureDisabled(null, userId));
2730 pushUserRestrictions(userId);
2733 private void cleanUpOldUsers() {
2734 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2736 Set<Integer> usersWithProfileOwners;
2737 Set<Integer> usersWithData;
2738 synchronized(this) {
2739 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2740 usersWithData = new ArraySet<>();
2741 for (int i = 0; i < mUserData.size(); i++) {
2742 usersWithData.add(mUserData.keyAt(i));
2745 List<UserInfo> allUsers = mUserManager.getUsers();
2747 Set<Integer> deletedUsers = new ArraySet<>();
2748 deletedUsers.addAll(usersWithProfileOwners);
2749 deletedUsers.addAll(usersWithData);
2750 for (UserInfo userInfo : allUsers) {
2751 deletedUsers.remove(userInfo.id);
2753 for (Integer userId : deletedUsers) {
2754 removeUserData(userId);
2758 private void handlePasswordExpirationNotification(int userHandle) {
2759 synchronized (this) {
2760 final long now = System.currentTimeMillis();
2762 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2763 userHandle, /* parent */ false);
2764 final int N = admins.size();
2765 for (int i = 0; i < N; i++) {
2766 ActiveAdmin admin = admins.get(i);
2767 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2768 && admin.passwordExpirationTimeout > 0L
2769 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2770 && admin.passwordExpirationDate > 0L) {
2771 sendAdminCommandLocked(admin,
2772 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2775 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2779 private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2781 protected Void doInBackground(Integer... params) {
2782 int userHandle = params[0];
2784 if (userHandle == UserHandle.USER_ALL) {
2785 for (UserInfo userInfo : mUserManager.getUsers(true)) {
2786 manageNotification(userInfo.getUserHandle());
2789 manageNotification(UserHandle.of(userHandle));
2794 private void manageNotification(UserHandle userHandle) {
2795 if (!mUserManager.isUserUnlocked(userHandle)) {
2799 // Call out to KeyChain to check for CAs which are waiting for approval.
2800 final List<String> pendingCertificates;
2802 pendingCertificates = getInstalledCaCertificates(userHandle);
2803 } catch (RemoteException | RuntimeException e) {
2804 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2808 synchronized (DevicePolicyManagerService.this) {
2809 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2811 // Remove deleted certificates. Flush xml if necessary.
2812 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2813 saveSettingsLocked(userHandle.getIdentifier());
2815 // Trim to approved certificates.
2816 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2819 if (pendingCertificates.isEmpty()) {
2820 mInjector.getNotificationManager().cancelAsUser(
2821 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2825 // Build and show a warning notification
2828 int parentUserId = userHandle.getIdentifier();
2829 if (getProfileOwner(userHandle.getIdentifier()) != null) {
2830 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2831 getProfileOwnerName(userHandle.getIdentifier()));
2832 smallIconId = R.drawable.stat_sys_certificate_info;
2833 parentUserId = getProfileParentId(userHandle.getIdentifier());
2834 } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
2835 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2836 getDeviceOwnerName());
2837 smallIconId = R.drawable.stat_sys_certificate_info;
2839 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2840 smallIconId = android.R.drawable.stat_sys_warning;
2843 final int numberOfCertificates = pendingCertificates.size();
2844 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2845 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2846 dialogIntent.setPackage("com.android.settings");
2847 dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
2848 dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
2849 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2850 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
2851 new UserHandle(parentUserId));
2853 final Context userContext;
2855 final String packageName = mContext.getPackageName();
2856 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
2857 } catch (PackageManager.NameNotFoundException e) {
2858 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2861 final Notification noti = new Notification.Builder(userContext)
2862 .setSmallIcon(smallIconId)
2863 .setContentTitle(mContext.getResources().getQuantityText(
2864 R.plurals.ssl_ca_cert_warning, numberOfCertificates))
2865 .setContentText(contentText)
2866 .setContentIntent(notifyIntent)
2867 .setPriority(Notification.PRIORITY_HIGH)
2869 .setColor(mContext.getColor(
2870 com.android.internal.R.color.system_notification_accent_color))
2873 mInjector.getNotificationManager().notifyAsUser(
2874 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2877 private List<String> getInstalledCaCertificates(UserHandle userHandle)
2878 throws RemoteException, RuntimeException {
2879 KeyChainConnection conn = null;
2881 conn = KeyChain.bindAsUser(mContext, userHandle);
2882 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
2883 List<String> result = new ArrayList<>(aliases.size());
2884 for (int i = 0; i < aliases.size(); i++) {
2885 result.add(aliases.get(i).string);
2888 } catch (InterruptedException e) {
2889 Thread.currentThread().interrupt();
2891 } catch (AssertionError e) {
2892 throw new RuntimeException(e);
2902 * @param adminReceiver The admin to add
2903 * @param refreshing true = update an active admin, no error
2906 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2910 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2913 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2914 Bundle onEnableData) {
2915 mContext.enforceCallingOrSelfPermission(
2916 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2917 enforceFullCrossUsersPermission(userHandle);
2919 DevicePolicyData policy = getUserData(userHandle);
2920 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2921 /* throwForMissionPermission= */ true);
2923 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2925 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2926 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2929 synchronized (this) {
2930 long ident = mInjector.binderClearCallingIdentity();
2932 final ActiveAdmin existingAdmin
2933 = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2934 if (!refreshing && existingAdmin != null) {
2935 throw new IllegalArgumentException("Admin is already added");
2937 if (policy.mRemovingAdmins.contains(adminReceiver)) {
2938 throw new IllegalArgumentException(
2939 "Trying to set an admin which is being removed");
2941 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2942 newAdmin.testOnlyAdmin =
2943 (existingAdmin != null) ? existingAdmin.testOnlyAdmin
2944 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
2945 policy.mAdminMap.put(adminReceiver, newAdmin);
2946 int replaceIndex = -1;
2947 final int N = policy.mAdminList.size();
2948 for (int i=0; i < N; i++) {
2949 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2950 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2955 if (replaceIndex == -1) {
2956 policy.mAdminList.add(newAdmin);
2957 enableIfNecessary(info.getPackageName(), userHandle);
2959 policy.mAdminList.set(replaceIndex, newAdmin);
2961 saveSettingsLocked(userHandle);
2962 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2963 onEnableData, null);
2965 mInjector.binderRestoreCallingIdentity(ident);
2971 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2975 enforceFullCrossUsersPermission(userHandle);
2976 synchronized (this) {
2977 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2982 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2986 enforceFullCrossUsersPermission(userHandle);
2987 synchronized (this) {
2988 DevicePolicyData policyData = getUserData(userHandle);
2989 return policyData.mRemovingAdmins.contains(adminReceiver);
2994 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2998 enforceFullCrossUsersPermission(userHandle);
2999 synchronized (this) {
3000 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3001 if (administrator == null) {
3002 throw new SecurityException("No active admin " + adminReceiver);
3004 return administrator.info.usesPolicy(policyId);
3009 @SuppressWarnings("unchecked")
3010 public List<ComponentName> getActiveAdmins(int userHandle) {
3012 return Collections.EMPTY_LIST;
3015 enforceFullCrossUsersPermission(userHandle);
3016 synchronized (this) {
3017 DevicePolicyData policy = getUserData(userHandle);
3018 final int N = policy.mAdminList.size();
3022 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3023 for (int i=0; i<N; i++) {
3024 res.add(policy.mAdminList.get(i).info.getComponent());
3031 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
3035 enforceFullCrossUsersPermission(userHandle);
3036 synchronized (this) {
3037 DevicePolicyData policy = getUserData(userHandle);
3038 final int N = policy.mAdminList.size();
3039 for (int i=0; i<N; i++) {
3040 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
3048 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
3052 Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
3053 enforceShell("forceRemoveActiveAdmin");
3054 long ident = mInjector.binderClearCallingIdentity();
3056 synchronized (this) {
3057 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
3058 throw new SecurityException("Attempt to remove non-test admin "
3059 + adminReceiver + " " + userHandle);
3062 // If admin is a device or profile owner tidy that up first.
3063 if (isDeviceOwner(adminReceiver, userHandle)) {
3064 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3066 if (isProfileOwner(adminReceiver, userHandle)) {
3067 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3068 userHandle, /* parent */ false);
3069 clearProfileOwnerLocked(admin, userHandle);
3072 // Remove the admin skipping sending the broadcast.
3073 removeAdminArtifacts(adminReceiver, userHandle);
3074 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3076 mInjector.binderRestoreCallingIdentity(ident);
3081 * Return if a given package has testOnly="true", in which case we'll relax certain rules
3084 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked}
3085 * to check wehter an active admin is test-only or not.
3087 * The system allows this flag to be changed when an app is updated, which is not good
3088 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3089 * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3091 private boolean isPackageTestOnly(String packageName, int userHandle) {
3092 final ApplicationInfo ai;
3094 ai = mIPackageManager.getApplicationInfo(packageName,
3095 (PackageManager.MATCH_DIRECT_BOOT_AWARE
3096 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3097 } catch (RemoteException e) {
3098 throw new IllegalStateException(e);
3101 throw new IllegalStateException("Couldn't find package: "
3102 + packageName + " on user " + userHandle);
3104 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3108 * See {@link #isPackageTestOnly}.
3110 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3111 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3112 return (admin != null) && admin.testOnlyAdmin;
3115 private void enforceShell(String method) {
3116 final int callingUid = Binder.getCallingUid();
3117 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3118 throw new SecurityException("Non-shell user attempted to call " + method);
3123 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3127 enforceFullCrossUsersPermission(userHandle);
3128 enforceUserUnlocked(userHandle);
3129 synchronized (this) {
3130 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3131 if (admin == null) {
3134 // Active device/profile owners must remain active admins.
3135 if (isDeviceOwner(adminReceiver, userHandle)
3136 || isProfileOwner(adminReceiver, userHandle)) {
3137 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3141 if (admin.getUid() != mInjector.binderGetCallingUid()) {
3142 mContext.enforceCallingOrSelfPermission(
3143 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3145 long ident = mInjector.binderClearCallingIdentity();
3147 removeActiveAdminLocked(adminReceiver, userHandle);
3149 mInjector.binderRestoreCallingIdentity(ident);
3155 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3156 ComponentName profileOwner = getProfileOwner(userHandle);
3157 // Profile challenge is supported on N or newer release.
3158 return profileOwner != null &&
3159 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3163 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3167 Preconditions.checkNotNull(who, "ComponentName is null");
3168 validateQualityConstant(quality);
3170 synchronized (this) {
3171 ActiveAdmin ap = getActiveAdminForCallerLocked(
3172 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3173 if (ap.passwordQuality != quality) {
3174 ap.passwordQuality = quality;
3175 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3181 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3183 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3185 enforceFullCrossUsersPermission(userHandle);
3186 synchronized (this) {
3187 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3190 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3191 return admin != null ? admin.passwordQuality : mode;
3194 // Return the strictest policy across all participating admins.
3195 List<ActiveAdmin> admins =
3196 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3197 final int N = admins.size();
3198 for (int i = 0; i < N; i++) {
3199 ActiveAdmin admin = admins.get(i);
3200 if (mode < admin.passwordQuality) {
3201 mode = admin.passwordQuality;
3208 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3209 int userHandle, boolean parent) {
3210 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3211 // If this user has a separate challenge, only return its restrictions.
3212 return getUserDataUnchecked(userHandle).mAdminList;
3214 // Return all admins for this user and the profiles that are visible from this
3215 // user that do not use a separate work challenge.
3216 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3217 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3218 DevicePolicyData policy = getUserData(userInfo.id);
3219 if (!userInfo.isManagedProfile()) {
3220 admins.addAll(policy.mAdminList);
3222 // For managed profiles, we always include the policies set on the parent
3223 // profile. Additionally, we include the ones set on the managed profile
3224 // if no separate challenge is in place.
3225 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3226 final int N = policy.mAdminList.size();
3227 for (int i = 0; i < N; i++) {
3228 ActiveAdmin admin = policy.mAdminList.get(i);
3229 if (admin.hasParentActiveAdmin()) {
3230 admins.add(admin.getParentActiveAdmin());
3232 if (!hasSeparateChallenge) {
3242 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3243 long ident = mInjector.binderClearCallingIdentity();
3245 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3247 mInjector.binderRestoreCallingIdentity(ident);
3252 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3256 Preconditions.checkNotNull(who, "ComponentName is null");
3257 synchronized (this) {
3258 ActiveAdmin ap = getActiveAdminForCallerLocked(
3259 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3260 if (ap.minimumPasswordLength != length) {
3261 ap.minimumPasswordLength = length;
3262 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3268 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3272 enforceFullCrossUsersPermission(userHandle);
3273 synchronized (this) {
3277 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3278 return admin != null ? admin.minimumPasswordLength : length;
3281 // Return the strictest policy across all participating admins.
3282 List<ActiveAdmin> admins =
3283 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3284 final int N = admins.size();
3285 for (int i = 0; i < N; i++) {
3286 ActiveAdmin admin = admins.get(i);
3287 if (length < admin.minimumPasswordLength) {
3288 length = admin.minimumPasswordLength;
3296 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3300 Preconditions.checkNotNull(who, "ComponentName is null");
3301 synchronized (this) {
3302 ActiveAdmin ap = getActiveAdminForCallerLocked(
3303 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3304 if (ap.passwordHistoryLength != length) {
3305 ap.passwordHistoryLength = length;
3306 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3312 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3316 enforceFullCrossUsersPermission(userHandle);
3317 synchronized (this) {
3321 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3322 return admin != null ? admin.passwordHistoryLength : length;
3325 // Return the strictest policy across all participating admins.
3326 List<ActiveAdmin> admins =
3327 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3328 final int N = admins.size();
3329 for (int i = 0; i < N; i++) {
3330 ActiveAdmin admin = admins.get(i);
3331 if (length < admin.passwordHistoryLength) {
3332 length = admin.passwordHistoryLength;
3341 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3345 Preconditions.checkNotNull(who, "ComponentName is null");
3346 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3347 final int userHandle = mInjector.userHandleGetCallingUserId();
3348 synchronized (this) {
3349 ActiveAdmin ap = getActiveAdminForCallerLocked(
3350 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3351 // Calling this API automatically bumps the expiration date
3352 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3353 ap.passwordExpirationDate = expiration;
3354 ap.passwordExpirationTimeout = timeout;
3356 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3357 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3358 .format(new Date(expiration)));
3360 saveSettingsLocked(userHandle);
3362 // in case this is the first one, set the alarm on the appropriate user.
3363 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3368 * Return a single admin's expiration cycle time, or the min of all cycle times.
3369 * Returns 0 if not configured.
3372 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3376 enforceFullCrossUsersPermission(userHandle);
3377 synchronized (this) {
3381 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3382 return admin != null ? admin.passwordExpirationTimeout : timeout;
3385 // Return the strictest policy across all participating admins.
3386 List<ActiveAdmin> admins =
3387 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3388 final int N = admins.size();
3389 for (int i = 0; i < N; i++) {
3390 ActiveAdmin admin = admins.get(i);
3391 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3392 && timeout > admin.passwordExpirationTimeout)) {
3393 timeout = admin.passwordExpirationTimeout;
3401 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3402 final int userId = UserHandle.getCallingUserId();
3403 List<String> changedProviders = null;
3405 synchronized (this) {
3406 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3407 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3408 if (activeAdmin.crossProfileWidgetProviders == null) {
3409 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3411 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3412 if (!providers.contains(packageName)) {
3413 providers.add(packageName);
3414 changedProviders = new ArrayList<>(providers);
3415 saveSettingsLocked(userId);
3419 if (changedProviders != null) {
3420 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3428 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3429 final int userId = UserHandle.getCallingUserId();
3430 List<String> changedProviders = null;
3432 synchronized (this) {
3433 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3434 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3435 if (activeAdmin.crossProfileWidgetProviders == null) {
3438 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3439 if (providers.remove(packageName)) {
3440 changedProviders = new ArrayList<>(providers);
3441 saveSettingsLocked(userId);
3445 if (changedProviders != null) {
3446 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3454 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3455 synchronized (this) {
3456 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3457 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3458 if (activeAdmin.crossProfileWidgetProviders == null
3459 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3462 if (mInjector.binderIsCallingUidMyUid()) {
3463 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3465 return activeAdmin.crossProfileWidgetProviders;
3471 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3472 * Returns 0 if not configured.
3474 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3478 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3479 return admin != null ? admin.passwordExpirationDate : timeout;
3482 // Return the strictest policy across all participating admins.
3483 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3484 final int N = admins.size();
3485 for (int i = 0; i < N; i++) {
3486 ActiveAdmin admin = admins.get(i);
3487 if (timeout == 0L || (admin.passwordExpirationDate != 0
3488 && timeout > admin.passwordExpirationDate)) {
3489 timeout = admin.passwordExpirationDate;
3496 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3500 enforceFullCrossUsersPermission(userHandle);
3501 synchronized (this) {
3502 return getPasswordExpirationLocked(who, userHandle, parent);
3507 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3511 Preconditions.checkNotNull(who, "ComponentName is null");
3512 synchronized (this) {
3513 ActiveAdmin ap = getActiveAdminForCallerLocked(
3514 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3515 if (ap.minimumPasswordUpperCase != length) {
3516 ap.minimumPasswordUpperCase = length;
3517 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3523 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3527 enforceFullCrossUsersPermission(userHandle);
3528 synchronized (this) {
3532 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3533 return admin != null ? admin.minimumPasswordUpperCase : length;
3536 // Return the strictest policy across all participating admins.
3537 List<ActiveAdmin> admins =
3538 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3539 final int N = admins.size();
3540 for (int i = 0; i < N; i++) {
3541 ActiveAdmin admin = admins.get(i);
3542 if (length < admin.minimumPasswordUpperCase) {
3543 length = admin.minimumPasswordUpperCase;
3551 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3552 Preconditions.checkNotNull(who, "ComponentName is null");
3553 synchronized (this) {
3554 ActiveAdmin ap = getActiveAdminForCallerLocked(
3555 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3556 if (ap.minimumPasswordLowerCase != length) {
3557 ap.minimumPasswordLowerCase = length;
3558 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3564 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3568 enforceFullCrossUsersPermission(userHandle);
3569 synchronized (this) {
3573 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3574 return admin != null ? admin.minimumPasswordLowerCase : length;
3577 // Return the strictest policy across all participating admins.
3578 List<ActiveAdmin> admins =
3579 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3580 final int N = admins.size();
3581 for (int i = 0; i < N; i++) {
3582 ActiveAdmin admin = admins.get(i);
3583 if (length < admin.minimumPasswordLowerCase) {
3584 length = admin.minimumPasswordLowerCase;
3592 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3596 Preconditions.checkNotNull(who, "ComponentName is null");
3597 synchronized (this) {
3598 ActiveAdmin ap = getActiveAdminForCallerLocked(
3599 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3600 if (ap.minimumPasswordLetters != length) {
3601 ap.minimumPasswordLetters = length;
3602 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3608 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3612 enforceFullCrossUsersPermission(userHandle);
3613 synchronized (this) {
3617 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3618 return admin != null ? admin.minimumPasswordLetters : length;
3621 // Return the strictest policy across all participating admins.
3622 List<ActiveAdmin> admins =
3623 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3624 final int N = admins.size();
3625 for (int i = 0; i < N; i++) {
3626 ActiveAdmin admin = admins.get(i);
3627 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3630 if (length < admin.minimumPasswordLetters) {
3631 length = admin.minimumPasswordLetters;
3639 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3643 Preconditions.checkNotNull(who, "ComponentName is null");
3644 synchronized (this) {
3645 ActiveAdmin ap = getActiveAdminForCallerLocked(
3646 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3647 if (ap.minimumPasswordNumeric != length) {
3648 ap.minimumPasswordNumeric = length;
3649 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3655 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3659 enforceFullCrossUsersPermission(userHandle);
3660 synchronized (this) {
3664 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3665 return admin != null ? admin.minimumPasswordNumeric : length;
3668 // Return the strictest policy across all participating admins.
3669 List<ActiveAdmin> admins =
3670 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3671 final int N = admins.size();
3672 for (int i = 0; i < N; i++) {
3673 ActiveAdmin admin = admins.get(i);
3674 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3677 if (length < admin.minimumPasswordNumeric) {
3678 length = admin.minimumPasswordNumeric;
3686 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3690 Preconditions.checkNotNull(who, "ComponentName is null");
3691 synchronized (this) {
3692 ActiveAdmin ap = getActiveAdminForCallerLocked(
3693 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3694 if (ap.minimumPasswordSymbols != length) {
3695 ap.minimumPasswordSymbols = length;
3696 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3702 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3706 enforceFullCrossUsersPermission(userHandle);
3707 synchronized (this) {
3711 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3712 return admin != null ? admin.minimumPasswordSymbols : length;
3715 // Return the strictest policy across all participating admins.
3716 List<ActiveAdmin> admins =
3717 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3718 final int N = admins.size();
3719 for (int i = 0; i < N; i++) {
3720 ActiveAdmin admin = admins.get(i);
3721 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3724 if (length < admin.minimumPasswordSymbols) {
3725 length = admin.minimumPasswordSymbols;
3733 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3737 Preconditions.checkNotNull(who, "ComponentName is null");
3738 synchronized (this) {
3739 ActiveAdmin ap = getActiveAdminForCallerLocked(
3740 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3741 if (ap.minimumPasswordNonLetter != length) {
3742 ap.minimumPasswordNonLetter = length;
3743 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3749 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3753 enforceFullCrossUsersPermission(userHandle);
3754 synchronized (this) {
3758 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3759 return admin != null ? admin.minimumPasswordNonLetter : length;
3762 // Return the strictest policy across all participating admins.
3763 List<ActiveAdmin> admins =
3764 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3765 final int N = admins.size();
3766 for (int i = 0; i < N; i++) {
3767 ActiveAdmin admin = admins.get(i);
3768 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3771 if (length < admin.minimumPasswordNonLetter) {
3772 length = admin.minimumPasswordNonLetter;
3780 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3784 enforceFullCrossUsersPermission(userHandle);
3786 synchronized (this) {
3787 // This API can only be called by an active device admin,
3788 // so try to retrieve it to check that the caller is one.
3789 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3790 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3791 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3796 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3800 enforceFullCrossUsersPermission(userHandle);
3801 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3803 synchronized (this) {
3804 int targetUser = getProfileParentId(userHandle);
3805 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3806 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3810 private boolean isActivePasswordSufficientForUserLocked(
3811 DevicePolicyData policy, int userHandle, boolean parent) {
3812 enforceUserUnlocked(userHandle, parent);
3814 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
3815 if (policy.mActivePasswordQuality < requiredPasswordQuality) {
3818 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
3819 && policy.mActivePasswordLength < getPasswordMinimumLength(
3820 null, userHandle, parent)) {
3823 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3826 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3827 null, userHandle, parent)
3828 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3829 null, userHandle, parent)
3830 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3831 null, userHandle, parent)
3832 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3833 null, userHandle, parent)
3834 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3835 null, userHandle, parent)
3836 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3837 null, userHandle, parent);
3841 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3842 enforceFullCrossUsersPermission(userHandle);
3843 synchronized (this) {
3844 if (!isCallerWithSystemUid()) {
3845 // This API can only be called by an active device admin,
3846 // so try to retrieve it to check that the caller is one.
3847 getActiveAdminForCallerLocked(
3848 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3851 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3853 return policy.mFailedPasswordAttempts;
3858 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3862 Preconditions.checkNotNull(who, "ComponentName is null");
3863 synchronized (this) {
3864 // This API can only be called by an active device admin,
3865 // so try to retrieve it to check that the caller is one.
3866 getActiveAdminForCallerLocked(
3867 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3868 ActiveAdmin ap = getActiveAdminForCallerLocked(
3869 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3870 if (ap.maximumFailedPasswordsForWipe != num) {
3871 ap.maximumFailedPasswordsForWipe = num;
3872 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3878 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3882 enforceFullCrossUsersPermission(userHandle);
3883 synchronized (this) {
3884 ActiveAdmin admin = (who != null)
3885 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3886 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3887 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3892 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3894 return UserHandle.USER_NULL;
3896 enforceFullCrossUsersPermission(userHandle);
3897 synchronized (this) {
3898 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3899 userHandle, parent);
3900 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3905 * Returns the admin with the strictest policy on maximum failed passwords for:
3907 * <li>this user if it has a separate profile challenge, or
3908 * <li>this user and all profiles that don't have their own challenge otherwise.
3910 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3911 * the primary profile.
3912 * Returns {@code null} if no participating admin has that policy set.
3914 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3915 int userHandle, boolean parent) {
3917 ActiveAdmin strictestAdmin = null;
3919 // Return the strictest policy across all participating admins.
3920 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3921 final int N = admins.size();
3922 for (int i = 0; i < N; i++) {
3923 ActiveAdmin admin = admins.get(i);
3924 if (admin.maximumFailedPasswordsForWipe ==
3925 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3926 continue; // No max number of failed passwords policy set for this profile.
3929 // We always favor the primary profile if several profiles have the same value set.
3930 int userId = admin.getUserHandle().getIdentifier();
3932 count > admin.maximumFailedPasswordsForWipe ||
3933 (count == admin.maximumFailedPasswordsForWipe &&
3934 getUserInfo(userId).isPrimary())) {
3935 count = admin.maximumFailedPasswordsForWipe;
3936 strictestAdmin = admin;
3939 return strictestAdmin;
3942 private UserInfo getUserInfo(@UserIdInt int userId) {
3943 final long token = mInjector.binderClearCallingIdentity();
3945 return mUserManager.getUserInfo(userId);
3947 mInjector.binderRestoreCallingIdentity(token);
3952 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3956 final int callingUid = mInjector.binderGetCallingUid();
3957 final int userHandle = mInjector.userHandleGetCallingUserId();
3959 String password = passwordOrNull != null ? passwordOrNull : "";
3961 // Password resetting to empty/null is not allowed for managed profiles.
3962 if (TextUtils.isEmpty(password)) {
3963 enforceNotManagedProfile(userHandle, "clear the active password");
3967 synchronized (this) {
3968 // If caller has PO (or DO) it can change the password, so see if that's the case first.
3969 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3970 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3972 if (admin != null) {
3973 preN = getTargetSdk(admin.info.getPackageName(),
3974 userHandle) <= android.os.Build.VERSION_CODES.M;
3976 // Otherwise, make sure the caller has any active admin with the right policy.
3977 admin = getActiveAdminForCallerLocked(null,
3978 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3979 preN = getTargetSdk(admin.info.getPackageName(),
3980 userHandle) <= android.os.Build.VERSION_CODES.M;
3982 // As of N, password resetting to empty/null is not allowed anymore.
3983 // TODO Should we allow DO/PO to set an empty password?
3984 if (TextUtils.isEmpty(password)) {
3986 throw new SecurityException("Cannot call with null password");
3988 Slog.e(LOG_TAG, "Cannot call with null password");
3992 // As of N, password cannot be changed by the admin if it is already set.
3993 if (isLockScreenSecureUnchecked(userHandle)) {
3995 throw new SecurityException("Admin cannot change current password");
3997 Slog.e(LOG_TAG, "Admin cannot change current password");
4002 // Do not allow to reset password when current user has a managed profile
4003 if (!isManagedProfile(userHandle)) {
4004 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4005 if (userInfo.isManagedProfile()) {
4007 throw new IllegalStateException(
4008 "Cannot reset password on user has managed profile");
4010 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
4016 // Do not allow to reset password when user is locked
4017 if (!mUserManager.isUserUnlocked(userHandle)) {
4019 throw new IllegalStateException("Cannot reset password when user is locked");
4021 Slog.e(LOG_TAG, "Cannot reset password when user is locked");
4026 quality = getPasswordQuality(null, userHandle, /* parent */ false);
4027 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
4028 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4030 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
4031 int realQuality = LockPatternUtils.computePasswordQuality(password);
4032 if (realQuality < quality
4033 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4034 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
4035 + Integer.toHexString(realQuality)
4036 + " does not meet required quality 0x"
4037 + Integer.toHexString(quality));
4040 quality = Math.max(realQuality, quality);
4042 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
4043 if (password.length() < length) {
4044 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
4045 + " does not meet required length " + length);
4048 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4055 for (int i = 0; i < password.length(); i++) {
4056 char c = password.charAt(i);
4057 if (c >= 'A' && c <= 'Z') {
4060 } else if (c >= 'a' && c <= 'z') {
4063 } else if (c >= '0' && c <= '9') {
4071 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4072 if(letters < neededLetters) {
4073 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
4074 + " does not meet required number of letters " + neededLetters);
4077 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4078 if (numbers < neededNumbers) {
4079 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
4080 + " does not meet required number of numerical digits "
4084 int neededLowerCase = getPasswordMinimumLowerCase(
4085 null, userHandle, /* parent */ false);
4086 if (lowercase < neededLowerCase) {
4087 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
4088 + " does not meet required number of lowercase letters "
4092 int neededUpperCase = getPasswordMinimumUpperCase(
4093 null, userHandle, /* parent */ false);
4094 if (uppercase < neededUpperCase) {
4095 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
4096 + " does not meet required number of uppercase letters "
4100 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4101 if (symbols < neededSymbols) {
4102 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
4103 + " does not meet required number of special symbols " + neededSymbols);
4106 int neededNonLetter = getPasswordMinimumNonLetter(
4107 null, userHandle, /* parent */ false);
4108 if (nonletter < neededNonLetter) {
4109 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
4110 + " does not meet required number of non-letter characters "
4117 DevicePolicyData policy = getUserData(userHandle);
4118 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4119 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4123 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4124 boolean doNotAskCredentialsOnBoot =
4125 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4126 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4127 setDoNotAskCredentialsOnBoot();
4130 // Don't do this with the lock held, because it is going to call
4131 // back in to the service.
4132 final long ident = mInjector.binderClearCallingIdentity();
4134 if (!TextUtils.isEmpty(password)) {
4135 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4137 mLockPatternUtils.clearLock(userHandle);
4139 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4141 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4142 UserHandle.USER_ALL);
4144 synchronized (this) {
4145 int newOwner = requireEntry ? callingUid : -1;
4146 if (policy.mPasswordOwner != newOwner) {
4147 policy.mPasswordOwner = newOwner;
4148 saveSettingsLocked(userHandle);
4152 mInjector.binderRestoreCallingIdentity(ident);
4158 private boolean isLockScreenSecureUnchecked(int userId) {
4159 long ident = mInjector.binderClearCallingIdentity();
4161 return mLockPatternUtils.isSecure(userId);
4163 mInjector.binderRestoreCallingIdentity(ident);
4167 private void setDoNotAskCredentialsOnBoot() {
4168 synchronized (this) {
4169 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4170 if (!policyData.doNotAskCredentialsOnBoot) {
4171 policyData.doNotAskCredentialsOnBoot = true;
4172 saveSettingsLocked(UserHandle.USER_SYSTEM);
4178 public boolean getDoNotAskCredentialsOnBoot() {
4179 mContext.enforceCallingOrSelfPermission(
4180 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4181 synchronized (this) {
4182 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4183 return policyData.doNotAskCredentialsOnBoot;
4188 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4192 Preconditions.checkNotNull(who, "ComponentName is null");
4193 final int userHandle = mInjector.userHandleGetCallingUserId();
4194 synchronized (this) {
4195 ActiveAdmin ap = getActiveAdminForCallerLocked(
4196 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4197 if (ap.maximumTimeToUnlock != timeMs) {
4198 ap.maximumTimeToUnlock = timeMs;
4199 saveSettingsLocked(userHandle);
4200 updateMaximumTimeToLockLocked(userHandle);
4205 void updateMaximumTimeToLockLocked(int userHandle) {
4206 // Calculate the min timeout for all profiles - including the ones with a separate
4207 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4208 // challenge only and keep the screen on. However there is no easy way of doing that at the
4209 // moment so we set the screen off timeout regardless of whether it affects the parent user
4210 // or the profile challenge only.
4211 long timeMs = Long.MAX_VALUE;
4212 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4213 for (int profileId : profileIds) {
4214 DevicePolicyData policy = getUserDataUnchecked(profileId);
4215 final int N = policy.mAdminList.size();
4216 for (int i = 0; i < N; i++) {
4217 ActiveAdmin admin = policy.mAdminList.get(i);
4218 if (admin.maximumTimeToUnlock > 0
4219 && timeMs > admin.maximumTimeToUnlock) {
4220 timeMs = admin.maximumTimeToUnlock;
4222 // If userInfo.id is a managed profile, we also need to look at
4223 // the policies set on the parent.
4224 if (admin.hasParentActiveAdmin()) {
4225 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4226 if (parentAdmin.maximumTimeToUnlock > 0
4227 && timeMs > parentAdmin.maximumTimeToUnlock) {
4228 timeMs = parentAdmin.maximumTimeToUnlock;
4234 // We only store the last maximum time to lock on the parent profile. So if calling from a
4235 // managed profile, retrieve the policy for the parent.
4236 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4237 if (policy.mLastMaximumTimeToLock == timeMs) {
4240 policy.mLastMaximumTimeToLock = timeMs;
4242 final long ident = mInjector.binderClearCallingIdentity();
4244 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4245 // Make sure KEEP_SCREEN_ON is disabled, since that
4246 // would allow bypassing of the maximum time to lock.
4247 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4250 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4251 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4253 mInjector.binderRestoreCallingIdentity(ident);
4258 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4262 enforceFullCrossUsersPermission(userHandle);
4263 synchronized (this) {
4265 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4266 return admin != null ? admin.maximumTimeToUnlock : 0;
4268 // Return the strictest policy across all participating admins.
4269 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4270 userHandle, parent);
4271 return getMaximumTimeToLockPolicyFromAdmins(admins);
4276 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4280 enforceFullCrossUsersPermission(userHandle);
4281 synchronized (this) {
4282 // All admins for this user.
4283 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4284 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4285 DevicePolicyData policy = getUserData(userInfo.id);
4286 admins.addAll(policy.mAdminList);
4287 // If it is a managed profile, it may have parent active admins
4288 if (userInfo.isManagedProfile()) {
4289 for (ActiveAdmin admin : policy.mAdminList) {
4290 if (admin.hasParentActiveAdmin()) {
4291 admins.add(admin.getParentActiveAdmin());
4296 return getMaximumTimeToLockPolicyFromAdmins(admins);
4300 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4302 final int N = admins.size();
4303 for (int i = 0; i < N; i++) {
4304 ActiveAdmin admin = admins.get(i);
4306 time = admin.maximumTimeToUnlock;
4307 } else if (admin.maximumTimeToUnlock != 0
4308 && time > admin.maximumTimeToUnlock) {
4309 time = admin.maximumTimeToUnlock;
4316 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
4321 Preconditions.checkNotNull(who, "ComponentName is null");
4322 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
4323 // timeoutMs with value 0 means that the admin doesn't participate
4324 // timeoutMs is clamped to the interval in case the internal constants change in the future
4325 if (timeoutMs != 0 && timeoutMs < MINIMUM_STRONG_AUTH_TIMEOUT_MS) {
4326 timeoutMs = MINIMUM_STRONG_AUTH_TIMEOUT_MS;
4328 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
4329 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4332 final int userHandle = mInjector.userHandleGetCallingUserId();
4333 synchronized (this) {
4334 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4335 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4336 if (ap.strongAuthUnlockTimeout != timeoutMs) {
4337 ap.strongAuthUnlockTimeout = timeoutMs;
4338 saveSettingsLocked(userHandle);
4344 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
4345 * admins if who is null.
4346 * Returns 0 if not configured for the provided admin.
4349 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
4351 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4353 enforceFullCrossUsersPermission(userId);
4354 synchronized (this) {
4356 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
4357 return admin != null ? admin.strongAuthUnlockTimeout : 0;
4360 // Return the strictest policy across all participating admins.
4361 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
4363 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4364 for (int i = 0; i < admins.size(); i++) {
4365 final long timeout = admins.get(i).strongAuthUnlockTimeout;
4366 if (timeout != 0) { // take only participating admins into account
4367 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
4370 return Math.max(strongAuthUnlockTimeout, MINIMUM_STRONG_AUTH_TIMEOUT_MS);
4375 public void lockNow(boolean parent) {
4379 synchronized (this) {
4380 // This API can only be called by an active device admin,
4381 // so try to retrieve it to check that the caller is one.
4382 getActiveAdminForCallerLocked(
4383 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4385 int userToLock = mInjector.userHandleGetCallingUserId();
4387 // Unless this is a managed profile with work challenge enabled, lock all users.
4388 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4389 userToLock = UserHandle.USER_ALL;
4391 final long ident = mInjector.binderClearCallingIdentity();
4393 mLockPatternUtils.requireStrongAuth(
4394 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4395 if (userToLock == UserHandle.USER_ALL) {
4396 // Power off the display
4397 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4398 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4399 mInjector.getIWindowManager().lockNow(null);
4401 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4403 } catch (RemoteException e) {
4405 mInjector.binderRestoreCallingIdentity(ident);
4411 public void enforceCanManageCaCerts(ComponentName who) {
4413 if (!isCallerDelegatedCertInstaller()) {
4414 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4417 synchronized (this) {
4418 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4423 private void enforceCanManageInstalledKeys(ComponentName who) {
4425 if (!isCallerDelegatedCertInstaller()) {
4426 throw new SecurityException("who == null, but caller is not cert installer");
4429 synchronized (this) {
4430 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4435 private boolean isCallerDelegatedCertInstaller() {
4436 final int callingUid = mInjector.binderGetCallingUid();
4437 final int userHandle = UserHandle.getUserId(callingUid);
4438 synchronized (this) {
4439 final DevicePolicyData policy = getUserData(userHandle);
4440 if (policy.mDelegatedCertInstallerPackage == null) {
4445 int uid = mContext.getPackageManager().getPackageUidAsUser(
4446 policy.mDelegatedCertInstallerPackage, userHandle);
4447 return uid == callingUid;
4448 } catch (NameNotFoundException e) {
4455 public boolean approveCaCert(String alias, int userId, boolean approval) {
4456 enforceManageUsers();
4457 synchronized (this) {
4458 Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4459 boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4463 saveSettingsLocked(userId);
4465 new MonitoringCertNotificationTask().execute(userId);
4470 public boolean isCaCertApproved(String alias, int userId) {
4471 enforceManageUsers();
4472 synchronized (this) {
4473 return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4477 private void removeCaApprovalsIfNeeded(int userId) {
4478 for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4479 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4480 if (userInfo.isManagedProfile()){
4481 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4484 synchronized (this) {
4485 getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4486 saveSettingsLocked(userInfo.id);
4489 new MonitoringCertNotificationTask().execute(userInfo.id);
4495 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4496 enforceCanManageCaCerts(admin);
4500 X509Certificate cert = parseCert(certBuffer);
4501 pemCert = Credentials.convertToPem(cert);
4502 } catch (CertificateException ce) {
4503 Log.e(LOG_TAG, "Problem converting cert", ce);
4505 } catch (IOException ioe) {
4506 Log.e(LOG_TAG, "Problem reading cert", ioe);
4510 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4511 final long id = mInjector.binderClearCallingIdentity();
4513 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4515 keyChainConnection.getService().installCaCertificate(pemCert);
4517 } catch (RemoteException e) {
4518 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4520 keyChainConnection.close();
4522 } catch (InterruptedException e1) {
4523 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4524 Thread.currentThread().interrupt();
4526 mInjector.binderRestoreCallingIdentity(id);
4531 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4532 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4533 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4538 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4539 enforceCanManageCaCerts(admin);
4541 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4542 final long id = mInjector.binderClearCallingIdentity();
4544 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4546 for (int i = 0 ; i < aliases.length; i++) {
4547 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4549 } catch (RemoteException e) {
4550 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4552 keyChainConnection.close();
4554 } catch (InterruptedException ie) {
4555 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4556 Thread.currentThread().interrupt();
4558 mInjector.binderRestoreCallingIdentity(id);
4563 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4564 String alias, boolean requestAccess) {
4565 enforceCanManageInstalledKeys(who);
4567 final int callingUid = mInjector.binderGetCallingUid();
4568 final long id = mInjector.binderClearCallingIdentity();
4570 final KeyChainConnection keyChainConnection =
4571 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4573 IKeyChainService keyChain = keyChainConnection.getService();
4574 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4577 if (requestAccess) {
4578 keyChain.setGrant(callingUid, alias, true);
4581 } catch (RemoteException e) {
4582 Log.e(LOG_TAG, "Installing certificate", e);
4584 keyChainConnection.close();
4586 } catch (InterruptedException e) {
4587 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4588 Thread.currentThread().interrupt();
4590 mInjector.binderRestoreCallingIdentity(id);
4596 public boolean removeKeyPair(ComponentName who, String alias) {
4597 enforceCanManageInstalledKeys(who);
4599 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4600 final long id = Binder.clearCallingIdentity();
4602 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4604 IKeyChainService keyChain = keyChainConnection.getService();
4605 return keyChain.removeKeyPair(alias);
4606 } catch (RemoteException e) {
4607 Log.e(LOG_TAG, "Removing keypair", e);
4609 keyChainConnection.close();
4611 } catch (InterruptedException e) {
4612 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4613 Thread.currentThread().interrupt();
4615 Binder.restoreCallingIdentity(id);
4621 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4622 final IBinder response) {
4623 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4624 if (!isCallerWithSystemUid()) {
4628 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4629 // If there is a profile owner, redirect to that; otherwise query the device owner.
4630 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4631 if (aliasChooser == null && caller.isSystem()) {
4632 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4633 if (deviceOwnerAdmin != null) {
4634 aliasChooser = deviceOwnerAdmin.info.getComponent();
4637 if (aliasChooser == null) {
4638 sendPrivateKeyAliasResponse(null, response);
4642 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4643 intent.setComponent(aliasChooser);
4644 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4645 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4646 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4647 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4648 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4650 final long id = mInjector.binderClearCallingIdentity();
4652 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4654 public void onReceive(Context context, Intent intent) {
4655 final String chosenAlias = getResultData();
4656 sendPrivateKeyAliasResponse(chosenAlias, response);
4658 }, null, Activity.RESULT_OK, null, null);
4660 mInjector.binderRestoreCallingIdentity(id);
4664 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4665 final IKeyChainAliasCallback keyChainAliasResponse =
4666 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4667 new AsyncTask<Void, Void, Void>() {
4669 protected Void doInBackground(Void... unused) {
4671 keyChainAliasResponse.alias(alias);
4672 } catch (Exception e) {
4673 // Catch everything (not just RemoteException): caller could throw a
4674 // RuntimeException back across processes.
4675 Log.e(LOG_TAG, "error while responding to callback", e);
4683 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4684 throws SecurityException {
4685 int userHandle = UserHandle.getCallingUserId();
4686 synchronized (this) {
4687 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4688 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4689 if (installerPackage != null &&
4690 !isPackageInstalledForUser(installerPackage, userHandle)) {
4691 throw new IllegalArgumentException("Package " + installerPackage
4692 + " is not installed on the current user");
4695 DevicePolicyData policy = getUserData(userHandle);
4696 policy.mDelegatedCertInstallerPackage = installerPackage;
4697 saveSettingsLocked(userHandle);
4702 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4703 int userHandle = UserHandle.getCallingUserId();
4704 synchronized (this) {
4705 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4706 DevicePolicyData policy = getUserData(userHandle);
4707 return policy.mDelegatedCertInstallerPackage;
4712 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4713 * not installed and therefore not available.
4715 * @throws SecurityException if the caller is not a profile or device owner.
4716 * @throws UnsupportedOperationException if the package does not support being set as always-on.
4719 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4720 throws SecurityException {
4721 synchronized (this) {
4722 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4725 final int userId = mInjector.userHandleGetCallingUserId();
4726 final long token = mInjector.binderClearCallingIdentity();
4728 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4731 ConnectivityManager connectivityManager = (ConnectivityManager)
4732 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4733 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4734 throw new UnsupportedOperationException();
4737 mInjector.binderRestoreCallingIdentity(token);
4743 public String getAlwaysOnVpnPackage(ComponentName admin)
4744 throws SecurityException {
4745 synchronized (this) {
4746 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4749 final int userId = mInjector.userHandleGetCallingUserId();
4750 final long token = mInjector.binderClearCallingIdentity();
4752 ConnectivityManager connectivityManager = (ConnectivityManager)
4753 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4754 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4756 mInjector.binderRestoreCallingIdentity(token);
4760 private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
4761 if (wipeExtRequested) {
4762 StorageManager sm = (StorageManager) mContext.getSystemService(
4763 Context.STORAGE_SERVICE);
4764 sm.wipeAdoptableDisks();
4767 RecoverySystem.rebootWipeUserData(mContext, reason);
4768 } catch (IOException | SecurityException e) {
4769 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4774 public void wipeData(int flags) {
4778 final int userHandle = mInjector.userHandleGetCallingUserId();
4779 enforceFullCrossUsersPermission(userHandle);
4781 final String source;
4782 synchronized (this) {
4783 // This API can only be called by an active device admin,
4784 // so try to retrieve it to check that the caller is one.
4785 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4786 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4787 source = admin.info.getComponent().flattenToShortString();
4789 long ident = mInjector.binderClearCallingIdentity();
4791 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4792 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4793 throw new SecurityException(
4794 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4796 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4797 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4798 if (manager != null) {
4803 mInjector.binderRestoreCallingIdentity(ident);
4806 final boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4807 wipeDeviceNoLock(wipeExtRequested, userHandle,
4808 "DevicePolicyManager.wipeData() from " + source);
4811 private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
4812 final long ident = mInjector.binderClearCallingIdentity();
4814 if (userHandle == UserHandle.USER_SYSTEM) {
4815 wipeDataNoLock(wipeExtRequested, reason);
4817 mHandler.post(new Runnable() {
4821 IActivityManager am = mInjector.getIActivityManager();
4822 if (am.getCurrentUser().id == userHandle) {
4823 am.switchUser(UserHandle.USER_SYSTEM);
4826 boolean isManagedProfile = isManagedProfile(userHandle);
4827 if (!mUserManager.removeUser(userHandle)) {
4828 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4829 } else if (isManagedProfile) {
4830 sendWipeProfileNotification();
4832 } catch (RemoteException re) {
4839 mInjector.binderRestoreCallingIdentity(ident);
4843 private void sendWipeProfileNotification() {
4844 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4845 Notification notification = new Notification.Builder(mContext)
4846 .setSmallIcon(android.R.drawable.stat_sys_warning)
4847 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4848 .setContentText(contentText)
4849 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4850 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4852 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4855 private void clearWipeProfileNotification() {
4856 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4860 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4864 enforceFullCrossUsersPermission(userHandle);
4865 mContext.enforceCallingOrSelfPermission(
4866 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4868 synchronized (this) {
4869 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4870 if (admin == null) {
4871 result.sendResult(null);
4874 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4875 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4876 intent.setComponent(admin.info.getComponent());
4877 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4878 null, new BroadcastReceiver() {
4880 public void onReceive(Context context, Intent intent) {
4881 result.sendResult(getResultExtras(false));
4883 }, null, Activity.RESULT_OK, null, null);
4888 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4889 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4893 enforceFullCrossUsersPermission(userHandle);
4894 mContext.enforceCallingOrSelfPermission(
4895 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4897 // If the managed profile doesn't have a separate password, set the metrics to default
4898 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
4899 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4909 validateQualityConstant(quality);
4910 DevicePolicyData policy = getUserData(userHandle);
4911 synchronized (this) {
4912 policy.mActivePasswordQuality = quality;
4913 policy.mActivePasswordLength = length;
4914 policy.mActivePasswordLetters = letters;
4915 policy.mActivePasswordLowerCase = lowercase;
4916 policy.mActivePasswordUpperCase = uppercase;
4917 policy.mActivePasswordNumeric = numbers;
4918 policy.mActivePasswordSymbols = symbols;
4919 policy.mActivePasswordNonLetter = nonletter;
4924 public void reportPasswordChanged(int userId) {
4928 enforceFullCrossUsersPermission(userId);
4930 // Managed Profile password can only be changed when it has a separate challenge.
4931 if (!isSeparateProfileChallengeEnabled(userId)) {
4932 enforceNotManagedProfile(userId, "set the active password");
4935 mContext.enforceCallingOrSelfPermission(
4936 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4938 DevicePolicyData policy = getUserData(userId);
4940 long ident = mInjector.binderClearCallingIdentity();
4942 synchronized (this) {
4943 policy.mFailedPasswordAttempts = 0;
4944 saveSettingsLocked(userId);
4945 updatePasswordExpirationsLocked(userId);
4946 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
4948 // Send a broadcast to each profile using this password as its primary unlock.
4949 sendAdminCommandForLockscreenPoliciesLocked(
4950 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4951 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
4953 removeCaApprovalsIfNeeded(userId);
4955 mInjector.binderRestoreCallingIdentity(ident);
4960 * Called any time the device password is updated. Resets all password expiration clocks.
4962 private void updatePasswordExpirationsLocked(int userHandle) {
4963 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4964 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4965 userHandle, /* parent */ false);
4966 final int N = admins.size();
4967 for (int i = 0; i < N; i++) {
4968 ActiveAdmin admin = admins.get(i);
4969 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4970 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4971 long timeout = admin.passwordExpirationTimeout;
4972 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4973 admin.passwordExpirationDate = expiration;
4976 for (int affectedUserId : affectedUserIds) {
4977 saveSettingsLocked(affectedUserId);
4982 public void reportFailedPasswordAttempt(int userHandle) {
4983 enforceFullCrossUsersPermission(userHandle);
4984 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4985 enforceNotManagedProfile(userHandle,
4986 "report failed password attempt if separate profile challenge is not in place");
4988 mContext.enforceCallingOrSelfPermission(
4989 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4991 final long ident = mInjector.binderClearCallingIdentity();
4993 boolean wipeData = false;
4995 synchronized (this) {
4996 DevicePolicyData policy = getUserData(userHandle);
4997 policy.mFailedPasswordAttempts++;
4998 saveSettingsLocked(userHandle);
5000 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
5001 userHandle, /* parent */ false);
5002 int max = strictestAdmin != null
5003 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
5004 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
5005 // Wipe the user/profile associated with the policy that was violated. This
5006 // is not necessarily calling user: if the policy that fired was from a
5007 // managed profile rather than the main user profile, we wipe former only.
5009 identifier = strictestAdmin.getUserHandle().getIdentifier();
5012 sendAdminCommandForLockscreenPoliciesLocked(
5013 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
5014 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5018 // Call without holding lock.
5019 wipeDeviceNoLock(false, identifier,
5020 "reportFailedPasswordAttempt()");
5023 mInjector.binderRestoreCallingIdentity(ident);
5026 if (mInjector.securityLogIsLoggingEnabled()) {
5027 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5028 /*method strength*/ 1);
5033 public void reportSuccessfulPasswordAttempt(int userHandle) {
5034 enforceFullCrossUsersPermission(userHandle);
5035 mContext.enforceCallingOrSelfPermission(
5036 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5038 synchronized (this) {
5039 DevicePolicyData policy = getUserData(userHandle);
5040 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
5041 long ident = mInjector.binderClearCallingIdentity();
5043 policy.mFailedPasswordAttempts = 0;
5044 policy.mPasswordOwner = -1;
5045 saveSettingsLocked(userHandle);
5047 sendAdminCommandForLockscreenPoliciesLocked(
5048 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
5049 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5052 mInjector.binderRestoreCallingIdentity(ident);
5057 if (mInjector.securityLogIsLoggingEnabled()) {
5058 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5059 /*method strength*/ 1);
5064 public void reportFailedFingerprintAttempt(int userHandle) {
5065 enforceFullCrossUsersPermission(userHandle);
5066 mContext.enforceCallingOrSelfPermission(
5067 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5068 if (mInjector.securityLogIsLoggingEnabled()) {
5069 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5070 /*method strength*/ 0);
5075 public void reportSuccessfulFingerprintAttempt(int userHandle) {
5076 enforceFullCrossUsersPermission(userHandle);
5077 mContext.enforceCallingOrSelfPermission(
5078 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5079 if (mInjector.securityLogIsLoggingEnabled()) {
5080 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5081 /*method strength*/ 0);
5086 public void reportKeyguardDismissed(int userHandle) {
5087 enforceFullCrossUsersPermission(userHandle);
5088 mContext.enforceCallingOrSelfPermission(
5089 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5091 if (mInjector.securityLogIsLoggingEnabled()) {
5092 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
5097 public void reportKeyguardSecured(int userHandle) {
5098 enforceFullCrossUsersPermission(userHandle);
5099 mContext.enforceCallingOrSelfPermission(
5100 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5102 if (mInjector.securityLogIsLoggingEnabled()) {
5103 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
5108 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
5109 String exclusionList) {
5113 synchronized(this) {
5114 Preconditions.checkNotNull(who, "ComponentName is null");
5116 // Only check if system user has set global proxy. We don't allow other users to set it.
5117 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5118 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5119 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
5121 // Scan through active admins and find if anyone has already
5122 // set the global proxy.
5123 Set<ComponentName> compSet = policy.mAdminMap.keySet();
5124 for (ComponentName component : compSet) {
5125 ActiveAdmin ap = policy.mAdminMap.get(component);
5126 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
5127 // Another admin already sets the global proxy
5128 // Return it to the caller.
5133 // If the user is not system, don't set the global proxy. Fail silently.
5134 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
5135 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
5136 + UserHandle.getCallingUserId() + " is not permitted.");
5139 if (proxySpec == null) {
5140 admin.specifiesGlobalProxy = false;
5141 admin.globalProxySpec = null;
5142 admin.globalProxyExclusionList = null;
5145 admin.specifiesGlobalProxy = true;
5146 admin.globalProxySpec = proxySpec;
5147 admin.globalProxyExclusionList = exclusionList;
5150 // Reset the global proxy accordingly
5151 // Do this using system permissions, as apps cannot write to secure settings
5152 long origId = mInjector.binderClearCallingIdentity();
5154 resetGlobalProxyLocked(policy);
5156 mInjector.binderRestoreCallingIdentity(origId);
5163 public ComponentName getGlobalProxyAdmin(int userHandle) {
5167 enforceFullCrossUsersPermission(userHandle);
5168 synchronized(this) {
5169 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5170 // Scan through active admins and find if anyone has already
5171 // set the global proxy.
5172 final int N = policy.mAdminList.size();
5173 for (int i = 0; i < N; i++) {
5174 ActiveAdmin ap = policy.mAdminList.get(i);
5175 if (ap.specifiesGlobalProxy) {
5176 // Device admin sets the global proxy
5177 // Return it to the caller.
5178 return ap.info.getComponent();
5182 // No device admin sets the global proxy.
5187 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5188 synchronized (this) {
5189 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5191 long token = mInjector.binderClearCallingIdentity();
5193 ConnectivityManager connectivityManager = (ConnectivityManager)
5194 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5195 connectivityManager.setGlobalProxy(proxyInfo);
5197 mInjector.binderRestoreCallingIdentity(token);
5201 private void resetGlobalProxyLocked(DevicePolicyData policy) {
5202 final int N = policy.mAdminList.size();
5203 for (int i = 0; i < N; i++) {
5204 ActiveAdmin ap = policy.mAdminList.get(i);
5205 if (ap.specifiesGlobalProxy) {
5206 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5210 // No device admins defining global proxies - reset global proxy settings to none
5211 saveGlobalProxyLocked(null, null);
5214 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5215 if (exclusionList == null) {
5218 if (proxySpec == null) {
5221 // Remove white spaces
5222 proxySpec = proxySpec.trim();
5223 String data[] = proxySpec.split(":");
5224 int proxyPort = 8080;
5225 if (data.length > 1) {
5227 proxyPort = Integer.parseInt(data[1]);
5228 } catch (NumberFormatException e) {}
5230 exclusionList = exclusionList.trim();
5232 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5233 if (!proxyProperties.isValid()) {
5234 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5237 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5238 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5239 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5244 * Set the storage encryption request for a single admin. Returns the new total request
5245 * status (for all admins).
5248 public int setStorageEncryption(ComponentName who, boolean encrypt) {
5250 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5252 Preconditions.checkNotNull(who, "ComponentName is null");
5253 final int userHandle = UserHandle.getCallingUserId();
5254 synchronized (this) {
5255 // Check for permissions
5256 // Only system user can set storage encryption
5257 if (userHandle != UserHandle.USER_SYSTEM) {
5258 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5259 + UserHandle.getCallingUserId() + " is not permitted.");
5263 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5264 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5266 // Quick exit: If the filesystem does not support encryption, we can exit early.
5267 if (!isEncryptionSupported()) {
5268 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5271 // (1) Record the value for the admin so it's sticky
5272 if (ap.encryptionRequested != encrypt) {
5273 ap.encryptionRequested = encrypt;
5274 saveSettingsLocked(userHandle);
5277 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5278 // (2) Compute "max" for all admins
5279 boolean newRequested = false;
5280 final int N = policy.mAdminList.size();
5281 for (int i = 0; i < N; i++) {
5282 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5285 // Notify OS of new request
5286 setEncryptionRequested(newRequested);
5288 // Return the new global request status
5290 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5291 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5296 * Get the current storage encryption request status for a given admin, or aggregate of all
5300 public boolean getStorageEncryption(ComponentName who, int userHandle) {
5304 enforceFullCrossUsersPermission(userHandle);
5305 synchronized (this) {
5306 // Check for permissions if a particular caller is specified
5308 // When checking for a single caller, status is based on caller's request
5309 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5310 return ap != null ? ap.encryptionRequested : false;
5313 // If no particular caller is specified, return the aggregate set of requests.
5314 // This is short circuited by returning true on the first hit.
5315 DevicePolicyData policy = getUserData(userHandle);
5316 final int N = policy.mAdminList.size();
5317 for (int i = 0; i < N; i++) {
5318 if (policy.mAdminList.get(i).encryptionRequested) {
5327 * Get the current encryption status of the device.
5330 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5332 // Ok to return current status.
5334 enforceFullCrossUsersPermission(userHandle);
5336 // It's not critical here, but let's make sure the package name is correct, in case
5337 // we start using it for different purposes.
5338 ensureCallerPackage(callerPackage);
5340 final ApplicationInfo ai;
5342 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5343 } catch (RemoteException e) {
5344 throw new SecurityException(e);
5347 boolean legacyApp = false;
5348 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5352 final int rawStatus = getEncryptionStatus();
5353 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5354 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5360 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
5362 private boolean isEncryptionSupported() {
5363 // Note, this can be implemented as
5364 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5365 // But is provided as a separate internal method if there's a faster way to do a
5366 // simple check for supported-or-not.
5367 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5371 * Hook to low-levels: Reporting the current status of encryption.
5372 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5373 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5374 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5375 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5376 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5378 private int getEncryptionStatus() {
5379 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5380 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5381 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5382 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5383 } else if (mInjector.storageManagerIsEncrypted()) {
5384 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5385 } else if (mInjector.storageManagerIsEncryptable()) {
5386 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5388 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5393 * Hook to low-levels: If needed, record the new admin setting for encryption.
5395 private void setEncryptionRequested(boolean encrypt) {
5399 * Set whether the screen capture is disabled for the user managed by the specified admin.
5402 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5406 Preconditions.checkNotNull(who, "ComponentName is null");
5407 final int userHandle = UserHandle.getCallingUserId();
5408 synchronized (this) {
5409 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5410 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5411 if (ap.disableScreenCapture != disabled) {
5412 ap.disableScreenCapture = disabled;
5413 saveSettingsLocked(userHandle);
5414 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5420 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5421 * active admin (if given admin is null).
5424 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5428 synchronized (this) {
5430 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5431 return (admin != null) ? admin.disableScreenCapture : false;
5434 DevicePolicyData policy = getUserData(userHandle);
5435 final int N = policy.mAdminList.size();
5436 for (int i = 0; i < N; i++) {
5437 ActiveAdmin admin = policy.mAdminList.get(i);
5438 if (admin.disableScreenCapture) {
5446 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5447 final boolean disabled) {
5448 mHandler.post(new Runnable() {
5452 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5453 } catch (RemoteException e) {
5454 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5461 * Set whether auto time is required by the specified admin (must be device owner).
5464 public void setAutoTimeRequired(ComponentName who, boolean required) {
5468 Preconditions.checkNotNull(who, "ComponentName is null");
5469 final int userHandle = UserHandle.getCallingUserId();
5470 synchronized (this) {
5471 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5472 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5473 if (admin.requireAutoTime != required) {
5474 admin.requireAutoTime = required;
5475 saveSettingsLocked(userHandle);
5479 // Turn AUTO_TIME on in settings if it is required
5481 long ident = mInjector.binderClearCallingIdentity();
5483 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5485 mInjector.binderRestoreCallingIdentity(ident);
5491 * Returns whether or not auto time is required by the device owner.
5494 public boolean getAutoTimeRequired() {
5498 synchronized (this) {
5499 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5500 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5505 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5509 Preconditions.checkNotNull(who, "ComponentName is null");
5510 // Allow setting this policy to true only if there is a split system user.
5511 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5512 throw new UnsupportedOperationException(
5513 "Cannot force ephemeral users on systems without split system user.");
5515 boolean removeAllUsers = false;
5516 synchronized (this) {
5517 final ActiveAdmin deviceOwner =
5518 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5519 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5520 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5521 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5522 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5523 removeAllUsers = forceEphemeralUsers;
5526 if (removeAllUsers) {
5527 long identitity = mInjector.binderClearCallingIdentity();
5529 mUserManagerInternal.removeAllUsers();
5531 mInjector.binderRestoreCallingIdentity(identitity);
5537 public boolean getForceEphemeralUsers(ComponentName who) {
5541 Preconditions.checkNotNull(who, "ComponentName is null");
5542 synchronized (this) {
5543 final ActiveAdmin deviceOwner =
5544 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5545 return deviceOwner.forceEphemeralUsers;
5549 private boolean isDeviceOwnerManagedSingleUserDevice() {
5550 synchronized (this) {
5551 if (!mOwners.hasDeviceOwner()) {
5555 final long callingIdentity = mInjector.binderClearCallingIdentity();
5557 if (mInjector.userManagerIsSplitSystemUser()) {
5558 // In split system user mode, only allow the case where the device owner is managing
5559 // the only non-system user of the device
5560 return (mUserManager.getUserCount() == 2
5561 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5563 return mUserManager.getUserCount() == 1;
5566 mInjector.binderRestoreCallingIdentity(callingIdentity);
5570 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5571 synchronized (this) {
5572 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5574 if (!isDeviceOwnerManagedSingleUserDevice()) {
5575 throw new SecurityException(
5576 "There should only be one user, managed by Device Owner");
5581 public boolean requestBugreport(ComponentName who) {
5585 Preconditions.checkNotNull(who, "ComponentName is null");
5586 ensureDeviceOwnerManagingSingleUser(who);
5588 if (mRemoteBugreportServiceIsActive.get()
5589 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5590 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5594 final long callingIdentity = mInjector.binderClearCallingIdentity();
5596 ActivityManagerNative.getDefault().requestBugReport(
5597 ActivityManager.BUGREPORT_OPTION_REMOTE);
5599 mRemoteBugreportServiceIsActive.set(true);
5600 mRemoteBugreportSharingAccepted.set(false);
5601 registerRemoteBugreportReceivers();
5602 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5603 RemoteBugreportUtils.buildNotification(mContext,
5604 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5605 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5606 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5608 } catch (RemoteException re) {
5609 // should never happen
5610 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5613 mInjector.binderRestoreCallingIdentity(callingIdentity);
5617 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5618 Intent intent = new Intent(action);
5619 intent.setComponent(mOwners.getDeviceOwnerComponent());
5620 if (extras != null) {
5621 intent.putExtras(extras);
5623 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5626 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5627 return mOwners.getDeviceOwnerRemoteBugreportUri();
5630 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5631 String bugreportHash) {
5632 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5635 private void registerRemoteBugreportReceivers() {
5637 IntentFilter filterFinished = new IntentFilter(
5638 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5639 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5640 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5641 } catch (IntentFilter.MalformedMimeTypeException e) {
5642 // should never happen, as setting a constant
5643 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5645 IntentFilter filterConsent = new IntentFilter();
5646 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5647 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5648 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5651 private void onBugreportFinished(Intent intent) {
5652 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5653 mRemoteBugreportServiceIsActive.set(false);
5654 Uri bugreportUri = intent.getData();
5655 String bugreportUriString = null;
5656 if (bugreportUri != null) {
5657 bugreportUriString = bugreportUri.toString();
5659 String bugreportHash = intent.getStringExtra(
5660 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5661 if (mRemoteBugreportSharingAccepted.get()) {
5662 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5663 mInjector.getNotificationManager().cancel(LOG_TAG,
5664 RemoteBugreportUtils.NOTIFICATION_ID);
5666 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5667 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5668 RemoteBugreportUtils.buildNotification(mContext,
5669 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5672 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5675 private void onBugreportFailed() {
5676 mRemoteBugreportServiceIsActive.set(false);
5677 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5678 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5679 mRemoteBugreportSharingAccepted.set(false);
5680 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5681 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5682 Bundle extras = new Bundle();
5683 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5684 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5685 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5686 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5687 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5690 private void onBugreportSharingAccepted() {
5691 mRemoteBugreportSharingAccepted.set(true);
5692 String bugreportUriString = null;
5693 String bugreportHash = null;
5694 synchronized (this) {
5695 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5696 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5698 if (bugreportUriString != null) {
5699 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5700 } else if (mRemoteBugreportServiceIsActive.get()) {
5701 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5702 RemoteBugreportUtils.buildNotification(mContext,
5703 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5708 private void onBugreportSharingDeclined() {
5709 if (mRemoteBugreportServiceIsActive.get()) {
5710 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5711 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5712 mRemoteBugreportServiceIsActive.set(false);
5713 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5714 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5716 mRemoteBugreportSharingAccepted.set(false);
5717 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5718 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5721 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5722 String bugreportHash) {
5723 ParcelFileDescriptor pfd = null;
5725 if (bugreportUriString == null) {
5726 throw new FileNotFoundException();
5728 Uri bugreportUri = Uri.parse(bugreportUriString);
5729 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5731 synchronized (this) {
5732 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5733 intent.setComponent(mOwners.getDeviceOwnerComponent());
5734 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5735 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5736 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
5738 LocalServices.getService(ActivityManagerInternal.class)
5739 .grantUriPermissionFromIntent(Process.SHELL_UID,
5740 mOwners.getDeviceOwnerComponent().getPackageName(),
5741 intent, mOwners.getDeviceOwnerUserId());
5742 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5744 } catch (FileNotFoundException e) {
5745 Bundle extras = new Bundle();
5746 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5747 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5748 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5754 } catch (IOException ex) {
5757 mRemoteBugreportSharingAccepted.set(false);
5758 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5763 * Disables all device cameras according to the specified admin.
5766 public void setCameraDisabled(ComponentName who, boolean disabled) {
5770 Preconditions.checkNotNull(who, "ComponentName is null");
5771 final int userHandle = mInjector.userHandleGetCallingUserId();
5772 synchronized (this) {
5773 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5774 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5775 if (ap.disableCamera != disabled) {
5776 ap.disableCamera = disabled;
5777 saveSettingsLocked(userHandle);
5780 // Tell the user manager that the restrictions have changed.
5781 pushUserRestrictions(userHandle);
5785 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5789 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5790 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5793 private boolean getCameraDisabled(ComponentName who, int userHandle,
5794 boolean mergeDeviceOwnerRestriction) {
5798 synchronized (this) {
5800 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5801 return (admin != null) ? admin.disableCamera : false;
5803 // First, see if DO has set it. If so, it's device-wide.
5804 if (mergeDeviceOwnerRestriction) {
5805 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5806 if (deviceOwner != null && deviceOwner.disableCamera) {
5811 // Then check each device admin on the user.
5812 DevicePolicyData policy = getUserData(userHandle);
5813 // Determine whether or not the device camera is disabled for any active admins.
5814 final int N = policy.mAdminList.size();
5815 for (int i = 0; i < N; i++) {
5816 ActiveAdmin admin = policy.mAdminList.get(i);
5817 if (admin.disableCamera) {
5826 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5830 Preconditions.checkNotNull(who, "ComponentName is null");
5831 final int userHandle = mInjector.userHandleGetCallingUserId();
5832 if (isManagedProfile(userHandle)) {
5834 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5836 which = which & PROFILE_KEYGUARD_FEATURES;
5839 synchronized (this) {
5840 ActiveAdmin ap = getActiveAdminForCallerLocked(
5841 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5842 if (ap.disabledKeyguardFeatures != which) {
5843 ap.disabledKeyguardFeatures = which;
5844 saveSettingsLocked(userHandle);
5850 * Gets the disabled state for features in keyguard for the given admin,
5851 * or the aggregate of all active admins if who is null.
5854 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5858 enforceFullCrossUsersPermission(userHandle);
5859 final long ident = mInjector.binderClearCallingIdentity();
5861 synchronized (this) {
5863 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5864 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5867 final List<ActiveAdmin> admins;
5868 if (!parent && isManagedProfile(userHandle)) {
5869 // If we are being asked about a managed profile, just return keyguard features
5870 // disabled by admins in the profile.
5871 admins = getUserDataUnchecked(userHandle).mAdminList;
5873 // Otherwise return those set by admins in the user and its profiles.
5874 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5877 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5878 final int N = admins.size();
5879 for (int i = 0; i < N; i++) {
5880 ActiveAdmin admin = admins.get(i);
5881 int userId = admin.getUserHandle().getIdentifier();
5882 boolean isRequestedUser = !parent && (userId == userHandle);
5883 if (isRequestedUser || !isManagedProfile(userId)) {
5884 // If we are being asked explicitly about this user
5885 // return all disabled features even if its a managed profile.
5886 which |= admin.disabledKeyguardFeatures;
5888 // Otherwise a managed profile is only allowed to disable
5889 // some features on the parent user.
5890 which |= (admin.disabledKeyguardFeatures
5891 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5897 mInjector.binderRestoreCallingIdentity(ident);
5902 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5906 Preconditions.checkNotNull(who, "ComponentName is null");
5907 Preconditions.checkNotNull(packageList, "packageList is null");
5908 final int userHandle = UserHandle.getCallingUserId();
5909 synchronized (this) {
5910 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5911 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5912 admin.keepUninstalledPackages = packageList;
5913 saveSettingsLocked(userHandle);
5914 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5919 public List<String> getKeepUninstalledPackages(ComponentName who) {
5920 Preconditions.checkNotNull(who, "ComponentName is null");
5924 // TODO In split system user mode, allow apps on user 0 to query the list
5925 synchronized (this) {
5926 // Check if this is the device owner who is calling
5927 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5928 return getKeepUninstalledPackagesLocked();
5932 private List<String> getKeepUninstalledPackagesLocked() {
5933 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5934 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5938 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5943 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5944 throw new IllegalArgumentException("Invalid component " + admin
5945 + " for device owner");
5947 final boolean hasIncompatibleAccountsOrNonAdb =
5948 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin);
5949 synchronized (this) {
5950 enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb);
5951 if (getActiveAdminUncheckedLocked(admin, userId) == null
5952 || getUserData(userId).mRemovingAdmins.contains(admin)) {
5953 throw new IllegalArgumentException("Not active admin: " + admin);
5956 // Shutting down backup manager service permanently.
5957 long ident = mInjector.binderClearCallingIdentity();
5959 if (mInjector.getIBackupManager() != null) {
5960 mInjector.getIBackupManager()
5961 .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5963 } catch (RemoteException e) {
5964 throw new IllegalStateException("Failed deactivating backup service.", e);
5966 mInjector.binderRestoreCallingIdentity(ident);
5969 mOwners.setDeviceOwner(admin, ownerName, userId);
5970 mOwners.writeDeviceOwner();
5971 updateDeviceOwnerLocked();
5972 setDeviceOwnerSystemPropertyLocked();
5973 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5975 ident = mInjector.binderClearCallingIdentity();
5977 // TODO Send to system too?
5978 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5980 mInjector.binderRestoreCallingIdentity(ident);
5982 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
5987 public boolean isDeviceOwner(ComponentName who, int userId) {
5988 synchronized (this) {
5989 return mOwners.hasDeviceOwner()
5990 && mOwners.getDeviceOwnerUserId() == userId
5991 && mOwners.getDeviceOwnerComponent().equals(who);
5995 public boolean isProfileOwner(ComponentName who, int userId) {
5996 final ComponentName profileOwner = getProfileOwner(userId);
5997 return who != null && who.equals(profileOwner);
6001 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
6005 if (!callingUserOnly) {
6006 enforceManageUsers();
6008 synchronized (this) {
6009 if (!mOwners.hasDeviceOwner()) {
6012 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
6013 mOwners.getDeviceOwnerUserId()) {
6016 return mOwners.getDeviceOwnerComponent();
6021 public int getDeviceOwnerUserId() {
6023 return UserHandle.USER_NULL;
6025 enforceManageUsers();
6026 synchronized (this) {
6027 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
6032 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
6036 public String getDeviceOwnerName() {
6040 enforceManageUsers();
6041 synchronized (this) {
6042 if (!mOwners.hasDeviceOwner()) {
6045 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
6046 // Should setDeviceOwner/ProfileOwner still take a name?
6047 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
6048 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
6052 // Returns the active device owner or null if there is no device owner.
6054 ActiveAdmin getDeviceOwnerAdminLocked() {
6055 ComponentName component = mOwners.getDeviceOwnerComponent();
6056 if (component == null) {
6060 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
6061 final int n = policy.mAdminList.size();
6062 for (int i = 0; i < n; i++) {
6063 ActiveAdmin admin = policy.mAdminList.get(i);
6064 if (component.equals(admin.info.getComponent())) {
6068 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
6073 public void clearDeviceOwner(String packageName) {
6074 Preconditions.checkNotNull(packageName, "packageName is null");
6075 final int callingUid = mInjector.binderGetCallingUid();
6077 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
6078 UserHandle.getUserId(callingUid));
6079 if (uid != callingUid) {
6080 throw new SecurityException("Invalid packageName");
6082 } catch (NameNotFoundException e) {
6083 throw new SecurityException(e);
6085 synchronized (this) {
6086 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6087 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6088 if (!mOwners.hasDeviceOwner()
6089 || !deviceOwnerComponent.getPackageName().equals(packageName)
6090 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
6091 throw new SecurityException(
6092 "clearDeviceOwner can only be called by the device owner");
6094 enforceUserUnlocked(deviceOwnerUserId);
6096 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
6097 long ident = mInjector.binderClearCallingIdentity();
6099 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
6100 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
6102 mInjector.binderRestoreCallingIdentity(ident);
6104 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
6108 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
6109 if (admin != null) {
6110 admin.disableCamera = false;
6111 admin.userRestrictions = null;
6112 admin.forceEphemeralUsers = false;
6113 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
6115 clearUserPoliciesLocked(userId);
6117 mOwners.clearDeviceOwner();
6118 mOwners.writeDeviceOwner();
6119 updateDeviceOwnerLocked();
6120 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
6122 if (mInjector.getIBackupManager() != null) {
6123 // Reactivate backup service.
6124 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6126 } catch (RemoteException e) {
6127 throw new IllegalStateException("Failed reactivating backup service.", e);
6132 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6137 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6138 throw new IllegalArgumentException("Component " + who
6139 + " not installed for userId:" + userHandle);
6141 final boolean hasIncompatibleAccountsOrNonAdb =
6142 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who);
6143 synchronized (this) {
6144 enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb);
6146 if (getActiveAdminUncheckedLocked(who, userHandle) == null
6147 || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6148 throw new IllegalArgumentException("Not active admin: " + who);
6151 mOwners.setProfileOwner(who, ownerName, userHandle);
6152 mOwners.writeProfileOwner(userHandle);
6153 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6159 public void clearProfileOwner(ComponentName who) {
6163 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
6164 final int userId = callingUser.getIdentifier();
6165 enforceNotManagedProfile(userId, "clear profile owner");
6166 enforceUserUnlocked(userId);
6167 // Check if this is the profile owner who is calling
6168 final ActiveAdmin admin =
6169 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6170 synchronized (this) {
6171 final long ident = mInjector.binderClearCallingIdentity();
6173 clearProfileOwnerLocked(admin, userId);
6174 removeActiveAdminLocked(who, userId);
6176 mInjector.binderRestoreCallingIdentity(ident);
6178 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6182 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6183 if (admin != null) {
6184 admin.disableCamera = false;
6185 admin.userRestrictions = null;
6187 clearUserPoliciesLocked(userId);
6188 mOwners.removeProfileOwner(userId);
6189 mOwners.writeProfileOwner(userId);
6193 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6194 Preconditions.checkNotNull(who, "ComponentName is null");
6199 synchronized (this) {
6200 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6201 long token = mInjector.binderClearCallingIdentity();
6203 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6205 mInjector.binderRestoreCallingIdentity(token);
6211 public CharSequence getDeviceOwnerLockScreenInfo() {
6212 return mLockPatternUtils.getDeviceOwnerInfo();
6215 private void clearUserPoliciesLocked(int userId) {
6216 // Reset some of the user-specific policies
6217 DevicePolicyData policy = getUserData(userId);
6218 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6219 policy.mDelegatedCertInstallerPackage = null;
6220 policy.mApplicationRestrictionsManagingPackage = null;
6221 policy.mStatusBarDisabled = false;
6222 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6223 saveSettingsLocked(userId);
6226 mIPackageManager.updatePermissionFlagsForAllApps(
6227 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6228 0 /* flagValues */, userId);
6229 pushUserRestrictions(userId);
6230 } catch (RemoteException re) {
6231 // Shouldn't happen.
6236 public boolean hasUserSetupCompleted() {
6237 return hasUserSetupCompleted(UserHandle.getCallingUserId());
6240 // This checks only if the Setup Wizard has run. Since Wear devices pair before
6241 // completing Setup Wizard, and pairing involves transferring user data, calling
6242 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
6243 private boolean hasUserSetupCompleted(int userHandle) {
6247 return getUserData(userHandle).mUserSetupComplete;
6250 private boolean hasPaired(int userHandle) {
6254 return getUserData(userHandle).mPaired;
6258 public int getUserProvisioningState() {
6260 return DevicePolicyManager.STATE_USER_UNMANAGED;
6262 int userHandle = mInjector.userHandleGetCallingUserId();
6263 return getUserProvisioningState(userHandle);
6266 private int getUserProvisioningState(int userHandle) {
6267 return getUserData(userHandle).mUserProvisioningState;
6271 public void setUserProvisioningState(int newState, int userHandle) {
6276 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6277 && getManagedUserId(userHandle) == -1) {
6278 // No managed device, user or profile, so setting provisioning state makes no sense.
6279 throw new IllegalStateException("Not allowed to change provisioning state unless a "
6280 + "device or profile owner is set.");
6283 synchronized (this) {
6284 boolean transitionCheckNeeded = true;
6286 // Calling identity/permission checks.
6287 final int callingUid = mInjector.binderGetCallingUid();
6288 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6289 // ADB shell can only move directly from un-managed to finalized as part of directly
6290 // setting profile-owner or device-owner.
6291 if (getUserProvisioningState(userHandle) !=
6292 DevicePolicyManager.STATE_USER_UNMANAGED
6293 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6294 throw new IllegalStateException("Not allowed to change provisioning state "
6295 + "unless current provisioning state is unmanaged, and new state is "
6298 transitionCheckNeeded = false;
6300 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6301 enforceCanManageProfileAndDeviceOwners();
6304 final DevicePolicyData policyData = getUserData(userHandle);
6305 if (transitionCheckNeeded) {
6306 // Optional state transition check for non-ADB case.
6307 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6309 policyData.mUserProvisioningState = newState;
6310 saveSettingsLocked(userHandle);
6314 private void checkUserProvisioningStateTransition(int currentState, int newState) {
6315 // Valid transitions for normal use-cases.
6316 switch (currentState) {
6317 case DevicePolicyManager.STATE_USER_UNMANAGED:
6318 // Can move to any state from unmanaged (except itself as an edge case)..
6319 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6323 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6324 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6325 // Can only move to finalized from these states.
6326 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6330 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6331 // Current user has a managed-profile, but current user is not managed, so
6332 // rather than moving to finalized state, go back to unmanaged once
6333 // profile provisioning is complete.
6334 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6338 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6339 // Cannot transition out of finalized.
6343 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6344 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6345 + "from state [" + currentState + "]");
6349 public void setProfileEnabled(ComponentName who) {
6353 Preconditions.checkNotNull(who, "ComponentName is null");
6354 synchronized (this) {
6355 // Check if this is the profile owner who is calling
6356 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6357 final int userId = UserHandle.getCallingUserId();
6358 enforceManagedProfile(userId, "enable the profile");
6360 long id = mInjector.binderClearCallingIdentity();
6362 mUserManager.setUserEnabled(userId);
6363 UserInfo parent = mUserManager.getProfileParent(userId);
6364 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6365 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6366 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6367 Intent.FLAG_RECEIVER_FOREGROUND);
6368 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6370 mInjector.binderRestoreCallingIdentity(id);
6376 public void setProfileName(ComponentName who, String profileName) {
6377 Preconditions.checkNotNull(who, "ComponentName is null");
6378 int userId = UserHandle.getCallingUserId();
6379 // Check if this is the profile owner (includes device owner).
6380 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6382 long id = mInjector.binderClearCallingIdentity();
6384 mUserManager.setUserName(userId, profileName);
6386 mInjector.binderRestoreCallingIdentity(id);
6391 public ComponentName getProfileOwner(int userHandle) {
6396 synchronized (this) {
6397 return mOwners.getProfileOwnerComponent(userHandle);
6401 // Returns the active profile owner for this user or null if the current user has no
6404 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6405 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6406 if (profileOwner == null) {
6409 DevicePolicyData policy = getUserData(userHandle);
6410 final int n = policy.mAdminList.size();
6411 for (int i = 0; i < n; i++) {
6412 ActiveAdmin admin = policy.mAdminList.get(i);
6413 if (profileOwner.equals(admin.info.getComponent())) {
6421 public String getProfileOwnerName(int userHandle) {
6425 enforceManageUsers();
6426 ComponentName profileOwner = getProfileOwner(userHandle);
6427 if (profileOwner == null) {
6430 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6434 * Canonical name for a given package.
6436 private String getApplicationLabel(String packageName, int userHandle) {
6437 long token = mInjector.binderClearCallingIdentity();
6439 final Context userContext;
6441 UserHandle handle = new UserHandle(userHandle);
6442 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6443 } catch (PackageManager.NameNotFoundException nnfe) {
6444 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6447 ApplicationInfo appInfo = userContext.getApplicationInfo();
6448 CharSequence result = null;
6449 if (appInfo != null) {
6450 PackageManager pm = userContext.getPackageManager();
6451 result = pm.getApplicationLabel(appInfo);
6453 return result != null ? result.toString() : null;
6455 mInjector.binderRestoreCallingIdentity(token);
6460 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6462 * The profile owner can only be set before the user setup phase has completed,
6465 * - adb unless hasIncompatibleAccountsOrNonAdb is true.
6467 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle,
6468 boolean hasIncompatibleAccountsOrNonAdb) {
6469 UserInfo info = getUserInfo(userHandle);
6471 // User doesn't exist.
6472 throw new IllegalArgumentException(
6473 "Attempted to set profile owner for invalid userId: " + userHandle);
6475 if (info.isGuest()) {
6476 throw new IllegalStateException("Cannot set a profile owner on a guest");
6478 if (mOwners.hasProfileOwner(userHandle)) {
6479 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6480 + "is already set.");
6482 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6483 throw new IllegalStateException("Trying to set the profile owner, but the user "
6484 + "already has a device owner.");
6486 int callingUid = mInjector.binderGetCallingUid();
6487 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6488 if ((mIsWatch || hasUserSetupCompleted(userHandle))
6489 && hasIncompatibleAccountsOrNonAdb) {
6490 throw new IllegalStateException("Not allowed to set the profile owner because "
6491 + "there are already some accounts on the profile");
6495 enforceCanManageProfileAndDeviceOwners();
6496 if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
6497 throw new IllegalStateException("Cannot set the profile owner on a user which is "
6498 + "already set-up");
6503 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6506 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId,
6507 boolean hasIncompatibleAccountsOrNonAdb) {
6508 int callingUid = mInjector.binderGetCallingUid();
6509 boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6511 enforceCanManageProfileAndDeviceOwners();
6514 final int code = checkSetDeviceOwnerPreConditionLocked(owner, userId, isAdb,
6515 hasIncompatibleAccountsOrNonAdb);
6519 case CODE_HAS_DEVICE_OWNER:
6520 throw new IllegalStateException(
6521 "Trying to set the device owner, but device owner is already set.");
6522 case CODE_USER_HAS_PROFILE_OWNER:
6523 throw new IllegalStateException("Trying to set the device owner, but the user "
6524 + "already has a profile owner.");
6525 case CODE_USER_NOT_RUNNING:
6526 throw new IllegalStateException("User not running: " + userId);
6527 case CODE_NOT_SYSTEM_USER:
6528 throw new IllegalStateException("User is not system user");
6529 case CODE_USER_SETUP_COMPLETED:
6530 throw new IllegalStateException(
6531 "Cannot set the device owner if the device is already set-up");
6532 case CODE_NONSYSTEM_USER_EXISTS:
6533 throw new IllegalStateException("Not allowed to set the device owner because there "
6534 + "are already several users on the device");
6535 case CODE_ACCOUNTS_NOT_EMPTY:
6536 throw new IllegalStateException("Not allowed to set the device owner because there "
6537 + "are already some accounts on the device");
6538 case CODE_HAS_PAIRED:
6539 throw new IllegalStateException("Not allowed to set the device owner because this "
6540 + "device has already paired");
6542 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6546 private void enforceUserUnlocked(int userId) {
6547 // Since we're doing this operation on behalf of an app, we only
6548 // want to use the actual "unlocked" state.
6549 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6550 "User must be running and unlocked");
6553 private void enforceUserUnlocked(int userId, boolean parent) {
6555 enforceUserUnlocked(getProfileParentId(userId));
6557 enforceUserUnlocked(userId);
6561 private void enforceManageUsers() {
6562 final int callingUid = mInjector.binderGetCallingUid();
6563 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6564 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6568 private void enforceFullCrossUsersPermission(int userHandle) {
6569 enforceSystemUserOrPermission(userHandle,
6570 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6573 private void enforceCrossUsersPermission(int userHandle) {
6574 enforceSystemUserOrPermission(userHandle,
6575 android.Manifest.permission.INTERACT_ACROSS_USERS);
6578 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6579 if (userHandle < 0) {
6580 throw new IllegalArgumentException("Invalid userId " + userHandle);
6582 final int callingUid = mInjector.binderGetCallingUid();
6583 if (userHandle == UserHandle.getUserId(callingUid)) {
6586 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6587 mContext.enforceCallingOrSelfPermission(permission,
6588 "Must be system or have " + permission + " permission");
6592 private void enforceManagedProfile(int userHandle, String message) {
6593 if(!isManagedProfile(userHandle)) {
6594 throw new SecurityException("You can not " + message + " outside a managed profile.");
6598 private void enforceNotManagedProfile(int userHandle, String message) {
6599 if(isManagedProfile(userHandle)) {
6600 throw new SecurityException("You can not " + message + " for a managed profile.");
6604 private void enforceDeviceOwnerOrManageUsers() {
6605 synchronized (this) {
6606 if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6607 mInjector.binderGetCallingUid()) != null) {
6611 enforceManageUsers();
6614 private void ensureCallerPackage(@Nullable String packageName) {
6615 if (packageName == null) {
6616 Preconditions.checkState(isCallerWithSystemUid(),
6617 "Only caller can omit package name");
6619 final int callingUid = mInjector.binderGetCallingUid();
6620 final int userId = mInjector.userHandleGetCallingUserId();
6622 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6623 packageName, 0, userId);
6624 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6625 } catch (RemoteException e) {
6631 private boolean isCallerWithSystemUid() {
6632 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6635 private int getProfileParentId(int userHandle) {
6636 final long ident = mInjector.binderClearCallingIdentity();
6638 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6639 return parentUser != null ? parentUser.id : userHandle;
6641 mInjector.binderRestoreCallingIdentity(ident);
6645 private int getCredentialOwner(int userHandle, boolean parent) {
6646 final long ident = mInjector.binderClearCallingIdentity();
6649 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6650 if (parentProfile != null) {
6651 userHandle = parentProfile.id;
6654 return mUserManager.getCredentialOwnerProfile(userHandle);
6656 mInjector.binderRestoreCallingIdentity(ident);
6660 private boolean isManagedProfile(int userHandle) {
6661 return getUserInfo(userHandle).isManagedProfile();
6664 private void enableIfNecessary(String packageName, int userId) {
6666 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6667 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6669 if (ai.enabledSetting
6670 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6671 mIPackageManager.setApplicationEnabledSetting(packageName,
6672 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6673 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6675 } catch (RemoteException e) {
6680 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6681 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6682 != PackageManager.PERMISSION_GRANTED) {
6684 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6685 + mInjector.binderGetCallingPid()
6686 + ", uid=" + mInjector.binderGetCallingUid());
6690 synchronized (this) {
6691 pw.println("Current Device Policy Manager state:");
6692 mOwners.dump(" ", pw);
6693 int userCount = mUserData.size();
6694 for (int u = 0; u < userCount; u++) {
6695 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6697 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6698 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6699 final int N = policy.mAdminList.size();
6700 for (int i=0; i<N; i++) {
6701 ActiveAdmin ap = policy.mAdminList.get(i);
6703 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6708 if (!policy.mRemovingAdmins.isEmpty()) {
6709 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6710 + policy.mRemovingAdmins);
6714 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6717 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6721 private String getEncryptionStatusName(int encryptionStatus) {
6722 switch (encryptionStatus) {
6723 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6725 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6726 return "block default key";
6727 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6729 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6731 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6732 return "unsupported";
6733 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6734 return "activating";
6741 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6742 ComponentName activity) {
6743 Preconditions.checkNotNull(who, "ComponentName is null");
6744 final int userHandle = UserHandle.getCallingUserId();
6745 synchronized (this) {
6746 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6748 long id = mInjector.binderClearCallingIdentity();
6750 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6751 } catch (RemoteException re) {
6754 mInjector.binderRestoreCallingIdentity(id);
6760 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6761 Preconditions.checkNotNull(who, "ComponentName is null");
6762 final int userHandle = UserHandle.getCallingUserId();
6763 synchronized (this) {
6764 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6766 long id = mInjector.binderClearCallingIdentity();
6768 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6769 } catch (RemoteException re) {
6772 mInjector.binderRestoreCallingIdentity(id);
6778 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6779 String packageName) {
6780 Preconditions.checkNotNull(admin, "ComponentName is null");
6782 final int userHandle = mInjector.userHandleGetCallingUserId();
6783 synchronized (this) {
6784 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6785 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6788 DevicePolicyData policy = getUserData(userHandle);
6789 policy.mApplicationRestrictionsManagingPackage = packageName;
6790 saveSettingsLocked(userHandle);
6796 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6797 Preconditions.checkNotNull(admin, "ComponentName is null");
6799 final int userHandle = mInjector.userHandleGetCallingUserId();
6800 synchronized (this) {
6801 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6802 DevicePolicyData policy = getUserData(userHandle);
6803 return policy.mApplicationRestrictionsManagingPackage;
6808 public boolean isCallerApplicationRestrictionsManagingPackage() {
6809 final int callingUid = mInjector.binderGetCallingUid();
6810 final int userHandle = UserHandle.getUserId(callingUid);
6811 synchronized (this) {
6812 final DevicePolicyData policy = getUserData(userHandle);
6813 if (policy.mApplicationRestrictionsManagingPackage == null) {
6818 int uid = mContext.getPackageManager().getPackageUidAsUser(
6819 policy.mApplicationRestrictionsManagingPackage, userHandle);
6820 return uid == callingUid;
6821 } catch (NameNotFoundException e) {
6827 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6829 synchronized (this) {
6830 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6832 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6833 throw new SecurityException(
6834 "No admin component given, and caller cannot manage application restrictions "
6835 + "for other apps.");
6840 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6841 enforceCanManageApplicationRestrictions(who);
6843 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6844 final long id = mInjector.binderClearCallingIdentity();
6846 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6848 mInjector.binderRestoreCallingIdentity(id);
6853 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6854 PersistableBundle args, boolean parent) {
6858 Preconditions.checkNotNull(admin, "admin is null");
6859 Preconditions.checkNotNull(agent, "agent is null");
6860 final int userHandle = UserHandle.getCallingUserId();
6861 synchronized (this) {
6862 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6863 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6864 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6865 saveSettingsLocked(userHandle);
6870 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6871 ComponentName agent, int userHandle, boolean parent) {
6875 Preconditions.checkNotNull(agent, "agent null");
6876 enforceFullCrossUsersPermission(userHandle);
6878 synchronized (this) {
6879 final String componentName = agent.flattenToString();
6880 if (admin != null) {
6881 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6882 if (ap == null) return null;
6883 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6884 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6885 List<PersistableBundle> result = new ArrayList<>();
6886 result.add(trustAgentInfo.options);
6890 // Return strictest policy for this user and profiles that are visible from this user.
6891 List<PersistableBundle> result = null;
6892 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6893 // of the options. If any admin doesn't have options, discard options for the rest
6895 List<ActiveAdmin> admins =
6896 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6897 boolean allAdminsHaveOptions = true;
6898 final int N = admins.size();
6899 for (int i = 0; i < N; i++) {
6900 final ActiveAdmin active = admins.get(i);
6902 final boolean disablesTrust = (active.disabledKeyguardFeatures
6903 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6904 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6905 if (info != null && info.options != null && !info.options.isEmpty()) {
6906 if (disablesTrust) {
6907 if (result == null) {
6908 result = new ArrayList<>();
6910 result.add(info.options);
6912 Log.w(LOG_TAG, "Ignoring admin " + active.info
6913 + " because it has trust options but doesn't declare "
6914 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6916 } else if (disablesTrust) {
6917 allAdminsHaveOptions = false;
6921 return allAdminsHaveOptions ? result : null;
6926 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6927 Preconditions.checkNotNull(who, "ComponentName is null");
6928 synchronized (this) {
6929 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6931 int userHandle = UserHandle.getCallingUserId();
6932 DevicePolicyData userData = getUserData(userHandle);
6933 userData.mRestrictionsProvider = permissionProvider;
6934 saveSettingsLocked(userHandle);
6939 public ComponentName getRestrictionsProvider(int userHandle) {
6940 synchronized (this) {
6941 if (!isCallerWithSystemUid()) {
6942 throw new SecurityException("Only the system can query the permission provider");
6944 DevicePolicyData userData = getUserData(userHandle);
6945 return userData != null ? userData.mRestrictionsProvider : null;
6950 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6951 Preconditions.checkNotNull(who, "ComponentName is null");
6952 int callingUserId = UserHandle.getCallingUserId();
6953 synchronized (this) {
6954 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6956 long id = mInjector.binderClearCallingIdentity();
6958 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6959 if (parent == null) {
6960 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6964 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6965 mIPackageManager.addCrossProfileIntentFilter(
6966 filter, who.getPackageName(), callingUserId, parent.id, 0);
6968 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6969 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6970 parent.id, callingUserId, 0);
6972 } catch (RemoteException re) {
6975 mInjector.binderRestoreCallingIdentity(id);
6981 public void clearCrossProfileIntentFilters(ComponentName who) {
6982 Preconditions.checkNotNull(who, "ComponentName is null");
6983 int callingUserId = UserHandle.getCallingUserId();
6984 synchronized (this) {
6985 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6986 long id = mInjector.binderClearCallingIdentity();
6988 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6989 if (parent == null) {
6990 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6994 // Removing those that go from the managed profile to the parent.
6995 mIPackageManager.clearCrossProfileIntentFilters(
6996 callingUserId, who.getPackageName());
6997 // And those that go from the parent to the managed profile.
6998 // If we want to support multiple managed profiles, we will have to only remove
6999 // those that have callingUserId as their target.
7000 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
7001 } catch (RemoteException re) {
7004 mInjector.binderRestoreCallingIdentity(id);
7010 * @return true if all packages in enabledPackages are either in the list
7011 * permittedList or are a system app.
7013 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
7014 List<String> permittedList, int userIdToCheck) {
7015 long id = mInjector.binderClearCallingIdentity();
7017 // If we have an enabled packages list for a managed profile the packages
7018 // we should check are installed for the parent user.
7019 UserInfo user = getUserInfo(userIdToCheck);
7020 if (user.isManagedProfile()) {
7021 userIdToCheck = user.profileGroupId;
7024 for (String enabledPackage : enabledPackages) {
7025 boolean systemService = false;
7027 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
7028 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
7029 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7030 } catch (RemoteException e) {
7031 Log.i(LOG_TAG, "Can't talk to package managed", e);
7033 if (!systemService && !permittedList.contains(enabledPackage)) {
7038 mInjector.binderRestoreCallingIdentity(id);
7043 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
7044 // Not using AccessibilityManager.getInstance because that guesses
7045 // at the user you require based on callingUid and caches for a given
7047 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
7048 IAccessibilityManager service = iBinder == null
7049 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
7050 return new AccessibilityManager(mContext, service, userId);
7054 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
7058 Preconditions.checkNotNull(who, "ComponentName is null");
7060 if (packageList != null) {
7061 int userId = UserHandle.getCallingUserId();
7062 List<AccessibilityServiceInfo> enabledServices = null;
7063 long id = mInjector.binderClearCallingIdentity();
7065 UserInfo user = getUserInfo(userId);
7066 if (user.isManagedProfile()) {
7067 userId = user.profileGroupId;
7069 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
7070 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
7071 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
7073 mInjector.binderRestoreCallingIdentity(id);
7076 if (enabledServices != null) {
7077 List<String> enabledPackages = new ArrayList<String>();
7078 for (AccessibilityServiceInfo service : enabledServices) {
7079 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
7081 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7083 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
7084 + "because it contains already enabled accesibility services.");
7090 synchronized (this) {
7091 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7092 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7093 admin.permittedAccessiblityServices = packageList;
7094 saveSettingsLocked(UserHandle.getCallingUserId());
7100 public List getPermittedAccessibilityServices(ComponentName who) {
7104 Preconditions.checkNotNull(who, "ComponentName is null");
7106 synchronized (this) {
7107 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7108 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7109 return admin.permittedAccessiblityServices;
7114 public List getPermittedAccessibilityServicesForUser(int userId) {
7118 synchronized (this) {
7119 List<String> result = null;
7120 // If we have multiple profiles we return the intersection of the
7121 // permitted lists. This can happen in cases where we have a device
7122 // and profile owner.
7123 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7124 for (int profileId : profileIds) {
7125 // Just loop though all admins, only device or profiles
7126 // owners can have permitted lists set.
7127 DevicePolicyData policy = getUserDataUnchecked(profileId);
7128 final int N = policy.mAdminList.size();
7129 for (int j = 0; j < N; j++) {
7130 ActiveAdmin admin = policy.mAdminList.get(j);
7131 List<String> fromAdmin = admin.permittedAccessiblityServices;
7132 if (fromAdmin != null) {
7133 if (result == null) {
7134 result = new ArrayList<>(fromAdmin);
7136 result.retainAll(fromAdmin);
7142 // If we have a permitted list add all system accessibility services.
7143 if (result != null) {
7144 long id = mInjector.binderClearCallingIdentity();
7146 UserInfo user = getUserInfo(userId);
7147 if (user.isManagedProfile()) {
7148 userId = user.profileGroupId;
7150 AccessibilityManager accessibilityManager =
7151 getAccessibilityManagerForUser(userId);
7152 List<AccessibilityServiceInfo> installedServices =
7153 accessibilityManager.getInstalledAccessibilityServiceList();
7155 if (installedServices != null) {
7156 for (AccessibilityServiceInfo service : installedServices) {
7157 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7158 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7159 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7160 result.add(serviceInfo.packageName);
7165 mInjector.binderRestoreCallingIdentity(id);
7174 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7179 Preconditions.checkNotNull(who, "ComponentName is null");
7180 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7181 if (!isCallerWithSystemUid()){
7182 throw new SecurityException(
7183 "Only the system can query if an accessibility service is disabled by admin");
7185 synchronized (this) {
7186 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7187 if (admin == null) {
7190 if (admin.permittedAccessiblityServices == null) {
7193 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7194 admin.permittedAccessiblityServices, userHandle);
7198 private boolean checkCallerIsCurrentUserOrProfile() {
7199 int callingUserId = UserHandle.getCallingUserId();
7200 long token = mInjector.binderClearCallingIdentity();
7202 UserInfo currentUser;
7203 UserInfo callingUser = getUserInfo(callingUserId);
7205 currentUser = mInjector.getIActivityManager().getCurrentUser();
7206 } catch (RemoteException e) {
7207 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7211 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7212 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7213 + "of a user that isn't the foreground user.");
7216 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7217 Slog.e(LOG_TAG, "Cannot set permitted input methods "
7218 + "of a user that isn't the foreground user.");
7222 mInjector.binderRestoreCallingIdentity(token);
7228 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7232 Preconditions.checkNotNull(who, "ComponentName is null");
7234 // TODO When InputMethodManager supports per user calls remove
7235 // this restriction.
7236 if (!checkCallerIsCurrentUserOrProfile()) {
7240 if (packageList != null) {
7241 // InputMethodManager fetches input methods for current user.
7242 // So this can only be set when calling user is the current user
7243 // or parent is current user in case of managed profiles.
7244 InputMethodManager inputMethodManager =
7245 mContext.getSystemService(InputMethodManager.class);
7246 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7248 if (enabledImes != null) {
7249 List<String> enabledPackages = new ArrayList<String>();
7250 for (InputMethodInfo ime : enabledImes) {
7251 enabledPackages.add(ime.getPackageName());
7253 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7254 mInjector.binderGetCallingUserHandle().getIdentifier())) {
7255 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7256 + "because it contains already enabled input method.");
7262 synchronized (this) {
7263 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7264 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7265 admin.permittedInputMethods = packageList;
7266 saveSettingsLocked(UserHandle.getCallingUserId());
7272 public List getPermittedInputMethods(ComponentName who) {
7276 Preconditions.checkNotNull(who, "ComponentName is null");
7278 synchronized (this) {
7279 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7280 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7281 return admin.permittedInputMethods;
7286 public List getPermittedInputMethodsForCurrentUser() {
7287 UserInfo currentUser;
7289 currentUser = mInjector.getIActivityManager().getCurrentUser();
7290 } catch (RemoteException e) {
7291 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7292 // Activity managed is dead, just allow all IMEs
7296 int userId = currentUser.id;
7297 synchronized (this) {
7298 List<String> result = null;
7299 // If we have multiple profiles we return the intersection of the
7300 // permitted lists. This can happen in cases where we have a device
7301 // and profile owner.
7302 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7303 for (int profileId : profileIds) {
7304 // Just loop though all admins, only device or profiles
7305 // owners can have permitted lists set.
7306 DevicePolicyData policy = getUserDataUnchecked(profileId);
7307 final int N = policy.mAdminList.size();
7308 for (int j = 0; j < N; j++) {
7309 ActiveAdmin admin = policy.mAdminList.get(j);
7310 List<String> fromAdmin = admin.permittedInputMethods;
7311 if (fromAdmin != null) {
7312 if (result == null) {
7313 result = new ArrayList<String>(fromAdmin);
7315 result.retainAll(fromAdmin);
7321 // If we have a permitted list add all system input methods.
7322 if (result != null) {
7323 InputMethodManager inputMethodManager =
7324 mContext.getSystemService(InputMethodManager.class);
7325 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7326 long id = mInjector.binderClearCallingIdentity();
7329 for (InputMethodInfo ime : imes) {
7330 ServiceInfo serviceInfo = ime.getServiceInfo();
7331 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7332 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7333 result.add(serviceInfo.packageName);
7338 mInjector.binderRestoreCallingIdentity(id);
7346 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7351 Preconditions.checkNotNull(who, "ComponentName is null");
7352 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7353 if (!isCallerWithSystemUid()) {
7354 throw new SecurityException(
7355 "Only the system can query if an input method is disabled by admin");
7357 synchronized (this) {
7358 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7359 if (admin == null) {
7362 if (admin.permittedInputMethods == null) {
7365 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7366 admin.permittedInputMethods, userHandle);
7370 private void sendAdminEnabledBroadcastLocked(int userHandle) {
7371 DevicePolicyData policyData = getUserData(userHandle);
7372 if (policyData.mAdminBroadcastPending) {
7373 // Send the initialization data to profile owner and delete the data
7374 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7375 if (admin != null) {
7376 PersistableBundle initBundle = policyData.mInitBundle;
7377 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7378 initBundle == null ? null : new Bundle(initBundle), null);
7380 policyData.mInitBundle = null;
7381 policyData.mAdminBroadcastPending = false;
7382 saveSettingsLocked(userHandle);
7387 public UserHandle createAndManageUser(ComponentName admin, String name,
7388 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7389 Preconditions.checkNotNull(admin, "admin is null");
7390 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7391 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7392 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7393 + admin + " are not in the same package");
7395 // Only allow the system user to use this method
7396 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7397 throw new SecurityException("createAndManageUser was called from non-system user");
7399 if (!mInjector.userManagerIsSplitSystemUser()
7400 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7401 throw new IllegalArgumentException(
7402 "Ephemeral users are only supported on systems with a split system user.");
7405 UserHandle user = null;
7406 synchronized (this) {
7407 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7409 final long id = mInjector.binderClearCallingIdentity();
7411 int userInfoFlags = 0;
7412 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7413 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7415 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7417 if (userInfo != null) {
7418 user = userInfo.getUserHandle();
7421 mInjector.binderRestoreCallingIdentity(id);
7428 final long id = mInjector.binderClearCallingIdentity();
7430 final String adminPkg = admin.getPackageName();
7432 final int userHandle = user.getIdentifier();
7434 // Install the profile owner if not present.
7435 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7436 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7438 } catch (RemoteException e) {
7439 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7440 + "removing created user", e);
7441 mUserManager.removeUser(user.getIdentifier());
7445 setActiveAdmin(profileOwner, true, userHandle);
7446 // User is not started yet, the broadcast by setActiveAdmin will not be received.
7447 // So we store adminExtras for broadcasting when the user starts for first time.
7448 synchronized(this) {
7449 DevicePolicyData policyData = getUserData(userHandle);
7450 policyData.mInitBundle = adminExtras;
7451 policyData.mAdminBroadcastPending = true;
7452 saveSettingsLocked(userHandle);
7454 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7455 setProfileOwner(profileOwner, ownerName, userHandle);
7457 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7458 Settings.Secure.putIntForUser(mContext.getContentResolver(),
7459 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7464 mInjector.binderRestoreCallingIdentity(id);
7469 public boolean removeUser(ComponentName who, UserHandle userHandle) {
7470 Preconditions.checkNotNull(who, "ComponentName is null");
7471 synchronized (this) {
7472 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7474 long id = mInjector.binderClearCallingIdentity();
7476 return mUserManager.removeUser(userHandle.getIdentifier());
7478 mInjector.binderRestoreCallingIdentity(id);
7484 public boolean switchUser(ComponentName who, UserHandle userHandle) {
7485 Preconditions.checkNotNull(who, "ComponentName is null");
7486 synchronized (this) {
7487 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7489 long id = mInjector.binderClearCallingIdentity();
7491 int userId = UserHandle.USER_SYSTEM;
7492 if (userHandle != null) {
7493 userId = userHandle.getIdentifier();
7495 return mInjector.getIActivityManager().switchUser(userId);
7496 } catch (RemoteException e) {
7497 Log.e(LOG_TAG, "Couldn't switch user", e);
7500 mInjector.binderRestoreCallingIdentity(id);
7506 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7507 enforceCanManageApplicationRestrictions(who);
7509 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7510 final long id = mInjector.binderClearCallingIdentity();
7512 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7513 // if no restrictions were saved, mUserManager.getApplicationRestrictions
7514 // returns null, but DPM method should return an empty Bundle as per JavaDoc
7515 return bundle != null ? bundle : Bundle.EMPTY;
7517 mInjector.binderRestoreCallingIdentity(id);
7522 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7523 boolean suspended) {
7524 Preconditions.checkNotNull(who, "ComponentName is null");
7525 int callingUserId = UserHandle.getCallingUserId();
7526 synchronized (this) {
7527 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7529 long id = mInjector.binderClearCallingIdentity();
7531 return mIPackageManager.setPackagesSuspendedAsUser(
7532 packageNames, suspended, callingUserId);
7533 } catch (RemoteException re) {
7534 // Shouldn't happen.
7535 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7537 mInjector.binderRestoreCallingIdentity(id);
7539 return packageNames;
7544 public boolean isPackageSuspended(ComponentName who, String packageName) {
7545 Preconditions.checkNotNull(who, "ComponentName is null");
7546 int callingUserId = UserHandle.getCallingUserId();
7547 synchronized (this) {
7548 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7550 long id = mInjector.binderClearCallingIdentity();
7552 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7553 } catch (RemoteException re) {
7554 // Shouldn't happen.
7555 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7557 mInjector.binderRestoreCallingIdentity(id);
7564 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7565 Preconditions.checkNotNull(who, "ComponentName is null");
7566 if (!UserRestrictionsUtils.isValidRestriction(key)) {
7570 final int userHandle = mInjector.userHandleGetCallingUserId();
7571 synchronized (this) {
7572 ActiveAdmin activeAdmin =
7573 getActiveAdminForCallerLocked(who,
7574 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7575 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7576 if (isDeviceOwner) {
7577 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7578 throw new SecurityException("Device owner cannot set user restriction " + key);
7580 } else { // profile owner
7581 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7582 throw new SecurityException("Profile owner cannot set user restriction " + key);
7586 // Save the restriction to ActiveAdmin.
7587 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7588 saveSettingsLocked(userHandle);
7590 pushUserRestrictions(userHandle);
7592 sendChangedNotification(userHandle);
7596 private void pushUserRestrictions(int userId) {
7597 synchronized (this) {
7598 final Bundle global;
7599 final Bundle local = new Bundle();
7600 if (mOwners.isDeviceOwnerUserId(userId)) {
7601 global = new Bundle();
7603 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7604 if (deviceOwner == null) {
7605 return; // Shouldn't happen.
7608 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7610 // DO can disable camera globally.
7611 if (deviceOwner.disableCamera) {
7612 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7617 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7618 if (profileOwner != null) {
7619 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7622 // Also merge in *local* camera restriction.
7623 if (getCameraDisabled(/* who= */ null,
7624 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7625 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7627 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7632 public Bundle getUserRestrictions(ComponentName who) {
7636 Preconditions.checkNotNull(who, "ComponentName is null");
7637 synchronized (this) {
7638 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7639 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7640 return activeAdmin.userRestrictions;
7645 public boolean setApplicationHidden(ComponentName who, String packageName,
7647 Preconditions.checkNotNull(who, "ComponentName is null");
7648 int callingUserId = UserHandle.getCallingUserId();
7649 synchronized (this) {
7650 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7652 long id = mInjector.binderClearCallingIdentity();
7654 return mIPackageManager.setApplicationHiddenSettingAsUser(
7655 packageName, hidden, callingUserId);
7656 } catch (RemoteException re) {
7658 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7660 mInjector.binderRestoreCallingIdentity(id);
7667 public boolean isApplicationHidden(ComponentName who, String packageName) {
7668 Preconditions.checkNotNull(who, "ComponentName is null");
7669 int callingUserId = UserHandle.getCallingUserId();
7670 synchronized (this) {
7671 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7673 long id = mInjector.binderClearCallingIdentity();
7675 return mIPackageManager.getApplicationHiddenSettingAsUser(
7676 packageName, callingUserId);
7677 } catch (RemoteException re) {
7679 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7681 mInjector.binderRestoreCallingIdentity(id);
7688 public void enableSystemApp(ComponentName who, String packageName) {
7689 Preconditions.checkNotNull(who, "ComponentName is null");
7690 synchronized (this) {
7691 // This API can only be called by an active device admin,
7692 // so try to retrieve it to check that the caller is one.
7693 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7695 int userId = UserHandle.getCallingUserId();
7696 long id = mInjector.binderClearCallingIdentity();
7700 Slog.v(LOG_TAG, "installing " + packageName + " for "
7704 int parentUserId = getProfileParentId(userId);
7705 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7706 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7710 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7712 } catch (RemoteException re) {
7714 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7716 mInjector.binderRestoreCallingIdentity(id);
7722 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7723 Preconditions.checkNotNull(who, "ComponentName is null");
7724 synchronized (this) {
7725 // This API can only be called by an active device admin,
7726 // so try to retrieve it to check that the caller is one.
7727 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7729 int userId = UserHandle.getCallingUserId();
7730 long id = mInjector.binderClearCallingIdentity();
7733 int parentUserId = getProfileParentId(userId);
7734 List<ResolveInfo> activitiesToEnable = mIPackageManager
7735 .queryIntentActivities(intent,
7736 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7737 PackageManager.MATCH_DIRECT_BOOT_AWARE
7738 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7743 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7745 int numberOfAppsInstalled = 0;
7746 if (activitiesToEnable != null) {
7747 for (ResolveInfo info : activitiesToEnable) {
7748 if (info.activityInfo != null) {
7749 String packageName = info.activityInfo.packageName;
7750 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7751 numberOfAppsInstalled++;
7752 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7754 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7760 return numberOfAppsInstalled;
7761 } catch (RemoteException e) {
7763 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7766 mInjector.binderRestoreCallingIdentity(id);
7771 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7772 throws RemoteException {
7773 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7775 if (appInfo == null) {
7776 throw new IllegalArgumentException("The application " + packageName +
7777 " is not present on this device");
7779 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7783 public void setAccountManagementDisabled(ComponentName who, String accountType,
7788 Preconditions.checkNotNull(who, "ComponentName is null");
7789 synchronized (this) {
7790 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7791 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7793 ap.accountTypesWithManagementDisabled.add(accountType);
7795 ap.accountTypesWithManagementDisabled.remove(accountType);
7797 saveSettingsLocked(UserHandle.getCallingUserId());
7802 public String[] getAccountTypesWithManagementDisabled() {
7803 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7807 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7808 enforceFullCrossUsersPermission(userId);
7812 synchronized (this) {
7813 DevicePolicyData policy = getUserData(userId);
7814 final int N = policy.mAdminList.size();
7815 ArraySet<String> resultSet = new ArraySet<>();
7816 for (int i = 0; i < N; i++) {
7817 ActiveAdmin admin = policy.mAdminList.get(i);
7818 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7820 return resultSet.toArray(new String[resultSet.size()]);
7825 public void setUninstallBlocked(ComponentName who, String packageName,
7826 boolean uninstallBlocked) {
7827 Preconditions.checkNotNull(who, "ComponentName is null");
7828 final int userId = UserHandle.getCallingUserId();
7829 synchronized (this) {
7830 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7832 long id = mInjector.binderClearCallingIdentity();
7834 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7835 } catch (RemoteException re) {
7836 // Shouldn't happen.
7837 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7839 mInjector.binderRestoreCallingIdentity(id);
7845 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7846 // This function should return true if and only if the package is blocked by
7847 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7848 // when the package is a system app, or when it is an active device admin.
7849 final int userId = UserHandle.getCallingUserId();
7851 synchronized (this) {
7853 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7856 long id = mInjector.binderClearCallingIdentity();
7858 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7859 } catch (RemoteException re) {
7860 // Shouldn't happen.
7861 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7863 mInjector.binderRestoreCallingIdentity(id);
7870 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7874 Preconditions.checkNotNull(who, "ComponentName is null");
7875 synchronized (this) {
7876 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7877 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7878 if (admin.disableCallerId != disabled) {
7879 admin.disableCallerId = disabled;
7880 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7886 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7890 Preconditions.checkNotNull(who, "ComponentName is null");
7891 synchronized (this) {
7892 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7893 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7894 return admin.disableCallerId;
7899 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7900 enforceCrossUsersPermission(userId);
7901 synchronized (this) {
7902 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7903 return (admin != null) ? admin.disableCallerId : false;
7908 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7912 Preconditions.checkNotNull(who, "ComponentName is null");
7913 synchronized (this) {
7914 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7915 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7916 if (admin.disableContactsSearch != disabled) {
7917 admin.disableContactsSearch = disabled;
7918 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7924 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7928 Preconditions.checkNotNull(who, "ComponentName is null");
7929 synchronized (this) {
7930 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7931 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7932 return admin.disableContactsSearch;
7937 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7938 enforceCrossUsersPermission(userId);
7939 synchronized (this) {
7940 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7941 return (admin != null) ? admin.disableContactsSearch : false;
7946 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7947 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7948 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7949 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7950 final int callingUserId = UserHandle.getCallingUserId();
7952 final long ident = mInjector.binderClearCallingIdentity();
7954 synchronized (this) {
7955 final int managedUserId = getManagedUserId(callingUserId);
7956 if (managedUserId < 0) {
7959 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7962 "Cross-profile contacts access disabled for user " + managedUserId);
7966 ContactsInternal.startQuickContactWithErrorToastForUser(
7967 mContext, intent, new UserHandle(managedUserId));
7970 mInjector.binderRestoreCallingIdentity(ident);
7975 * @return true if cross-profile QuickContact is disabled
7977 private boolean isCrossProfileQuickContactDisabled(int userId) {
7978 return getCrossProfileCallerIdDisabledForUser(userId)
7979 && getCrossProfileContactsSearchDisabledForUser(userId);
7983 * @return the user ID of the managed user that is linked to the current user, if any.
7986 public int getManagedUserId(int callingUserId) {
7988 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7991 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7992 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7993 continue; // Caller user self, or not a managed profile. Skip.
7996 Log.v(LOG_TAG, "Managed user=" + ui.id);
8001 Log.v(LOG_TAG, "Managed user not found.");
8007 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
8011 Preconditions.checkNotNull(who, "ComponentName is null");
8012 synchronized (this) {
8013 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8014 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8015 if (admin.disableBluetoothContactSharing != disabled) {
8016 admin.disableBluetoothContactSharing = disabled;
8017 saveSettingsLocked(UserHandle.getCallingUserId());
8023 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
8027 Preconditions.checkNotNull(who, "ComponentName is null");
8028 synchronized (this) {
8029 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8030 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8031 return admin.disableBluetoothContactSharing;
8036 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
8037 // TODO: Should there be a check to make sure this relationship is
8038 // within a profile group?
8039 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
8040 synchronized (this) {
8041 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8042 return (admin != null) ? admin.disableBluetoothContactSharing : false;
8047 * Sets which packages may enter lock task mode.
8049 * <p>This function can only be called by the device owner or alternatively by the profile owner
8050 * in case the user is affiliated.
8052 * @param packages The list of packages allowed to enter lock task mode.
8055 public void setLockTaskPackages(ComponentName who, String[] packages)
8056 throws SecurityException {
8057 Preconditions.checkNotNull(who, "ComponentName is null");
8058 synchronized (this) {
8059 ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
8060 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
8061 ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
8062 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
8063 if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
8064 int userHandle = mInjector.userHandleGetCallingUserId();
8065 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
8067 throw new SecurityException("Admin " + who +
8068 " is neither the device owner or affiliated user's profile owner.");
8073 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
8074 DevicePolicyData policy = getUserData(userHandle);
8075 policy.mLockTaskPackages = packages;
8077 // Store the settings persistently.
8078 saveSettingsLocked(userHandle);
8079 updateLockTaskPackagesLocked(packages, userHandle);
8083 * This function returns the list of components allowed to start the task lock mode.
8086 public String[] getLockTaskPackages(ComponentName who) {
8087 Preconditions.checkNotNull(who, "ComponentName is null");
8088 synchronized (this) {
8089 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8090 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
8091 final List<String> packages = getLockTaskPackagesLocked(userHandle);
8092 return packages.toArray(new String[packages.size()]);
8096 private List<String> getLockTaskPackagesLocked(int userHandle) {
8097 final DevicePolicyData policy = getUserData(userHandle);
8098 return policy.mLockTaskPackages;
8102 * This function lets the caller know whether the given package is allowed to start the
8104 * @param pkg The package to check
8107 public boolean isLockTaskPermitted(String pkg) {
8108 // Get current user's devicepolicy
8109 int uid = mInjector.binderGetCallingUid();
8110 int userHandle = UserHandle.getUserId(uid);
8111 DevicePolicyData policy = getUserData(userHandle);
8112 synchronized (this) {
8113 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
8114 String lockTaskPackage = policy.mLockTaskPackages.get(i);
8116 // If the given package equals one of the packages stored our list,
8117 // we allow this package to start lock task mode.
8118 if (lockTaskPackage.equals(pkg)) {
8127 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
8128 if (!isCallerWithSystemUid()) {
8129 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
8131 synchronized (this) {
8132 final DevicePolicyData policy = getUserData(userHandle);
8133 Bundle adminExtras = new Bundle();
8134 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
8135 for (ActiveAdmin admin : policy.mAdminList) {
8136 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
8137 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
8138 if (ownsDevice || ownsProfile) {
8140 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
8143 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
8151 public void setGlobalSetting(ComponentName who, String setting, String value) {
8152 Preconditions.checkNotNull(who, "ComponentName is null");
8154 synchronized (this) {
8155 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8157 // Some settings are no supported any more. However we do not want to throw a
8158 // SecurityException to avoid breaking apps.
8159 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
8160 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
8164 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
8165 throw new SecurityException(String.format(
8166 "Permission denial: device owners cannot update %1$s", setting));
8169 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
8170 // ignore if it contradicts an existing policy
8171 long timeMs = getMaximumTimeToLock(
8172 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
8173 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
8178 long id = mInjector.binderClearCallingIdentity();
8180 mInjector.settingsGlobalPutString(setting, value);
8182 mInjector.binderRestoreCallingIdentity(id);
8188 public void setSecureSetting(ComponentName who, String setting, String value) {
8189 Preconditions.checkNotNull(who, "ComponentName is null");
8190 int callingUserId = mInjector.userHandleGetCallingUserId();
8192 synchronized (this) {
8193 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8195 if (isDeviceOwner(who, callingUserId)) {
8196 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
8197 throw new SecurityException(String.format(
8198 "Permission denial: Device owners cannot update %1$s", setting));
8200 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
8201 throw new SecurityException(String.format(
8202 "Permission denial: Profile owners cannot update %1$s", setting));
8205 long id = mInjector.binderClearCallingIdentity();
8207 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
8209 mInjector.binderRestoreCallingIdentity(id);
8215 public void setMasterVolumeMuted(ComponentName who, boolean on) {
8216 Preconditions.checkNotNull(who, "ComponentName is null");
8217 synchronized (this) {
8218 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8219 setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
8224 public boolean isMasterVolumeMuted(ComponentName who) {
8225 Preconditions.checkNotNull(who, "ComponentName is null");
8226 synchronized (this) {
8227 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8229 AudioManager audioManager =
8230 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
8231 return audioManager.isMasterMute();
8236 public void setUserIcon(ComponentName who, Bitmap icon) {
8237 synchronized (this) {
8238 Preconditions.checkNotNull(who, "ComponentName is null");
8239 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8241 int userId = UserHandle.getCallingUserId();
8242 long id = mInjector.binderClearCallingIdentity();
8244 mUserManagerInternal.setUserIcon(userId, icon);
8246 mInjector.binderRestoreCallingIdentity(id);
8252 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8253 Preconditions.checkNotNull(who, "ComponentName is null");
8254 synchronized (this) {
8255 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8257 final int userId = UserHandle.getCallingUserId();
8259 long ident = mInjector.binderClearCallingIdentity();
8261 // disallow disabling the keyguard if a password is currently set
8262 if (disabled && mLockPatternUtils.isSecure(userId)) {
8265 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8267 mInjector.binderRestoreCallingIdentity(ident);
8273 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8274 int userId = UserHandle.getCallingUserId();
8275 synchronized (this) {
8276 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8277 DevicePolicyData policy = getUserData(userId);
8278 if (policy.mStatusBarDisabled != disabled) {
8279 if (!setStatusBarDisabledInternal(disabled, userId)) {
8282 policy.mStatusBarDisabled = disabled;
8283 saveSettingsLocked(userId);
8289 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8290 long ident = mInjector.binderClearCallingIdentity();
8292 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8293 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8294 if (statusBarService != null) {
8295 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8296 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8297 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8298 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8301 } catch (RemoteException e) {
8302 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8304 mInjector.binderRestoreCallingIdentity(ident);
8310 * We need to update the internal state of whether a user has completed setup or a
8311 * device has paired once. After that, we ignore any changes that reset the
8312 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
8313 * as we don't trust any apps that might try to reset them.
8315 * Unfortunately, we don't know which user's setup state was changed, so we write all of
8318 void updateUserSetupCompleteAndPaired() {
8319 List<UserInfo> users = mUserManager.getUsers(true);
8320 final int N = users.size();
8321 for (int i = 0; i < N; i++) {
8322 int userHandle = users.get(i).id;
8323 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8325 DevicePolicyData policy = getUserData(userHandle);
8326 if (!policy.mUserSetupComplete) {
8327 policy.mUserSetupComplete = true;
8328 synchronized (this) {
8329 saveSettingsLocked(userHandle);
8333 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
8335 DevicePolicyData policy = getUserData(userHandle);
8336 if (!policy.mPaired) {
8337 policy.mPaired = true;
8338 synchronized (this) {
8339 saveSettingsLocked(userHandle);
8346 private class SetupContentObserver extends ContentObserver {
8348 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8349 Settings.Secure.USER_SETUP_COMPLETE);
8350 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8351 Settings.Global.DEVICE_PROVISIONED);
8352 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
8354 public SetupContentObserver(Handler handler) {
8359 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8360 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8362 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
8367 public void onChange(boolean selfChange, Uri uri) {
8368 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
8369 updateUserSetupCompleteAndPaired();
8370 } else if (mDeviceProvisioned.equals(uri)) {
8371 synchronized (DevicePolicyManagerService.this) {
8372 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8373 // is delayed until device is marked as provisioned.
8374 setDeviceOwnerSystemPropertyLocked();
8381 final class LocalService extends DevicePolicyManagerInternal {
8382 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8385 public List<String> getCrossProfileWidgetProviders(int profileId) {
8386 synchronized (DevicePolicyManagerService.this) {
8387 if (mOwners == null) {
8388 return Collections.emptyList();
8390 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8391 if (ownerComponent == null) {
8392 return Collections.emptyList();
8395 DevicePolicyData policy = getUserDataUnchecked(profileId);
8396 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8398 if (admin == null || admin.crossProfileWidgetProviders == null
8399 || admin.crossProfileWidgetProviders.isEmpty()) {
8400 return Collections.emptyList();
8403 return admin.crossProfileWidgetProviders;
8408 public void addOnCrossProfileWidgetProvidersChangeListener(
8409 OnCrossProfileWidgetProvidersChangeListener listener) {
8410 synchronized (DevicePolicyManagerService.this) {
8411 if (mWidgetProviderListeners == null) {
8412 mWidgetProviderListeners = new ArrayList<>();
8414 if (!mWidgetProviderListeners.contains(listener)) {
8415 mWidgetProviderListeners.add(listener);
8421 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8422 synchronized(DevicePolicyManagerService.this) {
8423 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8427 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8428 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8429 synchronized (DevicePolicyManagerService.this) {
8430 listeners = new ArrayList<>(mWidgetProviderListeners);
8432 final int listenerCount = listeners.size();
8433 for (int i = 0; i < listenerCount; i++) {
8434 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8435 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8440 public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
8441 Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8442 intent.putExtra(Intent.EXTRA_USER_ID, userId);
8443 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8445 // This method is called from AM with its lock held, so don't take the DPMS lock.
8448 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8449 if (profileOwner != null) {
8450 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
8454 final Pair<Integer, ComponentName> deviceOwner =
8455 mOwners.getDeviceOwnerUserIdAndComponent();
8456 if (deviceOwner != null && deviceOwner.first == userId) {
8457 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
8461 // We're not specifying the device admin because there isn't one.
8467 * Returns true if specified admin is allowed to limit passwords and has a
8468 * {@code passwordQuality} of at least {@code minPasswordQuality}
8470 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8471 if (admin.passwordQuality < minPasswordQuality) {
8474 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8478 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8479 if (policy != null && !policy.isValid()) {
8480 throw new IllegalArgumentException("Invalid system update policy.");
8482 synchronized (this) {
8483 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8484 if (policy == null) {
8485 mOwners.clearSystemUpdatePolicy();
8487 mOwners.setSystemUpdatePolicy(policy);
8489 mOwners.writeDeviceOwner();
8491 mContext.sendBroadcastAsUser(
8492 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8497 public SystemUpdatePolicy getSystemUpdatePolicy() {
8498 if (UserManager.isDeviceInDemoMode(mContext)) {
8499 // Pretending to have an automatic update policy when the device is in retail demo
8500 // mode. This will allow the device to download and install an ota without
8501 // any user interaction.
8502 return SystemUpdatePolicy.createAutomaticInstallPolicy();
8504 synchronized (this) {
8505 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
8506 if (policy != null && !policy.isValid()) {
8507 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8515 * Checks if the caller of the method is the device owner app.
8517 * @param callerUid UID of the caller.
8518 * @return true if the caller is the device owner app
8521 boolean isCallerDeviceOwner(int callerUid) {
8522 synchronized (this) {
8523 if (!mOwners.hasDeviceOwner()) {
8526 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8529 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8531 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8533 for (String pkg : pkgs) {
8534 if (deviceOwnerPackageName.equals(pkg)) {
8544 public void notifyPendingSystemUpdate(long updateReceivedTime) {
8545 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8546 "Only the system update service can broadcast update information");
8548 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8549 Slog.w(LOG_TAG, "Only the system update service in the system user " +
8550 "can broadcast update information.");
8553 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8554 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8555 updateReceivedTime);
8557 synchronized (this) {
8558 final String deviceOwnerPackage =
8559 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8561 if (deviceOwnerPackage == null) {
8564 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8566 ActivityInfo[] receivers = null;
8568 receivers = mContext.getPackageManager().getPackageInfo(
8569 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8570 } catch (NameNotFoundException e) {
8571 Log.e(LOG_TAG, "Cannot find device owner package", e);
8573 if (receivers != null) {
8574 long ident = mInjector.binderClearCallingIdentity();
8576 for (int i = 0; i < receivers.length; i++) {
8577 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8578 intent.setComponent(new ComponentName(deviceOwnerPackage,
8579 receivers[i].name));
8580 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8584 mInjector.binderRestoreCallingIdentity(ident);
8591 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8592 int userId = UserHandle.getCallingUserId();
8593 synchronized (this) {
8594 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8595 DevicePolicyData userPolicy = getUserData(userId);
8596 if (userPolicy.mPermissionPolicy != policy) {
8597 userPolicy.mPermissionPolicy = policy;
8598 saveSettingsLocked(userId);
8604 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8605 int userId = UserHandle.getCallingUserId();
8606 synchronized (this) {
8607 DevicePolicyData userPolicy = getUserData(userId);
8608 return userPolicy.mPermissionPolicy;
8613 public boolean setPermissionGrantState(ComponentName admin, String packageName,
8614 String permission, int grantState) throws RemoteException {
8615 UserHandle user = mInjector.binderGetCallingUserHandle();
8616 synchronized (this) {
8617 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8618 long ident = mInjector.binderClearCallingIdentity();
8620 if (getTargetSdk(packageName, user.getIdentifier())
8621 < android.os.Build.VERSION_CODES.M) {
8624 final PackageManager packageManager = mContext.getPackageManager();
8625 switch (grantState) {
8626 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8627 packageManager.grantRuntimePermission(packageName, permission, user);
8628 packageManager.updatePermissionFlags(permission, packageName,
8629 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8630 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8633 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8634 packageManager.revokeRuntimePermission(packageName,
8636 packageManager.updatePermissionFlags(permission, packageName,
8637 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8638 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8641 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8642 packageManager.updatePermissionFlags(permission, packageName,
8643 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8647 } catch (SecurityException se) {
8650 mInjector.binderRestoreCallingIdentity(ident);
8656 public int getPermissionGrantState(ComponentName admin, String packageName,
8657 String permission) throws RemoteException {
8658 PackageManager packageManager = mContext.getPackageManager();
8660 UserHandle user = mInjector.binderGetCallingUserHandle();
8661 synchronized (this) {
8662 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8663 long ident = mInjector.binderClearCallingIdentity();
8665 int granted = mIPackageManager.checkPermission(permission,
8666 packageName, user.getIdentifier());
8667 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8668 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8669 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8670 // Not controlled by policy
8671 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8673 // Policy controlled so return result based on permission grant state
8674 return granted == PackageManager.PERMISSION_GRANTED
8675 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8676 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8679 mInjector.binderRestoreCallingIdentity(ident);
8684 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8686 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8688 return (pi != null) && (pi.applicationInfo.flags != 0);
8689 } catch (RemoteException re) {
8690 throw new RuntimeException("Package manager has died", re);
8695 public boolean isProvisioningAllowed(String action) {
8700 final int callingUserId = mInjector.userHandleGetCallingUserId();
8701 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8702 if (!hasFeatureManagedUsers()) {
8705 synchronized (this) {
8706 if (mOwners.hasDeviceOwner()) {
8707 if (!mInjector.userManagerIsSplitSystemUser()) {
8708 // Only split-system-user systems support managed-profiles in combination with
8712 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8713 // Only system device-owner supports managed-profiles. Non-system device-owner
8717 if (callingUserId == UserHandle.USER_SYSTEM) {
8718 // Managed-profiles cannot be setup on the system user, only regular users.
8723 if (getProfileOwner(callingUserId) != null) {
8724 // Managed user cannot have a managed profile.
8727 final long ident = mInjector.binderClearCallingIdentity();
8729 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8733 mInjector.binderRestoreCallingIdentity(ident);
8736 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8737 return isDeviceOwnerProvisioningAllowed(callingUserId);
8738 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8739 if (!hasFeatureManagedUsers()) {
8742 if (!mInjector.userManagerIsSplitSystemUser()) {
8743 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8746 if (callingUserId == UserHandle.USER_SYSTEM) {
8747 // System user cannot be a managed user.
8750 if (hasUserSetupCompleted(callingUserId)) {
8753 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8757 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8758 if (!mInjector.userManagerIsSplitSystemUser()) {
8759 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8762 return isDeviceOwnerProvisioningAllowed(callingUserId);
8764 throw new IllegalArgumentException("Unknown provisioning action " + action);
8768 * The device owner can only be set before the setup phase of the primary user has completed,
8769 * except for adb command if no accounts or additional users are present on the device.
8771 private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreConditionLocked(
8772 @Nullable ComponentName owner, int deviceOwnerUserId, boolean isAdb,
8773 boolean hasIncompatibleAccountsOrNonAdb) {
8774 if (mOwners.hasDeviceOwner()) {
8775 return CODE_HAS_DEVICE_OWNER;
8777 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8778 return CODE_USER_HAS_PROFILE_OWNER;
8780 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8781 return CODE_USER_NOT_RUNNING;
8783 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8784 return CODE_HAS_PAIRED;
8787 // if shell command runs after user setup completed check device status. Otherwise, OK.
8788 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8789 if (!mInjector.userManagerIsSplitSystemUser()) {
8790 if (mUserManager.getUserCount() > 1) {
8791 return CODE_NONSYSTEM_USER_EXISTS;
8793 if (hasIncompatibleAccountsOrNonAdb) {
8794 return CODE_ACCOUNTS_NOT_EMPTY;
8797 // STOPSHIP Do proper check in split user mode
8802 if (!mInjector.userManagerIsSplitSystemUser()) {
8803 // In non-split user mode, DO has to be user 0
8804 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8805 return CODE_NOT_SYSTEM_USER;
8807 // In non-split user mode, only provision DO before setup wizard completes
8808 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8809 return CODE_USER_SETUP_COMPLETED;
8812 // STOPSHIP Do proper check in split user mode
8818 private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8819 synchronized (this) {
8820 return CODE_OK == checkSetDeviceOwnerPreConditionLocked(
8821 /* owner unknown */ null, deviceOwnerUserId, /* isAdb */ false,
8822 /* hasIncompatibleAccountsOrNonAdb=*/ true);
8826 private boolean hasFeatureManagedUsers() {
8828 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8829 } catch (RemoteException e) {
8835 public String getWifiMacAddress(ComponentName admin) {
8836 // Make sure caller has DO.
8837 synchronized (this) {
8838 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8841 final long ident = mInjector.binderClearCallingIdentity();
8843 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8844 if (wifiInfo == null) {
8847 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8849 mInjector.binderRestoreCallingIdentity(ident);
8854 * Returns the target sdk version number that the given packageName was built for
8855 * in the given user.
8857 private int getTargetSdk(String packageName, int userId) {
8858 final ApplicationInfo ai;
8860 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8861 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8862 return targetSdkVersion;
8863 } catch (RemoteException e) {
8870 public boolean isManagedProfile(ComponentName admin) {
8871 synchronized (this) {
8872 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8874 final int callingUserId = mInjector.userHandleGetCallingUserId();
8875 final UserInfo user = getUserInfo(callingUserId);
8876 return user != null && user.isManagedProfile();
8880 public boolean isSystemOnlyUser(ComponentName admin) {
8881 synchronized (this) {
8882 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8884 final int callingUserId = mInjector.userHandleGetCallingUserId();
8885 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8889 public void reboot(ComponentName admin) {
8890 Preconditions.checkNotNull(admin);
8891 // Make sure caller has DO.
8892 synchronized (this) {
8893 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8895 long ident = mInjector.binderClearCallingIdentity();
8897 // Make sure there are no ongoing calls on the device.
8898 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8899 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8901 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8903 mInjector.binderRestoreCallingIdentity(ident);
8908 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8912 Preconditions.checkNotNull(who, "ComponentName is null");
8913 final int userHandle = mInjector.userHandleGetCallingUserId();
8914 synchronized (this) {
8915 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8916 mInjector.binderGetCallingUid());
8917 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8918 admin.shortSupportMessage = message;
8919 saveSettingsLocked(userHandle);
8925 public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8929 Preconditions.checkNotNull(who, "ComponentName is null");
8930 synchronized (this) {
8931 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8932 mInjector.binderGetCallingUid());
8933 return admin.shortSupportMessage;
8938 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8942 Preconditions.checkNotNull(who, "ComponentName is null");
8943 final int userHandle = mInjector.userHandleGetCallingUserId();
8944 synchronized (this) {
8945 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8946 mInjector.binderGetCallingUid());
8947 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8948 admin.longSupportMessage = message;
8949 saveSettingsLocked(userHandle);
8955 public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8959 Preconditions.checkNotNull(who, "ComponentName is null");
8960 synchronized (this) {
8961 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8962 mInjector.binderGetCallingUid());
8963 return admin.longSupportMessage;
8968 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8972 Preconditions.checkNotNull(who, "ComponentName is null");
8973 if (!isCallerWithSystemUid()) {
8974 throw new SecurityException("Only the system can query support message for user");
8976 synchronized (this) {
8977 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8978 if (admin != null) {
8979 return admin.shortSupportMessage;
8986 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8990 Preconditions.checkNotNull(who, "ComponentName is null");
8991 if (!isCallerWithSystemUid()) {
8992 throw new SecurityException("Only the system can query support message for user");
8994 synchronized (this) {
8995 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8996 if (admin != null) {
8997 return admin.longSupportMessage;
9004 public void setOrganizationColor(@NonNull ComponentName who, int color) {
9008 Preconditions.checkNotNull(who, "ComponentName is null");
9009 final int userHandle = mInjector.userHandleGetCallingUserId();
9010 enforceManagedProfile(userHandle, "set organization color");
9011 synchronized (this) {
9012 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9013 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9014 admin.organizationColor = color;
9015 saveSettingsLocked(userHandle);
9020 public void setOrganizationColorForUser(int color, int userId) {
9024 enforceFullCrossUsersPermission(userId);
9025 enforceManageUsers();
9026 enforceManagedProfile(userId, "set organization color");
9027 synchronized (this) {
9028 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9029 admin.organizationColor = color;
9030 saveSettingsLocked(userId);
9035 public int getOrganizationColor(@NonNull ComponentName who) {
9037 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9039 Preconditions.checkNotNull(who, "ComponentName is null");
9040 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
9041 synchronized (this) {
9042 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9043 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9044 return admin.organizationColor;
9049 public int getOrganizationColorForUser(int userHandle) {
9051 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9053 enforceFullCrossUsersPermission(userHandle);
9054 enforceManagedProfile(userHandle, "get organization color");
9055 synchronized (this) {
9056 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9057 return (profileOwner != null)
9058 ? profileOwner.organizationColor
9059 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
9064 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
9068 Preconditions.checkNotNull(who, "ComponentName is null");
9069 final int userHandle = mInjector.userHandleGetCallingUserId();
9070 enforceManagedProfile(userHandle, "set organization name");
9071 synchronized (this) {
9072 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9073 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9074 if (!TextUtils.equals(admin.organizationName, text)) {
9075 admin.organizationName = (text == null || text.length() == 0)
9076 ? null : text.toString();
9077 saveSettingsLocked(userHandle);
9083 public CharSequence getOrganizationName(@NonNull ComponentName who) {
9087 Preconditions.checkNotNull(who, "ComponentName is null");
9088 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
9089 synchronized(this) {
9090 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9091 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9092 return admin.organizationName;
9097 public CharSequence getOrganizationNameForUser(int userHandle) {
9101 enforceFullCrossUsersPermission(userHandle);
9102 enforceManagedProfile(userHandle, "get organization name");
9103 synchronized (this) {
9104 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9105 return (profileOwner != null)
9106 ? profileOwner.organizationName
9112 public void setAffiliationIds(ComponentName admin, List<String> ids) {
9113 final Set<String> affiliationIds = new ArraySet<String>(ids);
9114 final int callingUserId = mInjector.userHandleGetCallingUserId();
9116 synchronized (this) {
9117 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9118 getUserData(callingUserId).mAffiliationIds = affiliationIds;
9119 saveSettingsLocked(callingUserId);
9120 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
9121 // Affiliation ids specified by the device owner are additionally stored in
9122 // UserHandle.USER_SYSTEM's DevicePolicyData.
9123 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
9124 saveSettingsLocked(UserHandle.USER_SYSTEM);
9130 public boolean isAffiliatedUser() {
9131 final int callingUserId = mInjector.userHandleGetCallingUserId();
9133 synchronized (this) {
9134 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
9135 // The user that the DO is installed on is always affiliated.
9138 final ComponentName profileOwner = getProfileOwner(callingUserId);
9139 if (profileOwner == null
9140 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
9143 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
9144 final Set<String> deviceAffiliationIds =
9145 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
9146 for (String id : userAffiliationIds) {
9147 if (deviceAffiliationIds.contains(id)) {
9155 private synchronized void disableDeviceOwnerManagedSingleUserFeaturesIfNeeded() {
9156 final boolean isSingleUserManagedDevice = isDeviceOwnerManagedSingleUserDevice();
9158 // disable security logging if needed
9159 if (!isSingleUserManagedDevice) {
9160 mInjector.securityLogSetLoggingEnabledProperty(false);
9161 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user managed"
9165 // disable backup service if needed
9166 // note: when clearing DO, the backup service shouldn't be disabled if it was enabled by
9168 if (mOwners.hasDeviceOwner() && !isSingleUserManagedDevice) {
9169 setBackupServiceEnabledInternal(false);
9170 Slog.w(LOG_TAG, "Backup is off as it's a managed device that has more that one user.");
9173 // disable network logging if needed
9174 if (!isSingleUserManagedDevice) {
9175 setNetworkLoggingActiveInternal(false);
9176 Slog.w(LOG_TAG, "Network logging turned off as it's no longer a single user managed"
9178 // if there still is a device owner, disable logging policy, otherwise the admin
9180 if (mOwners.hasDeviceOwner()) {
9181 getDeviceOwnerAdminLocked().isNetworkLoggingEnabled = false;
9182 saveSettingsLocked(mOwners.getDeviceOwnerUserId());
9188 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
9189 Preconditions.checkNotNull(admin);
9190 ensureDeviceOwnerManagingSingleUser(admin);
9192 synchronized (this) {
9193 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
9196 mInjector.securityLogSetLoggingEnabledProperty(enabled);
9198 mSecurityLogMonitor.start();
9200 mSecurityLogMonitor.stop();
9206 public boolean isSecurityLoggingEnabled(ComponentName admin) {
9207 Preconditions.checkNotNull(admin);
9208 synchronized (this) {
9209 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9210 return mInjector.securityLogGetLoggingEnabledProperty();
9215 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
9216 Preconditions.checkNotNull(admin);
9217 ensureDeviceOwnerManagingSingleUser(admin);
9219 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
9223 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
9225 SecurityLog.readPreviousEvents(output);
9226 return new ParceledListSlice<SecurityEvent>(output);
9227 } catch (IOException e) {
9228 Slog.w(LOG_TAG, "Fail to read previous events" , e);
9229 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
9234 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
9235 Preconditions.checkNotNull(admin);
9236 ensureDeviceOwnerManagingSingleUser(admin);
9238 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
9239 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
9242 private void enforceCanManageDeviceAdmin() {
9243 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
9247 private void enforceCanManageProfileAndDeviceOwners() {
9248 mContext.enforceCallingOrSelfPermission(
9249 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
9253 public boolean isUninstallInQueue(final String packageName) {
9254 enforceCanManageDeviceAdmin();
9255 final int userId = mInjector.userHandleGetCallingUserId();
9256 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9257 synchronized (this) {
9258 return mPackagesToRemove.contains(packageUserPair);
9263 public void uninstallPackageWithActiveAdmins(final String packageName) {
9264 enforceCanManageDeviceAdmin();
9265 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
9267 final int userId = mInjector.userHandleGetCallingUserId();
9269 enforceUserUnlocked(userId);
9271 final ComponentName profileOwner = getProfileOwner(userId);
9272 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
9273 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
9276 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
9277 if (getDeviceOwnerUserId() == userId && deviceOwner != null
9278 && packageName.equals(deviceOwner.getPackageName())) {
9279 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
9282 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9283 synchronized (this) {
9284 mPackagesToRemove.add(packageUserPair);
9287 // All active admins on the user.
9288 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
9290 // Active admins in the target package.
9291 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
9292 if (allActiveAdmins != null) {
9293 for (ComponentName activeAdmin : allActiveAdmins) {
9294 if (packageName.equals(activeAdmin.getPackageName())) {
9295 packageActiveAdmins.add(activeAdmin);
9296 removeActiveAdmin(activeAdmin, userId);
9300 if (packageActiveAdmins.size() == 0) {
9301 startUninstallIntent(packageName, userId);
9303 mHandler.postDelayed(new Runnable() {
9306 for (ComponentName activeAdmin : packageActiveAdmins) {
9307 removeAdminArtifacts(activeAdmin, userId);
9309 startUninstallIntent(packageName, userId);
9311 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9316 public boolean isDeviceProvisioned() {
9317 return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9320 private void removePackageIfRequired(final String packageName, final int userId) {
9321 if (!packageHasActiveAdmins(packageName, userId)) {
9322 // Will not do anything if uninstall was not requested or was already started.
9323 startUninstallIntent(packageName, userId);
9327 private void startUninstallIntent(final String packageName, final int userId) {
9328 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9329 synchronized (this) {
9330 if (!mPackagesToRemove.contains(packageUserPair)) {
9331 // Do nothing if uninstall was not requested or was already started.
9334 mPackagesToRemove.remove(packageUserPair);
9337 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9338 // Package does not exist. Nothing to do.
9341 } catch (RemoteException re) {
9342 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9345 try { // force stop the package before uninstalling
9346 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9347 } catch (RemoteException re) {
9348 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9350 final Uri packageURI = Uri.parse("package:" + packageName);
9351 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9352 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9353 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9357 * Removes the admin from the policy. Ideally called after the admin's
9358 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9360 * @param adminReceiver The admin to remove
9361 * @param userHandle The user for which this admin has to be removed.
9363 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9364 synchronized (this) {
9365 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9366 if (admin == null) {
9369 final DevicePolicyData policy = getUserData(userHandle);
9370 final boolean doProxyCleanup = admin.info.usesPolicy(
9371 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9372 policy.mAdminList.remove(admin);
9373 policy.mAdminMap.remove(adminReceiver);
9374 validatePasswordOwnerLocked(policy);
9375 if (doProxyCleanup) {
9376 resetGlobalProxyLocked(policy);
9378 saveSettingsLocked(userHandle);
9379 updateMaximumTimeToLockLocked(userHandle);
9380 policy.mRemovingAdmins.remove(adminReceiver);
9382 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
9384 // The removed admin might have disabled camera, so update user
9386 pushUserRestrictions(userHandle);
9390 public void setDeviceProvisioningConfigApplied() {
9391 enforceManageUsers();
9392 synchronized (this) {
9393 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9394 policy.mDeviceProvisioningConfigApplied = true;
9395 saveSettingsLocked(UserHandle.USER_SYSTEM);
9400 public boolean isDeviceProvisioningConfigApplied() {
9401 enforceManageUsers();
9402 synchronized (this) {
9403 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9404 return policy.mDeviceProvisioningConfigApplied;
9409 * Return true if a given user has any accounts that'll prevent installing a device or profile
9410 * owner {@code owner}.
9411 * - If the user has no accounts, then return false.
9412 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
9413 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
9414 * ..._DISALLOWED, return true.
9415 * - Otherwise return false.
9417 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used
9418 * when the caller is not ADB.
9420 * DO NOT CALL IT WITH THE DPMS LOCK HELD.
9422 private boolean hasIncompatibleAccountsOrNonAdbNoLock(
9423 int userId, @Nullable ComponentName owner) {
9424 final boolean isAdb = (mInjector.binderGetCallingUid() == Process.SHELL_UID)
9425 || (mInjector.binderGetCallingUid() == Process.ROOT_UID);
9430 if (Thread.holdsLock(this)) {
9431 Slog.wtf(LOG_TAG, "hasIncompatibleAccountsNoLock() called with the DPMS lock held.");
9435 final long token = mInjector.binderClearCallingIdentity();
9437 final AccountManager am = AccountManager.get(mContext);
9438 final Account accounts[] = am.getAccountsAsUser(userId);
9439 if (accounts.length == 0) {
9442 synchronized (this) {
9443 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
9445 "Non test-only owner can't be installed with existing accounts.");
9450 final String[] feature_allow =
9451 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
9452 final String[] feature_disallow =
9453 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
9455 boolean compatible = true;
9456 for (Account account : accounts) {
9457 if (hasAccountFeatures(am, account, feature_disallow)) {
9458 Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
9462 if (!hasAccountFeatures(am, account, feature_allow)) {
9463 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
9469 Log.w(LOG_TAG, "All accounts are compatible");
9471 Log.e(LOG_TAG, "Found incompatible accounts");
9475 mInjector.binderRestoreCallingIdentity(token);
9479 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
9481 return am.hasFeatures(account, features, null, null).getResult();
9482 } catch (Exception e) {
9483 Log.w(LOG_TAG, "Failed to get account feature", e);
9489 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
9490 Preconditions.checkNotNull(admin);
9494 ensureDeviceOwnerManagingSingleUser(admin);
9495 setBackupServiceEnabledInternal(enabled);
9498 private synchronized void setBackupServiceEnabledInternal(boolean enabled) {
9499 long ident = mInjector.binderClearCallingIdentity();
9501 IBackupManager ibm = mInjector.getIBackupManager();
9503 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
9505 } catch (RemoteException e) {
9506 throw new IllegalStateException(
9507 "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
9509 mInjector.binderRestoreCallingIdentity(ident);
9514 public boolean isBackupServiceEnabled(ComponentName admin) {
9515 Preconditions.checkNotNull(admin);
9519 synchronized (this) {
9520 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9522 IBackupManager ibm = mInjector.getIBackupManager();
9523 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
9524 } catch (RemoteException e) {
9525 throw new IllegalStateException("Failed requesting backup service state.", e);
9531 public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
9535 Preconditions.checkNotNull(admin);
9536 ensureDeviceOwnerManagingSingleUser(admin);
9538 if (enabled == isNetworkLoggingEnabledInternalLocked()) {
9539 // already in the requested state
9542 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9543 deviceOwner.isNetworkLoggingEnabled = enabled;
9545 deviceOwner.numNetworkLoggingNotifications = 0;
9546 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
9548 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
9550 setNetworkLoggingActiveInternal(enabled);
9553 private synchronized void setNetworkLoggingActiveInternal(boolean active) {
9554 final long callingIdentity = mInjector.binderClearCallingIdentity();
9557 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
9558 if (!mNetworkLogger.startNetworkLogging()) {
9559 mNetworkLogger = null;
9560 Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
9561 + " service not being available yet.");
9563 sendNetworkLoggingNotificationLocked();
9565 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
9566 mNetworkLogger = null;
9567 Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
9568 + " service not being available yet.");
9570 mNetworkLogger = null;
9571 mInjector.getNotificationManager().cancel(NETWORK_LOGGING_NOTIFICATION_ID);
9574 mInjector.binderRestoreCallingIdentity(callingIdentity);
9579 public boolean isNetworkLoggingEnabled(ComponentName admin) {
9583 synchronized (this) {
9584 enforceDeviceOwnerOrManageUsers();
9585 return isNetworkLoggingEnabledInternalLocked();
9589 private boolean isNetworkLoggingEnabledInternalLocked() {
9590 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9591 return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
9595 * A maximum of 1200 events are returned, and the total marshalled size is in the order of
9596 * 100kB, so returning a List instead of ParceledListSlice is acceptable.
9597 * Ideally this would be done with ParceledList, however it only supports homogeneous types.
9599 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
9602 public synchronized List<NetworkEvent> retrieveNetworkLogs(ComponentName admin,
9607 Preconditions.checkNotNull(admin);
9608 ensureDeviceOwnerManagingSingleUser(admin);
9610 if (mNetworkLogger == null) {
9613 return isNetworkLoggingEnabledInternalLocked()
9614 ? mNetworkLogger.retrieveLogs(batchToken)
9618 private void sendNetworkLoggingNotificationLocked() {
9619 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9620 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
9623 if (deviceOwner.numNetworkLoggingNotifications >=
9624 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
9627 final long now = System.currentTimeMillis();
9628 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
9631 deviceOwner.numNetworkLoggingNotifications++;
9632 if (deviceOwner.numNetworkLoggingNotifications
9633 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
9634 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
9636 deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
9638 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
9639 intent.setPackage("com.android.systemui");
9640 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
9641 UserHandle.CURRENT);
9642 Notification notification = new Notification.Builder(mContext)
9643 .setSmallIcon(R.drawable.ic_qs_network_logging)
9644 .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
9645 .setContentText(mContext.getString(R.string.network_logging_notification_text))
9646 .setTicker(mContext.getString(R.string.network_logging_notification_title))
9648 .setContentIntent(pendingIntent)
9650 mInjector.getNotificationManager().notify(NETWORK_LOGGING_NOTIFICATION_ID, notification);
9651 saveSettingsLocked(mOwners.getDeviceOwnerUserId());