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.ActivityManagerNative;
42 import android.app.AlarmManager;
43 import android.app.AppGlobals;
44 import android.app.IActivityManager;
45 import android.app.Notification;
46 import android.app.NotificationManager;
47 import android.app.PendingIntent;
48 import android.app.StatusBarManager;
49 import android.app.admin.DeviceAdminInfo;
50 import android.app.admin.DeviceAdminReceiver;
51 import android.app.admin.DevicePolicyManager;
52 import android.app.admin.DevicePolicyManagerInternal;
53 import android.app.admin.IDevicePolicyManager;
54 import android.app.admin.NetworkEvent;
55 import android.app.admin.SecurityLog;
56 import android.app.admin.SecurityLog.SecurityEvent;
57 import android.app.admin.SystemUpdatePolicy;
58 import android.app.backup.IBackupManager;
59 import android.app.trust.TrustManager;
60 import android.content.BroadcastReceiver;
61 import android.content.ComponentName;
62 import android.content.Context;
63 import android.content.Intent;
64 import android.content.IntentFilter;
65 import android.content.pm.ActivityInfo;
66 import android.content.pm.ApplicationInfo;
67 import android.content.pm.IPackageManager;
68 import android.content.pm.PackageInfo;
69 import android.content.pm.PackageManager;
70 import android.content.pm.PackageManager.NameNotFoundException;
71 import android.content.pm.PackageManagerInternal;
72 import android.content.pm.ParceledListSlice;
73 import android.content.pm.ResolveInfo;
74 import android.content.pm.ServiceInfo;
75 import android.content.pm.UserInfo;
76 import android.database.ContentObserver;
77 import android.graphics.Bitmap;
78 import android.graphics.Color;
79 import android.media.AudioManager;
80 import android.media.IAudioService;
81 import android.net.ConnectivityManager;
82 import android.net.IIpConnectivityMetrics;
83 import android.net.ProxyInfo;
84 import android.net.Uri;
85 import android.net.metrics.IpConnectivityLog;
86 import android.net.wifi.WifiInfo;
87 import android.net.wifi.WifiManager;
88 import android.os.AsyncTask;
89 import android.os.Binder;
90 import android.os.Build;
91 import android.os.Bundle;
92 import android.os.Environment;
93 import android.os.FileUtils;
94 import android.os.Handler;
95 import android.os.IBinder;
96 import android.os.Looper;
97 import android.os.ParcelFileDescriptor;
98 import android.os.PersistableBundle;
99 import android.os.PowerManager;
100 import android.os.PowerManagerInternal;
101 import android.os.Process;
102 import android.os.RecoverySystem;
103 import android.os.RemoteCallback;
104 import android.os.RemoteException;
105 import android.os.ServiceManager;
106 import android.os.SystemClock;
107 import android.os.SystemProperties;
108 import android.os.UserHandle;
109 import android.os.UserManager;
110 import android.os.UserManagerInternal;
111 import android.os.storage.StorageManager;
112 import android.provider.ContactsContract.QuickContact;
113 import android.provider.ContactsInternal;
114 import android.provider.Settings;
115 import android.security.Credentials;
116 import android.security.IKeyChainAliasCallback;
117 import android.security.IKeyChainService;
118 import android.security.KeyChain;
119 import android.security.KeyChain.KeyChainConnection;
120 import android.service.persistentdata.PersistentDataBlockManager;
121 import android.telephony.TelephonyManager;
122 import android.text.TextUtils;
123 import android.util.ArrayMap;
124 import android.util.ArraySet;
125 import android.util.Log;
126 import android.util.Pair;
127 import android.util.Slog;
128 import android.util.SparseArray;
129 import android.util.Xml;
130 import android.view.IWindowManager;
131 import android.view.accessibility.AccessibilityManager;
132 import android.view.accessibility.IAccessibilityManager;
133 import android.view.inputmethod.InputMethodInfo;
134 import android.view.inputmethod.InputMethodManager;
136 import com.android.internal.R;
137 import com.android.internal.annotations.VisibleForTesting;
138 import com.android.internal.statusbar.IStatusBarService;
139 import com.android.internal.util.FastXmlSerializer;
140 import com.android.internal.util.JournaledFile;
141 import com.android.internal.util.ParcelableString;
142 import com.android.internal.util.Preconditions;
143 import com.android.internal.util.XmlUtils;
144 import com.android.internal.widget.LockPatternUtils;
145 import com.android.server.LocalServices;
146 import com.android.server.SystemService;
147 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
148 import com.android.server.pm.UserRestrictionsUtils;
149 import com.google.android.collect.Sets;
151 import org.xmlpull.v1.XmlPullParser;
152 import org.xmlpull.v1.XmlPullParserException;
153 import org.xmlpull.v1.XmlSerializer;
155 import java.io.ByteArrayInputStream;
157 import java.io.FileDescriptor;
158 import java.io.FileInputStream;
159 import java.io.FileNotFoundException;
160 import java.io.FileOutputStream;
161 import java.io.IOException;
162 import java.io.PrintWriter;
163 import java.lang.annotation.Retention;
164 import java.lang.annotation.RetentionPolicy;
165 import java.nio.charset.StandardCharsets;
166 import java.security.cert.CertificateException;
167 import java.security.cert.CertificateFactory;
168 import java.security.cert.X509Certificate;
169 import java.text.DateFormat;
170 import java.util.ArrayList;
171 import java.util.Arrays;
172 import java.util.Collections;
173 import java.util.Date;
174 import java.util.List;
175 import java.util.Map.Entry;
176 import java.util.Set;
177 import java.util.concurrent.atomic.AtomicBoolean;
180 * Implementation of the device policy APIs.
182 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
184 private static final String LOG_TAG = "DevicePolicyManagerService";
186 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
188 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
190 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
192 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
194 private static final String TAG_STATUS_BAR = "statusbar";
196 private static final String ATTR_DISABLED = "disabled";
198 private static final String ATTR_NAME = "name";
200 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
201 "do-not-ask-credentials-on-boot";
203 private static final String TAG_AFFILIATION_ID = "affiliation-id";
205 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
207 private static final String ATTR_VALUE = "value";
209 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
211 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
213 private static final long MS_PER_DAY = 86400 * 1000;
215 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
217 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
218 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
220 private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
221 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
222 private static final int NETWORK_LOGGING_NOTIFICATION_ID = 1002;
224 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
225 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
226 private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
227 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
228 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
229 "device-provisioning-config-applied";
230 private static final String ATTR_DEVICE_PAIRED = "device-paired";
232 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
233 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
234 = "application-restrictions-manager";
237 * System property whose value is either "true" or "false", indicating whether
239 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
241 private static final int STATUS_BAR_DISABLE_MASK =
242 StatusBarManager.DISABLE_EXPAND |
243 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
244 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
245 StatusBarManager.DISABLE_SEARCH;
247 private static final int STATUS_BAR_DISABLE2_MASK =
248 StatusBarManager.DISABLE2_QUICK_SETTINGS;
250 private static final Set<String> SECURE_SETTINGS_WHITELIST;
251 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
252 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
253 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
255 SECURE_SETTINGS_WHITELIST = new ArraySet<>();
256 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
257 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
258 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
260 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
261 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
262 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
264 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
265 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
266 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
267 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
268 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
269 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
270 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
271 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
272 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
274 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
275 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
276 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
277 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
278 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
279 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
283 * Keyguard features that when set on a managed profile that doesn't have its own challenge will
284 * affect the profile's parent user. These can also be set on the managed profile's parent DPM
287 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
288 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
289 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
292 * Keyguard features that when set on a profile affect the profile content or challenge only.
293 * These cannot be set on the managed profile's parent DPM instance
295 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
296 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
298 /** Keyguard features that are allowed to be set on a managed profile */
299 private static final int PROFILE_KEYGUARD_FEATURES =
300 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
302 private static final int CODE_OK = 0;
303 private static final int CODE_HAS_DEVICE_OWNER = 1;
304 private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
305 private static final int CODE_USER_NOT_RUNNING = 3;
306 private static final int CODE_USER_SETUP_COMPLETED = 4;
307 private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
308 private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
309 private static final int CODE_NOT_SYSTEM_USER = 7;
310 private static final int CODE_HAS_PAIRED = 8;
312 @Retention(RetentionPolicy.SOURCE)
313 @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
314 CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
315 private @interface DeviceOwnerPreConditionCode {}
317 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
320 * Minimum timeout in milliseconds after which unlocking with weak auth times out,
321 * i.e. the user has to use a strong authentication method like password, PIN or pattern.
323 private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
325 final Context mContext;
326 final Injector mInjector;
327 final IPackageManager mIPackageManager;
328 final UserManager mUserManager;
329 final UserManagerInternal mUserManagerInternal;
330 final TelephonyManager mTelephonyManager;
331 private final LockPatternUtils mLockPatternUtils;
334 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
335 * is requested for user u.
337 private final Set<Pair<String, Integer>> mPackagesToRemove =
338 new ArraySet<Pair<String, Integer>>();
340 final LocalService mLocalService;
342 // Stores and loads state on device and profile owners.
344 final Owners mOwners;
346 private final Binder mToken = new Binder();
349 * Whether or not device admin feature is supported. If it isn't return defaults for all
355 * Whether or not this device is a watch.
359 private final SecurityLogMonitor mSecurityLogMonitor;
360 private NetworkLogger mNetworkLogger;
362 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
363 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
365 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
368 if(mRemoteBugreportServiceIsActive.get()) {
374 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
377 public void onReceive(Context context, Intent intent) {
378 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
379 && mRemoteBugreportServiceIsActive.get()) {
380 onBugreportFinished(intent);
385 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
388 public void onReceive(Context context, Intent intent) {
389 String action = intent.getAction();
390 mInjector.getNotificationManager().cancel(LOG_TAG,
391 RemoteBugreportUtils.NOTIFICATION_ID);
392 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
393 onBugreportSharingAccepted();
394 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
395 onBugreportSharingDeclined();
397 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
401 public static final class Lifecycle extends SystemService {
402 private DevicePolicyManagerService mService;
404 public Lifecycle(Context context) {
406 mService = new DevicePolicyManagerService(context);
410 public void onStart() {
411 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
415 public void onBootPhase(int phase) {
416 mService.systemReady(phase);
420 public void onStartUser(int userHandle) {
421 mService.onStartUser(userHandle);
425 public static class DevicePolicyData {
426 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
427 int mActivePasswordLength = 0;
428 int mActivePasswordUpperCase = 0;
429 int mActivePasswordLowerCase = 0;
430 int mActivePasswordLetters = 0;
431 int mActivePasswordNumeric = 0;
432 int mActivePasswordSymbols = 0;
433 int mActivePasswordNonLetter = 0;
434 int mFailedPasswordAttempts = 0;
437 int mPasswordOwner = -1;
438 long mLastMaximumTimeToLock = -1;
439 boolean mUserSetupComplete = false;
440 boolean mPaired = false;
441 int mUserProvisioningState;
442 int mPermissionPolicy;
444 boolean mDeviceProvisioningConfigApplied = false;
446 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
447 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
448 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
450 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
452 // This is the list of component allowed to start lock task mode.
453 List<String> mLockTaskPackages = new ArrayList<>();
455 boolean mStatusBarDisabled = false;
457 ComponentName mRestrictionsProvider;
459 String mDelegatedCertInstallerPackage;
461 boolean doNotAskCredentialsOnBoot = false;
463 String mApplicationRestrictionsManagingPackage;
465 Set<String> mAffiliationIds = new ArraySet<>();
467 // Used for initialization of users created by createAndManageUsers.
468 boolean mAdminBroadcastPending = false;
469 PersistableBundle mInitBundle = null;
471 public DevicePolicyData(int userHandle) {
472 mUserHandle = userHandle;
476 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
478 final Handler mHandler;
480 BroadcastReceiver mReceiver = new BroadcastReceiver() {
482 public void onReceive(Context context, Intent intent) {
483 final String action = intent.getAction();
484 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
488 * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
489 * however it's too early in the boot process to register with IIpConnectivityMetrics
490 * to listen for events.
492 if (Intent.ACTION_USER_STARTED.equals(action)
493 && userHandle == mOwners.getDeviceOwnerUserId()) {
494 synchronized (DevicePolicyManagerService.this) {
495 if (isNetworkLoggingEnabledInternalLocked()) {
496 setNetworkLoggingActiveInternal(true);
500 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
501 && userHandle == mOwners.getDeviceOwnerUserId()
502 && getDeviceOwnerRemoteBugreportUri() != null) {
503 IntentFilter filterConsent = new IntentFilter();
504 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
505 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
506 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
507 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
508 RemoteBugreportUtils.NOTIFICATION_ID,
509 RemoteBugreportUtils.buildNotification(mContext,
510 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
513 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
514 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
516 Slog.v(LOG_TAG, "Sending password expiration notifications for action "
517 + action + " for user " + userHandle);
519 mHandler.post(new Runnable() {
522 handlePasswordExpirationNotification(userHandle);
526 if (Intent.ACTION_USER_UNLOCKED.equals(action)
527 || Intent.ACTION_USER_STARTED.equals(action)
528 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
529 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
530 new MonitoringCertNotificationTask().execute(userId);
532 if (Intent.ACTION_USER_ADDED.equals(action)) {
533 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
534 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
535 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
536 removeUserData(userHandle);
537 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
538 synchronized (DevicePolicyManagerService.this) {
539 // Reset the policy data
540 mUserData.remove(userHandle);
541 sendAdminEnabledBroadcastLocked(userHandle);
543 handlePackagesChanged(null /* check all admins */, userHandle);
544 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
545 handlePackagesChanged(null /* check all admins */, userHandle);
546 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
547 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
548 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
549 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
550 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
551 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
552 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
553 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
554 clearWipeProfileNotification();
559 static class ActiveAdmin {
560 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
561 private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
562 private static final String TAG_DISABLE_CAMERA = "disable-camera";
563 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
564 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
565 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
566 = "disable-bt-contacts-sharing";
567 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
568 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
569 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
570 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
571 private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled";
572 private static final String TAG_ACCOUNT_TYPE = "account-type";
573 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
574 = "permitted-accessiblity-services";
575 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
576 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
577 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
578 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
579 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
580 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
581 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
582 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
583 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
584 private static final String TAG_PERMITTED_IMES = "permitted-imes";
585 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
586 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
587 private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
588 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
589 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
590 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
591 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
592 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
593 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
594 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
595 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
596 private static final String ATTR_VALUE = "value";
597 private static final String TAG_PASSWORD_QUALITY = "password-quality";
598 private static final String TAG_POLICIES = "policies";
599 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
600 "cross-profile-widget-providers";
601 private static final String TAG_PROVIDER = "provider";
602 private static final String TAG_PACKAGE_LIST_ITEM = "item";
603 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages";
604 private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
605 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
606 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
607 private static final String TAG_PARENT_ADMIN = "parent-admin";
608 private static final String TAG_ORGANIZATION_COLOR = "organization-color";
609 private static final String TAG_ORGANIZATION_NAME = "organization-name";
610 private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification";
611 private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications";
613 final DeviceAdminInfo info;
615 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
617 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
618 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
620 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
621 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
623 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
624 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
626 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
627 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
629 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
630 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
632 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
633 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
635 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
636 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
638 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
639 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
641 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
642 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
644 long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
646 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
647 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
649 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
650 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
652 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
653 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
655 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
657 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
659 boolean encryptionRequested = false;
660 boolean testOnlyAdmin = false;
661 boolean disableCamera = false;
662 boolean disableCallerId = false;
663 boolean disableContactsSearch = false;
664 boolean disableBluetoothContactSharing = true;
665 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
666 boolean requireAutoTime = false; // Can only be set by a device owner.
667 boolean forceEphemeralUsers = false; // Can only be set by a device owner.
668 boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner.
670 // one notification after enabling + 3 more after reboots
671 static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 4;
672 int numNetworkLoggingNotifications = 0;
673 long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch
675 ActiveAdmin parentAdmin;
676 final boolean isParent;
678 static class TrustAgentInfo {
679 public PersistableBundle options;
680 TrustAgentInfo(PersistableBundle bundle) {
685 Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
687 // The list of permitted accessibility services package namesas set by a profile
688 // or device owner. Null means all accessibility services are allowed, empty means
689 // none except system services are allowed.
690 List<String> permittedAccessiblityServices;
692 // The list of permitted input methods package names as set by a profile or device owner.
693 // Null means all input methods are allowed, empty means none except system imes are
695 List<String> permittedInputMethods;
697 // List of package names to keep cached.
698 List<String> keepUninstalledPackages;
700 // TODO: review implementation decisions with frameworks team
701 boolean specifiesGlobalProxy = false;
702 String globalProxySpec = null;
703 String globalProxyExclusionList = null;
705 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
707 List<String> crossProfileWidgetProviders;
709 Bundle userRestrictions;
711 // Support text provided by the admin to display to the user.
712 CharSequence shortSupportMessage = null;
713 CharSequence longSupportMessage = null;
715 // Background color of confirm credentials screen. Default: teal.
716 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
717 int organizationColor = DEF_ORGANIZATION_COLOR;
719 // Default title of confirm credentials screen
720 String organizationName = null;
722 ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
727 ActiveAdmin getParentActiveAdmin() {
728 Preconditions.checkState(!isParent);
730 if (parentAdmin == null) {
731 parentAdmin = new ActiveAdmin(info, /* parent */ true);
736 boolean hasParentActiveAdmin() {
737 return parentAdmin != null;
740 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
742 public UserHandle getUserHandle() {
743 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
746 void writeToXml(XmlSerializer out)
747 throws IllegalArgumentException, IllegalStateException, IOException {
748 out.startTag(null, TAG_POLICIES);
749 info.writePoliciesToXml(out);
750 out.endTag(null, TAG_POLICIES);
751 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
752 out.startTag(null, TAG_PASSWORD_QUALITY);
753 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
754 out.endTag(null, TAG_PASSWORD_QUALITY);
755 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
756 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
757 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
758 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
760 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
761 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
762 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
763 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
765 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
766 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
767 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
768 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
770 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
771 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
772 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
773 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
775 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
776 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
777 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
778 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
780 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
781 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
782 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
783 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
785 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
786 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
787 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
788 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
790 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
791 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
792 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
793 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
796 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
797 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
798 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
799 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
801 if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
802 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
803 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
804 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
806 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
807 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
808 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
809 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
811 if (specifiesGlobalProxy) {
812 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
813 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
814 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
815 if (globalProxySpec != null) {
816 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
817 out.attribute(null, ATTR_VALUE, globalProxySpec);
818 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
820 if (globalProxyExclusionList != null) {
821 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
822 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
823 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
826 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
827 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
828 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
829 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
831 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
832 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
833 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
834 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
836 if (encryptionRequested) {
837 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
838 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
839 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
842 out.startTag(null, TAG_TEST_ONLY_ADMIN);
843 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
844 out.endTag(null, TAG_TEST_ONLY_ADMIN);
847 out.startTag(null, TAG_DISABLE_CAMERA);
848 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
849 out.endTag(null, TAG_DISABLE_CAMERA);
851 if (disableCallerId) {
852 out.startTag(null, TAG_DISABLE_CALLER_ID);
853 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
854 out.endTag(null, TAG_DISABLE_CALLER_ID);
856 if (disableContactsSearch) {
857 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
858 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
859 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
861 if (!disableBluetoothContactSharing) {
862 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
863 out.attribute(null, ATTR_VALUE,
864 Boolean.toString(disableBluetoothContactSharing));
865 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
867 if (disableScreenCapture) {
868 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
869 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
870 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
872 if (requireAutoTime) {
873 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
874 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
875 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
877 if (forceEphemeralUsers) {
878 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
879 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
880 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
882 if (isNetworkLoggingEnabled) {
883 out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
884 out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled));
885 out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS,
886 Integer.toString(numNetworkLoggingNotifications));
887 out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION,
888 Long.toString(lastNetworkLoggingNotificationTimeMs));
889 out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
891 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
892 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
893 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
894 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
896 if (!accountTypesWithManagementDisabled.isEmpty()) {
897 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
898 for (String ac : accountTypesWithManagementDisabled) {
899 out.startTag(null, TAG_ACCOUNT_TYPE);
900 out.attribute(null, ATTR_VALUE, ac);
901 out.endTag(null, TAG_ACCOUNT_TYPE);
903 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
905 if (!trustAgentInfos.isEmpty()) {
906 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
907 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
908 for (Entry<String, TrustAgentInfo> entry : set) {
909 TrustAgentInfo trustAgentInfo = entry.getValue();
910 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
911 out.attribute(null, ATTR_VALUE, entry.getKey());
912 if (trustAgentInfo.options != null) {
913 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
915 trustAgentInfo.options.saveToXml(out);
916 } catch (XmlPullParserException e) {
917 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
919 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
921 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
923 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
925 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
926 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
927 final int providerCount = crossProfileWidgetProviders.size();
928 for (int i = 0; i < providerCount; i++) {
929 String provider = crossProfileWidgetProviders.get(i);
930 out.startTag(null, TAG_PROVIDER);
931 out.attribute(null, ATTR_VALUE, provider);
932 out.endTag(null, TAG_PROVIDER);
934 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
936 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
937 permittedAccessiblityServices);
938 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
939 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
940 if (hasUserRestrictions()) {
941 UserRestrictionsUtils.writeRestrictions(
942 out, userRestrictions, TAG_USER_RESTRICTIONS);
944 if (!TextUtils.isEmpty(shortSupportMessage)) {
945 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
946 out.text(shortSupportMessage.toString());
947 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
949 if (!TextUtils.isEmpty(longSupportMessage)) {
950 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
951 out.text(longSupportMessage.toString());
952 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
954 if (parentAdmin != null) {
955 out.startTag(null, TAG_PARENT_ADMIN);
956 parentAdmin.writeToXml(out);
957 out.endTag(null, TAG_PARENT_ADMIN);
959 if (organizationColor != DEF_ORGANIZATION_COLOR) {
960 out.startTag(null, TAG_ORGANIZATION_COLOR);
961 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
962 out.endTag(null, TAG_ORGANIZATION_COLOR);
964 if (organizationName != null) {
965 out.startTag(null, TAG_ORGANIZATION_NAME);
966 out.text(organizationName);
967 out.endTag(null, TAG_ORGANIZATION_NAME);
971 void writePackageListToXml(XmlSerializer out, String outerTag,
972 List<String> packageList)
973 throws IllegalArgumentException, IllegalStateException, IOException {
974 if (packageList == null) {
978 out.startTag(null, outerTag);
979 for (String packageName : packageList) {
980 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
981 out.attribute(null, ATTR_VALUE, packageName);
982 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
984 out.endTag(null, outerTag);
987 void readFromXml(XmlPullParser parser)
988 throws XmlPullParserException, IOException {
989 int outerDepth = parser.getDepth();
991 while ((type=parser.next()) != END_DOCUMENT
992 && (type != END_TAG || parser.getDepth() > outerDepth)) {
993 if (type == END_TAG || type == TEXT) {
996 String tag = parser.getName();
997 if (TAG_POLICIES.equals(tag)) {
998 info.readPoliciesFromXml(parser);
999 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
1000 passwordQuality = Integer.parseInt(
1001 parser.getAttributeValue(null, ATTR_VALUE));
1002 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
1003 minimumPasswordLength = Integer.parseInt(
1004 parser.getAttributeValue(null, ATTR_VALUE));
1005 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
1006 passwordHistoryLength = Integer.parseInt(
1007 parser.getAttributeValue(null, ATTR_VALUE));
1008 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
1009 minimumPasswordUpperCase = Integer.parseInt(
1010 parser.getAttributeValue(null, ATTR_VALUE));
1011 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
1012 minimumPasswordLowerCase = Integer.parseInt(
1013 parser.getAttributeValue(null, ATTR_VALUE));
1014 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
1015 minimumPasswordLetters = Integer.parseInt(
1016 parser.getAttributeValue(null, ATTR_VALUE));
1017 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
1018 minimumPasswordNumeric = Integer.parseInt(
1019 parser.getAttributeValue(null, ATTR_VALUE));
1020 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
1021 minimumPasswordSymbols = Integer.parseInt(
1022 parser.getAttributeValue(null, ATTR_VALUE));
1023 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
1024 minimumPasswordNonLetter = Integer.parseInt(
1025 parser.getAttributeValue(null, ATTR_VALUE));
1026 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
1027 maximumTimeToUnlock = Long.parseLong(
1028 parser.getAttributeValue(null, ATTR_VALUE));
1029 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
1030 strongAuthUnlockTimeout = Long.parseLong(
1031 parser.getAttributeValue(null, ATTR_VALUE));
1032 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
1033 maximumFailedPasswordsForWipe = Integer.parseInt(
1034 parser.getAttributeValue(null, ATTR_VALUE));
1035 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
1036 specifiesGlobalProxy = Boolean.parseBoolean(
1037 parser.getAttributeValue(null, ATTR_VALUE));
1038 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1040 parser.getAttributeValue(null, ATTR_VALUE);
1041 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1042 globalProxyExclusionList =
1043 parser.getAttributeValue(null, ATTR_VALUE);
1044 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1045 passwordExpirationTimeout = Long.parseLong(
1046 parser.getAttributeValue(null, ATTR_VALUE));
1047 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1048 passwordExpirationDate = Long.parseLong(
1049 parser.getAttributeValue(null, ATTR_VALUE));
1050 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1051 encryptionRequested = Boolean.parseBoolean(
1052 parser.getAttributeValue(null, ATTR_VALUE));
1053 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1054 testOnlyAdmin = Boolean.parseBoolean(
1055 parser.getAttributeValue(null, ATTR_VALUE));
1056 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1057 disableCamera = Boolean.parseBoolean(
1058 parser.getAttributeValue(null, ATTR_VALUE));
1059 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1060 disableCallerId = Boolean.parseBoolean(
1061 parser.getAttributeValue(null, ATTR_VALUE));
1062 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1063 disableContactsSearch = Boolean.parseBoolean(
1064 parser.getAttributeValue(null, ATTR_VALUE));
1065 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1066 disableBluetoothContactSharing = Boolean.parseBoolean(parser
1067 .getAttributeValue(null, ATTR_VALUE));
1068 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1069 disableScreenCapture = Boolean.parseBoolean(
1070 parser.getAttributeValue(null, ATTR_VALUE));
1071 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1072 requireAutoTime = Boolean.parseBoolean(
1073 parser.getAttributeValue(null, ATTR_VALUE));
1074 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1075 forceEphemeralUsers = Boolean.parseBoolean(
1076 parser.getAttributeValue(null, ATTR_VALUE));
1077 } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) {
1078 isNetworkLoggingEnabled = Boolean.parseBoolean(
1079 parser.getAttributeValue(null, ATTR_VALUE));
1080 lastNetworkLoggingNotificationTimeMs = Long.parseLong(
1081 parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION));
1082 numNetworkLoggingNotifications = Integer.parseInt(
1083 parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS));
1084 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1085 disabledKeyguardFeatures = Integer.parseInt(
1086 parser.getAttributeValue(null, ATTR_VALUE));
1087 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1088 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
1089 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1090 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1091 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1092 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
1093 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1094 permittedAccessiblityServices = readPackageList(parser, tag);
1095 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1096 permittedInputMethods = readPackageList(parser, tag);
1097 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1098 keepUninstalledPackages = readPackageList(parser, tag);
1099 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1100 UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
1101 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1102 type = parser.next();
1103 if (type == XmlPullParser.TEXT) {
1104 shortSupportMessage = parser.getText();
1106 Log.w(LOG_TAG, "Missing text when loading short support message");
1108 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1109 type = parser.next();
1110 if (type == XmlPullParser.TEXT) {
1111 longSupportMessage = parser.getText();
1113 Log.w(LOG_TAG, "Missing text when loading long support message");
1115 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1116 Preconditions.checkState(!isParent);
1118 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1119 parentAdmin.readFromXml(parser);
1120 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1121 organizationColor = Integer.parseInt(
1122 parser.getAttributeValue(null, ATTR_VALUE));
1123 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1124 type = parser.next();
1125 if (type == XmlPullParser.TEXT) {
1126 organizationName = parser.getText();
1128 Log.w(LOG_TAG, "Missing text when loading organization name");
1131 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1132 XmlUtils.skipCurrentTag(parser);
1137 private List<String> readPackageList(XmlPullParser parser,
1138 String tag) throws XmlPullParserException, IOException {
1139 List<String> result = new ArrayList<String>();
1140 int outerDepth = parser.getDepth();
1142 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1143 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1144 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1147 String outerTag = parser.getName();
1148 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1149 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1150 if (packageName != null) {
1151 result.add(packageName);
1153 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1156 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
1162 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1163 throws XmlPullParserException, IOException {
1164 int outerDepthDAM = parser.getDepth();
1166 Set<String> result = new ArraySet<>();
1167 while ((typeDAM=parser.next()) != END_DOCUMENT
1168 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1169 if (typeDAM == END_TAG || typeDAM == TEXT) {
1172 String tagDAM = parser.getName();
1173 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1174 result.add(parser.getAttributeValue(null, ATTR_VALUE));
1176 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1182 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1183 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1184 int outerDepthDAM = parser.getDepth();
1186 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1187 while ((typeDAM=parser.next()) != END_DOCUMENT
1188 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1189 if (typeDAM == END_TAG || typeDAM == TEXT) {
1192 String tagDAM = parser.getName();
1193 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1194 final String component = parser.getAttributeValue(null, ATTR_VALUE);
1195 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1196 result.put(component, trustAgentInfo);
1198 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1204 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1205 throws XmlPullParserException, IOException {
1206 int outerDepthDAM = parser.getDepth();
1208 TrustAgentInfo result = new TrustAgentInfo(null);
1209 while ((typeDAM=parser.next()) != END_DOCUMENT
1210 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1211 if (typeDAM == END_TAG || typeDAM == TEXT) {
1214 String tagDAM = parser.getName();
1215 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1216 result.options = PersistableBundle.restoreFromXml(parser);
1218 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1224 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1225 throws XmlPullParserException, IOException {
1226 int outerDepthDAM = parser.getDepth();
1228 ArrayList<String> result = null;
1229 while ((typeDAM=parser.next()) != END_DOCUMENT
1230 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1231 if (typeDAM == END_TAG || typeDAM == TEXT) {
1234 String tagDAM = parser.getName();
1235 if (TAG_PROVIDER.equals(tagDAM)) {
1236 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1237 if (result == null) {
1238 result = new ArrayList<>();
1240 result.add(provider);
1242 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
1248 boolean hasUserRestrictions() {
1249 return userRestrictions != null && userRestrictions.size() > 0;
1252 Bundle ensureUserRestrictions() {
1253 if (userRestrictions == null) {
1254 userRestrictions = new Bundle();
1256 return userRestrictions;
1259 void dump(String prefix, PrintWriter pw) {
1260 pw.print(prefix); pw.print("uid="); pw.println(getUid());
1261 pw.print(prefix); pw.print("testOnlyAdmin=");
1262 pw.println(testOnlyAdmin);
1263 pw.print(prefix); pw.println("policies:");
1264 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1266 for (int i=0; i<pols.size(); i++) {
1267 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
1270 pw.print(prefix); pw.print("passwordQuality=0x");
1271 pw.println(Integer.toHexString(passwordQuality));
1272 pw.print(prefix); pw.print("minimumPasswordLength=");
1273 pw.println(minimumPasswordLength);
1274 pw.print(prefix); pw.print("passwordHistoryLength=");
1275 pw.println(passwordHistoryLength);
1276 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1277 pw.println(minimumPasswordUpperCase);
1278 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1279 pw.println(minimumPasswordLowerCase);
1280 pw.print(prefix); pw.print("minimumPasswordLetters=");
1281 pw.println(minimumPasswordLetters);
1282 pw.print(prefix); pw.print("minimumPasswordNumeric=");
1283 pw.println(minimumPasswordNumeric);
1284 pw.print(prefix); pw.print("minimumPasswordSymbols=");
1285 pw.println(minimumPasswordSymbols);
1286 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1287 pw.println(minimumPasswordNonLetter);
1288 pw.print(prefix); pw.print("maximumTimeToUnlock=");
1289 pw.println(maximumTimeToUnlock);
1290 pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1291 pw.println(strongAuthUnlockTimeout);
1292 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1293 pw.println(maximumFailedPasswordsForWipe);
1294 pw.print(prefix); pw.print("specifiesGlobalProxy=");
1295 pw.println(specifiesGlobalProxy);
1296 pw.print(prefix); pw.print("passwordExpirationTimeout=");
1297 pw.println(passwordExpirationTimeout);
1298 pw.print(prefix); pw.print("passwordExpirationDate=");
1299 pw.println(passwordExpirationDate);
1300 if (globalProxySpec != null) {
1301 pw.print(prefix); pw.print("globalProxySpec=");
1302 pw.println(globalProxySpec);
1304 if (globalProxyExclusionList != null) {
1305 pw.print(prefix); pw.print("globalProxyEclusionList=");
1306 pw.println(globalProxyExclusionList);
1308 pw.print(prefix); pw.print("encryptionRequested=");
1309 pw.println(encryptionRequested);
1310 pw.print(prefix); pw.print("disableCamera=");
1311 pw.println(disableCamera);
1312 pw.print(prefix); pw.print("disableCallerId=");
1313 pw.println(disableCallerId);
1314 pw.print(prefix); pw.print("disableContactsSearch=");
1315 pw.println(disableContactsSearch);
1316 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1317 pw.println(disableBluetoothContactSharing);
1318 pw.print(prefix); pw.print("disableScreenCapture=");
1319 pw.println(disableScreenCapture);
1320 pw.print(prefix); pw.print("requireAutoTime=");
1321 pw.println(requireAutoTime);
1322 pw.print(prefix); pw.print("forceEphemeralUsers=");
1323 pw.println(forceEphemeralUsers);
1324 pw.print(prefix); pw.print("isNetworkLoggingEnabled=");
1325 pw.println(isNetworkLoggingEnabled);
1326 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1327 pw.println(disabledKeyguardFeatures);
1328 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1329 pw.println(crossProfileWidgetProviders);
1330 if (permittedAccessiblityServices != null) {
1331 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1332 pw.println(permittedAccessiblityServices);
1334 if (permittedInputMethods != null) {
1335 pw.print(prefix); pw.print("permittedInputMethods=");
1336 pw.println(permittedInputMethods);
1338 if (keepUninstalledPackages != null) {
1339 pw.print(prefix); pw.print("keepUninstalledPackages=");
1340 pw.println(keepUninstalledPackages);
1342 pw.print(prefix); pw.print("organizationColor=");
1343 pw.println(organizationColor);
1344 if (organizationName != null) {
1345 pw.print(prefix); pw.print("organizationName=");
1346 pw.println(organizationName);
1348 pw.print(prefix); pw.println("userRestrictions:");
1349 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions);
1350 pw.print(prefix); pw.print("isParent=");
1351 pw.println(isParent);
1352 if (parentAdmin != null) {
1353 pw.print(prefix); pw.println("parentAdmin:");
1354 parentAdmin.dump(prefix + " ", pw);
1359 private void handlePackagesChanged(String packageName, int userHandle) {
1360 boolean removed = false;
1361 if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1362 DevicePolicyData policy = getUserData(userHandle);
1363 synchronized (this) {
1364 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1365 ActiveAdmin aa = policy.mAdminList.get(i);
1367 // If we're checking all packages or if the specific one we're checking matches,
1368 // then check if the package and receiver still exist.
1369 final String adminPackage = aa.info.getPackageName();
1370 if (packageName == null || packageName.equals(adminPackage)) {
1371 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1372 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1373 PackageManager.MATCH_DIRECT_BOOT_AWARE
1374 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1375 userHandle) == null) {
1377 policy.mAdminList.remove(i);
1378 policy.mAdminMap.remove(aa.info.getComponent());
1381 } catch (RemoteException re) {
1386 validatePasswordOwnerLocked(policy);
1387 saveSettingsLocked(policy.mUserHandle);
1390 // Check if delegated cert installer or app restrictions managing packages are removed.
1391 if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1392 policy.mDelegatedCertInstallerPackage = null;
1393 saveSettingsLocked(policy.mUserHandle);
1395 if (isRemovedPackage(
1396 packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1397 policy.mApplicationRestrictionsManagingPackage = null;
1398 saveSettingsLocked(policy.mUserHandle);
1402 // The removed admin might have disabled camera, so update user restrictions.
1403 pushUserRestrictions(userHandle);
1407 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1409 return targetPackage != null
1410 && (changedPackage == null || changedPackage.equals(targetPackage))
1411 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1412 } catch (RemoteException e) {
1420 * Unit test will subclass it to inject mocks.
1423 static class Injector {
1425 private final Context mContext;
1427 Injector(Context context) {
1431 Owners newOwners() {
1432 return new Owners(getUserManager(), getUserManagerInternal(),
1433 getPackageManagerInternal());
1436 UserManager getUserManager() {
1437 return UserManager.get(mContext);
1440 UserManagerInternal getUserManagerInternal() {
1441 return LocalServices.getService(UserManagerInternal.class);
1444 PackageManagerInternal getPackageManagerInternal() {
1445 return LocalServices.getService(PackageManagerInternal.class);
1448 NotificationManager getNotificationManager() {
1449 return mContext.getSystemService(NotificationManager.class);
1452 IIpConnectivityMetrics getIIpConnectivityMetrics() {
1453 return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1454 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1457 PowerManagerInternal getPowerManagerInternal() {
1458 return LocalServices.getService(PowerManagerInternal.class);
1461 TelephonyManager getTelephonyManager() {
1462 return TelephonyManager.from(mContext);
1465 TrustManager getTrustManager() {
1466 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1469 AlarmManager getAlarmManager() {
1470 return (AlarmManager) mContext.getSystemService(AlarmManager.class);
1473 IWindowManager getIWindowManager() {
1474 return IWindowManager.Stub
1475 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1478 IActivityManager getIActivityManager() {
1479 return ActivityManagerNative.getDefault();
1482 IPackageManager getIPackageManager() {
1483 return AppGlobals.getPackageManager();
1486 IBackupManager getIBackupManager() {
1487 return IBackupManager.Stub.asInterface(
1488 ServiceManager.getService(Context.BACKUP_SERVICE));
1491 IAudioService getIAudioService() {
1492 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1495 LockPatternUtils newLockPatternUtils() {
1496 return new LockPatternUtils(mContext);
1499 boolean storageManagerIsFileBasedEncryptionEnabled() {
1500 return StorageManager.isFileEncryptedNativeOnly();
1503 boolean storageManagerIsNonDefaultBlockEncrypted() {
1504 long identity = Binder.clearCallingIdentity();
1506 return StorageManager.isNonDefaultBlockEncrypted();
1508 Binder.restoreCallingIdentity(identity);
1512 boolean storageManagerIsEncrypted() {
1513 return StorageManager.isEncrypted();
1516 boolean storageManagerIsEncryptable() {
1517 return StorageManager.isEncryptable();
1520 Looper getMyLooper() {
1521 return Looper.myLooper();
1524 WifiManager getWifiManager() {
1525 return mContext.getSystemService(WifiManager.class);
1528 long binderClearCallingIdentity() {
1529 return Binder.clearCallingIdentity();
1532 void binderRestoreCallingIdentity(long token) {
1533 Binder.restoreCallingIdentity(token);
1536 int binderGetCallingUid() {
1537 return Binder.getCallingUid();
1540 int binderGetCallingPid() {
1541 return Binder.getCallingPid();
1544 UserHandle binderGetCallingUserHandle() {
1545 return Binder.getCallingUserHandle();
1548 boolean binderIsCallingUidMyUid() {
1549 return getCallingUid() == Process.myUid();
1552 final int userHandleGetCallingUserId() {
1553 return UserHandle.getUserId(binderGetCallingUid());
1556 File environmentGetUserSystemDirectory(int userId) {
1557 return Environment.getUserSystemDirectory(userId);
1560 void powerManagerGoToSleep(long time, int reason, int flags) {
1561 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1564 void powerManagerReboot(String reason) {
1565 mContext.getSystemService(PowerManager.class).reboot(reason);
1568 boolean systemPropertiesGetBoolean(String key, boolean def) {
1569 return SystemProperties.getBoolean(key, def);
1572 long systemPropertiesGetLong(String key, long def) {
1573 return SystemProperties.getLong(key, def);
1576 String systemPropertiesGet(String key, String def) {
1577 return SystemProperties.get(key, def);
1580 String systemPropertiesGet(String key) {
1581 return SystemProperties.get(key);
1584 void systemPropertiesSet(String key, String value) {
1585 SystemProperties.set(key, value);
1588 boolean userManagerIsSplitSystemUser() {
1589 return UserManager.isSplitSystemUser();
1592 String getDevicePolicyFilePathForSystemUser() {
1593 return "/data/system/";
1596 void registerContentObserver(Uri uri, boolean notifyForDescendents,
1597 ContentObserver observer, int userHandle) {
1598 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1599 observer, userHandle);
1602 int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1603 return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1604 name, def, userHandle);
1607 void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1608 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1609 name, value, userHandle);
1612 void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1613 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1614 name, value, userHandle);
1617 void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1618 Settings.Global.putStringForUser(mContext.getContentResolver(),
1619 name, value, userHandle);
1622 void settingsSecurePutInt(String name, int value) {
1623 Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1626 int settingsGlobalGetInt(String name, int def) {
1627 return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1630 void settingsGlobalPutInt(String name, int value) {
1631 Settings.Global.putInt(mContext.getContentResolver(), name, value);
1634 void settingsSecurePutString(String name, String value) {
1635 Settings.Secure.putString(mContext.getContentResolver(), name, value);
1638 void settingsGlobalPutString(String name, String value) {
1639 Settings.Global.putString(mContext.getContentResolver(), name, value);
1642 void securityLogSetLoggingEnabledProperty(boolean enabled) {
1643 SecurityLog.setLoggingEnabledProperty(enabled);
1646 boolean securityLogGetLoggingEnabledProperty() {
1647 return SecurityLog.getLoggingEnabledProperty();
1650 boolean securityLogIsLoggingEnabled() {
1651 return SecurityLog.isLoggingEnabled();
1656 * Instantiates the service.
1658 public DevicePolicyManagerService(Context context) {
1659 this(new Injector(context));
1663 DevicePolicyManagerService(Injector injector) {
1664 mInjector = injector;
1665 mContext = Preconditions.checkNotNull(injector.mContext);
1666 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1667 mOwners = Preconditions.checkNotNull(injector.newOwners());
1669 mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1670 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1671 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1672 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1674 mLocalService = new LocalService();
1675 mLockPatternUtils = injector.newLockPatternUtils();
1677 mSecurityLogMonitor = new SecurityLogMonitor(this);
1679 mHasFeature = mContext.getPackageManager()
1680 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1681 mIsWatch = mContext.getPackageManager()
1682 .hasSystemFeature(PackageManager.FEATURE_WATCH);
1684 // Skip the rest of the initialization
1687 IntentFilter filter = new IntentFilter();
1688 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1689 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1690 filter.addAction(Intent.ACTION_USER_ADDED);
1691 filter.addAction(Intent.ACTION_USER_REMOVED);
1692 filter.addAction(Intent.ACTION_USER_STARTED);
1693 filter.addAction(Intent.ACTION_USER_UNLOCKED);
1694 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1695 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1696 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1697 filter = new IntentFilter();
1698 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1699 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1700 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1701 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1702 filter.addDataScheme("package");
1703 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1704 filter = new IntentFilter();
1705 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1706 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1708 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1712 * Creates and loads the policy data from xml.
1713 * @param userHandle the user for whom to load the policy data
1717 DevicePolicyData getUserData(int userHandle) {
1718 synchronized (this) {
1719 DevicePolicyData policy = mUserData.get(userHandle);
1720 if (policy == null) {
1721 policy = new DevicePolicyData(userHandle);
1722 mUserData.append(userHandle, policy);
1723 loadSettingsLocked(policy, userHandle);
1730 * Creates and loads the policy data from xml for data that is shared between
1731 * various profiles of a user. In contrast to {@link #getUserData(int)}
1732 * it allows access to data of users other than the calling user.
1734 * This function should only be used for shared data, e.g. everything regarding
1735 * passwords and should be removed once multiple screen locks are present.
1736 * @param userHandle the user for whom to load the policy data
1739 DevicePolicyData getUserDataUnchecked(int userHandle) {
1740 long ident = mInjector.binderClearCallingIdentity();
1742 return getUserData(userHandle);
1744 mInjector.binderRestoreCallingIdentity(ident);
1748 void removeUserData(int userHandle) {
1749 synchronized (this) {
1750 if (userHandle == UserHandle.USER_SYSTEM) {
1751 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1754 mOwners.removeProfileOwner(userHandle);
1755 mOwners.writeProfileOwner(userHandle);
1757 DevicePolicyData policy = mUserData.get(userHandle);
1758 if (policy != null) {
1759 mUserData.remove(userHandle);
1761 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1762 DEVICE_POLICIES_XML);
1763 policyFile.delete();
1764 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1766 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1770 synchronized (this) {
1772 setDeviceOwnerSystemPropertyLocked();
1773 findOwnerComponentIfNecessaryLocked();
1774 migrateUserRestrictionsIfNecessaryLocked();
1776 // TODO PO may not have a class name either due to b/17652534. Address that too.
1778 updateDeviceOwnerLocked();
1782 private void setDeviceOwnerSystemPropertyLocked() {
1783 // Device owner may still be provisioned, do not set the read-only system property yet.
1784 // Wear devices don't set device_provisioned until the device is paired, so allow
1785 // device_owner property to be set without that.
1787 && mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1790 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1791 // always false at this point.
1792 if (StorageManager.inCryptKeeperBounce()) {
1796 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1797 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1799 if (mOwners.hasDeviceOwner()) {
1800 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1801 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1802 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
1803 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1804 mSecurityLogMonitor.start();
1807 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1808 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1813 private void findOwnerComponentIfNecessaryLocked() {
1814 if (!mOwners.hasDeviceOwner()) {
1817 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1819 if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1820 return; // Already a full component name.
1823 final ComponentName doComponent = findAdminComponentWithPackageLocked(
1824 doComponentName.getPackageName(),
1825 mOwners.getDeviceOwnerUserId());
1826 if (doComponent == null) {
1827 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1829 mOwners.setDeviceOwnerWithRestrictionsMigrated(
1831 mOwners.getDeviceOwnerName(),
1832 mOwners.getDeviceOwnerUserId(),
1833 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1834 mOwners.writeDeviceOwner();
1836 Log.v(LOG_TAG, "Device owner component filled in");
1842 * We didn't use to persist user restrictions for each owners but only persisted in user
1845 private void migrateUserRestrictionsIfNecessaryLocked() {
1846 boolean migrated = false;
1847 // Migrate for the DO. Basically all restrictions should be considered to be set by DO,
1848 // except for the "system controlled" ones.
1849 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1851 Log.v(LOG_TAG, "Migrating DO user restrictions");
1855 // Migrate user 0 restrictions to DO.
1856 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1858 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1859 /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1861 // Push DO user restrictions to user manager.
1862 pushUserRestrictions(UserHandle.USER_SYSTEM);
1864 mOwners.setDeviceOwnerUserRestrictionsMigrated();
1869 // The following restrictions can be set on secondary users by the device owner, so we
1870 // assume they're not from the PO.
1871 final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1872 UserManager.DISALLOW_OUTGOING_CALLS,
1873 UserManager.DISALLOW_SMS);
1875 for (UserInfo ui : mUserManager.getUsers()) {
1876 final int userId = ui.id;
1877 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1879 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1883 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1885 final Set<String> exceptionList =
1886 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1888 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1889 exceptionList, /* isDeviceOwner =*/ false);
1891 // Note if a secondary user has no PO but has a DA that disables camera, we
1892 // don't get here and won't push the camera user restriction to UserManager
1893 // here. That's okay because we'll push user restrictions anyway when a user
1894 // starts. But we still do it because we want to let user manager persist
1896 pushUserRestrictions(userId);
1898 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1901 if (VERBOSE_LOG && migrated) {
1902 Log.v(LOG_TAG, "User restrictions migrated.");
1906 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1907 Set<String> exceptionList, boolean isDeviceOwner) {
1908 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1909 user.getIdentifier());
1911 final Bundle newBaseRestrictions = new Bundle();
1912 final Bundle newOwnerRestrictions = new Bundle();
1914 for (String key : origRestrictions.keySet()) {
1915 if (!origRestrictions.getBoolean(key)) {
1918 final boolean canOwnerChange = isDeviceOwner
1919 ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1920 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1922 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1923 newBaseRestrictions.putBoolean(key, true);
1925 newOwnerRestrictions.putBoolean(key, true);
1930 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1931 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1932 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1934 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1935 newBaseRestrictions);
1937 if (admin != null) {
1938 admin.ensureUserRestrictions().clear();
1939 admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1941 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1943 saveSettingsLocked(user.getIdentifier());
1946 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1947 final DevicePolicyData policy = getUserData(userId);
1948 final int n = policy.mAdminList.size();
1949 ComponentName found = null;
1951 for (int i = 0; i < n; i++) {
1952 final ActiveAdmin admin = policy.mAdminList.get(i);
1953 if (packageName.equals(admin.info.getPackageName())) {
1956 found = admin.info.getComponent();
1962 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1968 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1969 * reminders. Clears alarm if no expirations are configured.
1971 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1972 final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1973 final long now = System.currentTimeMillis();
1974 final long timeToExpire = expiration - now;
1975 final long alarmTime;
1976 if (expiration == 0) {
1977 // No expirations are currently configured: Cancel alarm.
1979 } else if (timeToExpire <= 0) {
1980 // The password has already expired: Repeat every 24 hours.
1981 alarmTime = now + MS_PER_DAY;
1983 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1984 // the expiration time.
1985 long alarmInterval = timeToExpire % MS_PER_DAY;
1986 if (alarmInterval == 0) {
1987 alarmInterval = MS_PER_DAY;
1989 alarmTime = now + alarmInterval;
1992 long token = mInjector.binderClearCallingIdentity();
1994 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1995 AlarmManager am = mInjector.getAlarmManager();
1996 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1997 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1998 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1999 UserHandle.of(affectedUserHandle));
2001 if (alarmTime != 0) {
2002 am.set(AlarmManager.RTC, alarmTime, pi);
2005 mInjector.binderRestoreCallingIdentity(token);
2009 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2010 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2012 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2013 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2019 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2021 enforceManagedProfile(userHandle, "call APIs on the parent profile");
2023 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2024 if (admin != null && parent) {
2025 admin = admin.getParentActiveAdmin();
2030 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2031 throws SecurityException {
2032 final int callingUid = mInjector.binderGetCallingUid();
2034 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
2035 if (result != null) {
2040 final int userId = UserHandle.getUserId(callingUid);
2041 final DevicePolicyData policy = getUserData(userId);
2042 ActiveAdmin admin = policy.mAdminMap.get(who);
2043 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2044 throw new SecurityException("Admin " + admin.info.getComponent()
2045 + " does not own the device");
2047 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2048 throw new SecurityException("Admin " + admin.info.getComponent()
2049 + " does not own the profile");
2051 throw new SecurityException("Admin " + admin.info.getComponent()
2052 + " did not specify uses-policy for: "
2053 + admin.info.getTagForPolicy(reqPolicy));
2055 throw new SecurityException("No active admin owned by uid "
2056 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
2060 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2061 throws SecurityException {
2063 enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2064 "call APIs on the parent profile");
2066 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2067 return parent ? admin.getParentActiveAdmin() : admin;
2070 * Find the admin for the component and userId bit of the uid, then check
2071 * the admin's uid matches the uid.
2073 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2074 final int userId = UserHandle.getUserId(uid);
2075 final DevicePolicyData policy = getUserData(userId);
2076 ActiveAdmin admin = policy.mAdminMap.get(who);
2077 if (admin == null) {
2078 throw new SecurityException("No active admin " + who);
2080 if (admin.getUid() != uid) {
2081 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2086 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2088 // Try to find an admin which can use reqPolicy
2089 final int userId = UserHandle.getUserId(uid);
2090 final DevicePolicyData policy = getUserData(userId);
2092 ActiveAdmin admin = policy.mAdminMap.get(who);
2093 if (admin == null) {
2094 throw new SecurityException("No active admin " + who);
2096 if (admin.getUid() != uid) {
2097 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2099 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2103 for (ActiveAdmin admin : policy.mAdminList) {
2104 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2115 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2117 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2118 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2120 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2122 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2123 // DO always has the PO power.
2124 return ownsDevice || ownsProfile;
2126 return admin.info.usesPolicy(reqPolicy);
2130 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2131 sendAdminCommandLocked(admin, action, null);
2134 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2135 sendAdminCommandLocked(admin, action, null, result);
2139 * Send an update to one specific admin, get notified when that admin returns a result.
2141 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2142 BroadcastReceiver result) {
2143 Intent intent = new Intent(action);
2144 intent.setComponent(admin.info.getComponent());
2145 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2146 intent.putExtra("expiration", admin.passwordExpirationDate);
2148 if (adminExtras != null) {
2149 intent.putExtras(adminExtras);
2151 if (result != null) {
2152 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2153 null, result, mHandler, Activity.RESULT_OK, null, null);
2155 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2160 * Send an update to all admins of a user that enforce a specified policy.
2162 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2163 final DevicePolicyData policy = getUserData(userHandle);
2164 final int count = policy.mAdminList.size();
2166 for (int i = 0; i < count; i++) {
2167 final ActiveAdmin admin = policy.mAdminList.get(i);
2168 if (admin.info.usesPolicy(reqPolicy)) {
2169 sendAdminCommandLocked(admin, action);
2176 * Send an update intent to all admins of a user and its profiles. Only send to admins that
2177 * enforce a specified policy.
2179 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2181 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2182 for (int profileId : profileIds) {
2183 sendAdminCommandLocked(action, reqPolicy, profileId);
2188 * Sends a broadcast to each profile that share the password unlock with the given user id.
2190 private void sendAdminCommandForLockscreenPoliciesLocked(
2191 String action, int reqPolicy, int userHandle) {
2192 if (isSeparateProfileChallengeEnabled(userHandle)) {
2193 sendAdminCommandLocked(action, reqPolicy, userHandle);
2195 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2199 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2200 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2201 DevicePolicyData policy = getUserData(userHandle);
2202 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2203 policy.mRemovingAdmins.add(adminReceiver);
2204 sendAdminCommandLocked(admin,
2205 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2206 new BroadcastReceiver() {
2208 public void onReceive(Context context, Intent intent) {
2209 removeAdminArtifacts(adminReceiver, userHandle);
2210 removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2217 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2218 boolean throwForMissiongPermission) {
2222 enforceFullCrossUsersPermission(userHandle);
2223 ActivityInfo ai = null;
2225 ai = mIPackageManager.getReceiverInfo(adminName,
2226 PackageManager.GET_META_DATA |
2227 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2228 PackageManager.MATCH_DIRECT_BOOT_AWARE |
2229 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2230 } catch (RemoteException e) {
2231 // shouldn't happen.
2234 throw new IllegalArgumentException("Unknown admin: " + adminName);
2237 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2238 final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2239 + permission.BIND_DEVICE_ADMIN;
2240 Slog.w(LOG_TAG, message);
2241 if (throwForMissiongPermission &&
2242 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2243 throw new IllegalArgumentException(message);
2248 return new DeviceAdminInfo(mContext, ai);
2249 } catch (XmlPullParserException | IOException e) {
2250 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2256 private JournaledFile makeJournaledFile(int userHandle) {
2257 final String base = userHandle == UserHandle.USER_SYSTEM
2258 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2259 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2260 DEVICE_POLICIES_XML).getAbsolutePath();
2262 Log.v(LOG_TAG, "Opening " + base);
2264 return new JournaledFile(new File(base), new File(base + ".tmp"));
2267 private void saveSettingsLocked(int userHandle) {
2268 DevicePolicyData policy = getUserData(userHandle);
2269 JournaledFile journal = makeJournaledFile(userHandle);
2270 FileOutputStream stream = null;
2272 stream = new FileOutputStream(journal.chooseForWrite(), false);
2273 XmlSerializer out = new FastXmlSerializer();
2274 out.setOutput(stream, StandardCharsets.UTF_8.name());
2275 out.startDocument(null, true);
2277 out.startTag(null, "policies");
2278 if (policy.mRestrictionsProvider != null) {
2279 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2280 policy.mRestrictionsProvider.flattenToString());
2282 if (policy.mUserSetupComplete) {
2283 out.attribute(null, ATTR_SETUP_COMPLETE,
2284 Boolean.toString(true));
2286 if (policy.mPaired) {
2287 out.attribute(null, ATTR_DEVICE_PAIRED,
2288 Boolean.toString(true));
2290 if (policy.mDeviceProvisioningConfigApplied) {
2291 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2292 Boolean.toString(true));
2294 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2295 out.attribute(null, ATTR_PROVISIONING_STATE,
2296 Integer.toString(policy.mUserProvisioningState));
2298 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2299 out.attribute(null, ATTR_PERMISSION_POLICY,
2300 Integer.toString(policy.mPermissionPolicy));
2302 if (policy.mDelegatedCertInstallerPackage != null) {
2303 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2304 policy.mDelegatedCertInstallerPackage);
2306 if (policy.mApplicationRestrictionsManagingPackage != null) {
2307 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2308 policy.mApplicationRestrictionsManagingPackage);
2311 final int N = policy.mAdminList.size();
2312 for (int i=0; i<N; i++) {
2313 ActiveAdmin ap = policy.mAdminList.get(i);
2315 out.startTag(null, "admin");
2316 out.attribute(null, "name", ap.info.getComponent().flattenToString());
2318 out.endTag(null, "admin");
2322 if (policy.mPasswordOwner >= 0) {
2323 out.startTag(null, "password-owner");
2324 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2325 out.endTag(null, "password-owner");
2328 if (policy.mFailedPasswordAttempts != 0) {
2329 out.startTag(null, "failed-password-attempts");
2330 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2331 out.endTag(null, "failed-password-attempts");
2334 // Don't save metrics for FBE devices
2335 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
2336 && (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2337 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2338 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2339 || policy.mActivePasswordSymbols != 0
2340 || policy.mActivePasswordNonLetter != 0)) {
2341 out.startTag(null, "active-password");
2342 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2343 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2344 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2345 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2346 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2347 out.attribute(null, "numeric", Integer
2348 .toString(policy.mActivePasswordNumeric));
2349 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2350 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2351 out.endTag(null, "active-password");
2354 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2355 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2356 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2357 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2360 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2361 String component = policy.mLockTaskPackages.get(i);
2362 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2363 out.attribute(null, "name", component);
2364 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2367 if (policy.mStatusBarDisabled) {
2368 out.startTag(null, TAG_STATUS_BAR);
2369 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2370 out.endTag(null, TAG_STATUS_BAR);
2373 if (policy.doNotAskCredentialsOnBoot) {
2374 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2375 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2378 for (String id : policy.mAffiliationIds) {
2379 out.startTag(null, TAG_AFFILIATION_ID);
2380 out.attribute(null, "id", id);
2381 out.endTag(null, TAG_AFFILIATION_ID);
2384 if (policy.mAdminBroadcastPending) {
2385 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2386 out.attribute(null, ATTR_VALUE,
2387 Boolean.toString(policy.mAdminBroadcastPending));
2388 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2391 if (policy.mInitBundle != null) {
2392 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2393 policy.mInitBundle.saveToXml(out);
2394 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2397 out.endTag(null, "policies");
2401 FileUtils.sync(stream);
2404 sendChangedNotification(userHandle);
2405 } catch (XmlPullParserException | IOException e) {
2406 Slog.w(LOG_TAG, "failed writing file", e);
2408 if (stream != null) {
2411 } catch (IOException ex) {
2418 private void sendChangedNotification(int userHandle) {
2419 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2420 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2421 long ident = mInjector.binderClearCallingIdentity();
2423 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2425 mInjector.binderRestoreCallingIdentity(ident);
2429 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2430 JournaledFile journal = makeJournaledFile(userHandle);
2431 FileInputStream stream = null;
2432 File file = journal.chooseForRead();
2433 boolean needsRewrite = false;
2435 stream = new FileInputStream(file);
2436 XmlPullParser parser = Xml.newPullParser();
2437 parser.setInput(stream, StandardCharsets.UTF_8.name());
2440 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2441 && type != XmlPullParser.START_TAG) {
2443 String tag = parser.getName();
2444 if (!"policies".equals(tag)) {
2445 throw new XmlPullParserException(
2446 "Settings do not start with policies tag: found " + tag);
2449 // Extract the permission provider component name if available
2450 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2451 if (permissionProvider != null) {
2452 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2454 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2455 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2456 policy.mUserSetupComplete = true;
2458 String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
2459 if (paired != null && Boolean.toString(true).equals(paired)) {
2460 policy.mPaired = true;
2462 String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2463 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2464 if (deviceProvisioningConfigApplied != null
2465 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2466 policy.mDeviceProvisioningConfigApplied = true;
2468 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2469 if (!TextUtils.isEmpty(provisioningState)) {
2470 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2472 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2473 if (!TextUtils.isEmpty(permissionPolicy)) {
2474 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2476 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2477 ATTR_DELEGATED_CERT_INSTALLER);
2478 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2479 ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2481 type = parser.next();
2482 int outerDepth = parser.getDepth();
2483 policy.mLockTaskPackages.clear();
2484 policy.mAdminList.clear();
2485 policy.mAdminMap.clear();
2486 policy.mAffiliationIds.clear();
2487 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2488 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2489 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2492 tag = parser.getName();
2493 if ("admin".equals(tag)) {
2494 String name = parser.getAttributeValue(null, "name");
2496 DeviceAdminInfo dai = findAdmin(
2497 ComponentName.unflattenFromString(name), userHandle,
2498 /* throwForMissionPermission= */ false);
2500 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2502 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2503 + dai.getActivityInfo().applicationInfo.uid + " for user "
2507 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2508 ap.readFromXml(parser);
2509 policy.mAdminMap.put(ap.info.getComponent(), ap);
2511 } catch (RuntimeException e) {
2512 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2514 } else if ("failed-password-attempts".equals(tag)) {
2515 policy.mFailedPasswordAttempts = Integer.parseInt(
2516 parser.getAttributeValue(null, "value"));
2517 } else if ("password-owner".equals(tag)) {
2518 policy.mPasswordOwner = Integer.parseInt(
2519 parser.getAttributeValue(null, "value"));
2520 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2521 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2522 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2523 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2524 } else if (TAG_STATUS_BAR.equals(tag)) {
2525 policy.mStatusBarDisabled = Boolean.parseBoolean(
2526 parser.getAttributeValue(null, ATTR_DISABLED));
2527 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2528 policy.doNotAskCredentialsOnBoot = true;
2529 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2530 policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2531 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2532 String pending = parser.getAttributeValue(null, ATTR_VALUE);
2533 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2534 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2535 policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2536 } else if ("active-password".equals(tag)) {
2537 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2538 // Remove this from FBE devices
2539 needsRewrite = true;
2541 policy.mActivePasswordQuality = Integer.parseInt(
2542 parser.getAttributeValue(null, "quality"));
2543 policy.mActivePasswordLength = Integer.parseInt(
2544 parser.getAttributeValue(null, "length"));
2545 policy.mActivePasswordUpperCase = Integer.parseInt(
2546 parser.getAttributeValue(null, "uppercase"));
2547 policy.mActivePasswordLowerCase = Integer.parseInt(
2548 parser.getAttributeValue(null, "lowercase"));
2549 policy.mActivePasswordLetters = Integer.parseInt(
2550 parser.getAttributeValue(null, "letters"));
2551 policy.mActivePasswordNumeric = Integer.parseInt(
2552 parser.getAttributeValue(null, "numeric"));
2553 policy.mActivePasswordSymbols = Integer.parseInt(
2554 parser.getAttributeValue(null, "symbols"));
2555 policy.mActivePasswordNonLetter = Integer.parseInt(
2556 parser.getAttributeValue(null, "nonletter"));
2559 Slog.w(LOG_TAG, "Unknown tag: " + tag);
2560 XmlUtils.skipCurrentTag(parser);
2563 } catch (FileNotFoundException e) {
2564 // Don't be noisy, this is normal if we haven't defined any policies.
2565 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2566 | IndexOutOfBoundsException e) {
2567 Slog.w(LOG_TAG, "failed parsing " + file, e);
2570 if (stream != null) {
2573 } catch (IOException e) {
2577 // Generate a list of admins from the admin map
2578 policy.mAdminList.addAll(policy.mAdminMap.values());
2580 // Might need to upgrade the file by rewriting it
2582 saveSettingsLocked(userHandle);
2585 validatePasswordOwnerLocked(policy);
2586 updateMaximumTimeToLockLocked(userHandle);
2587 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2588 if (policy.mStatusBarDisabled) {
2589 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2593 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2594 long ident = mInjector.binderClearCallingIdentity();
2596 mInjector.getIActivityManager()
2597 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2598 } catch (RemoteException e) {
2599 // Not gonna happen.
2601 mInjector.binderRestoreCallingIdentity(ident);
2605 private void updateDeviceOwnerLocked() {
2606 long ident = mInjector.binderClearCallingIdentity();
2608 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2609 // user id and also protect all other DAs too.
2610 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2611 if (deviceOwnerComponent != null) {
2612 mInjector.getIActivityManager()
2613 .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2615 } catch (RemoteException e) {
2616 // Not gonna happen.
2618 mInjector.binderRestoreCallingIdentity(ident);
2622 static void validateQualityConstant(int quality) {
2624 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2625 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2626 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2627 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2628 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2629 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2630 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2631 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2632 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2635 throw new IllegalArgumentException("Invalid quality constant: 0x"
2636 + Integer.toHexString(quality));
2639 void validatePasswordOwnerLocked(DevicePolicyData policy) {
2640 if (policy.mPasswordOwner >= 0) {
2641 boolean haveOwner = false;
2642 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2643 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2649 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2650 + " no longer active; disabling");
2651 policy.mPasswordOwner = -1;
2657 void systemReady(int phase) {
2662 case SystemService.PHASE_LOCK_SETTINGS_READY:
2663 onLockSettingsReady();
2665 case SystemService.PHASE_BOOT_COMPLETED:
2666 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2671 private void onLockSettingsReady() {
2672 getUserData(UserHandle.USER_SYSTEM);
2676 onStartUser(UserHandle.USER_SYSTEM);
2678 // Register an observer for watching for user setup complete.
2679 new SetupContentObserver(mHandler).register();
2680 // Initialize the user setup state, to handle the upgrade case.
2681 updateUserSetupCompleteAndPaired();
2683 List<String> packageList;
2684 synchronized (this) {
2685 packageList = getKeepUninstalledPackagesLocked();
2687 if (packageList != null) {
2688 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2691 synchronized (this) {
2692 // push the force-ephemeral-users policy to the user manager.
2693 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2694 if (deviceOwner != null) {
2695 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2700 private void ensureDeviceOwnerUserStarted() {
2702 synchronized (this) {
2703 if (!mOwners.hasDeviceOwner()) {
2706 userId = mOwners.getDeviceOwnerUserId();
2709 Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2711 if (userId != UserHandle.USER_SYSTEM) {
2713 mInjector.getIActivityManager().startUserInBackground(userId);
2715 // STOPSHIP Prevent the DO user from being killed.
2717 } catch (RemoteException e) {
2718 Slog.w(LOG_TAG, "Exception starting user", e);
2723 private void onStartUser(int userId) {
2724 updateScreenCaptureDisabledInWindowManager(userId,
2725 getScreenCaptureDisabled(null, userId));
2726 pushUserRestrictions(userId);
2729 private void cleanUpOldUsers() {
2730 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2732 Set<Integer> usersWithProfileOwners;
2733 Set<Integer> usersWithData;
2734 synchronized(this) {
2735 usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2736 usersWithData = new ArraySet<>();
2737 for (int i = 0; i < mUserData.size(); i++) {
2738 usersWithData.add(mUserData.keyAt(i));
2741 List<UserInfo> allUsers = mUserManager.getUsers();
2743 Set<Integer> deletedUsers = new ArraySet<>();
2744 deletedUsers.addAll(usersWithProfileOwners);
2745 deletedUsers.addAll(usersWithData);
2746 for (UserInfo userInfo : allUsers) {
2747 deletedUsers.remove(userInfo.id);
2749 for (Integer userId : deletedUsers) {
2750 removeUserData(userId);
2754 private void handlePasswordExpirationNotification(int userHandle) {
2755 synchronized (this) {
2756 final long now = System.currentTimeMillis();
2758 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2759 userHandle, /* parent */ false);
2760 final int N = admins.size();
2761 for (int i = 0; i < N; i++) {
2762 ActiveAdmin admin = admins.get(i);
2763 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2764 && admin.passwordExpirationTimeout > 0L
2765 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2766 && admin.passwordExpirationDate > 0L) {
2767 sendAdminCommandLocked(admin,
2768 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2771 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2775 private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2777 protected Void doInBackground(Integer... params) {
2778 int userHandle = params[0];
2780 if (userHandle == UserHandle.USER_ALL) {
2781 for (UserInfo userInfo : mUserManager.getUsers(true)) {
2782 manageNotification(userInfo.getUserHandle());
2785 manageNotification(UserHandle.of(userHandle));
2790 private void manageNotification(UserHandle userHandle) {
2791 if (!mUserManager.isUserUnlocked(userHandle)) {
2795 // Call out to KeyChain to check for CAs which are waiting for approval.
2796 final List<String> pendingCertificates;
2798 pendingCertificates = getInstalledCaCertificates(userHandle);
2799 } catch (RemoteException | RuntimeException e) {
2800 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2804 synchronized (DevicePolicyManagerService.this) {
2805 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2807 // Remove deleted certificates. Flush xml if necessary.
2808 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2809 saveSettingsLocked(userHandle.getIdentifier());
2811 // Trim to approved certificates.
2812 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2815 if (pendingCertificates.isEmpty()) {
2816 mInjector.getNotificationManager().cancelAsUser(
2817 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2821 // Build and show a warning notification
2824 int parentUserId = userHandle.getIdentifier();
2825 if (getProfileOwner(userHandle.getIdentifier()) != null) {
2826 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2827 getProfileOwnerName(userHandle.getIdentifier()));
2828 smallIconId = R.drawable.stat_sys_certificate_info;
2829 parentUserId = getProfileParentId(userHandle.getIdentifier());
2830 } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
2831 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2832 getDeviceOwnerName());
2833 smallIconId = R.drawable.stat_sys_certificate_info;
2835 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2836 smallIconId = android.R.drawable.stat_sys_warning;
2839 final int numberOfCertificates = pendingCertificates.size();
2840 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2841 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2842 dialogIntent.setPackage("com.android.settings");
2843 dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
2844 dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
2845 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2846 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
2847 new UserHandle(parentUserId));
2849 final Context userContext;
2851 final String packageName = mContext.getPackageName();
2852 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
2853 } catch (PackageManager.NameNotFoundException e) {
2854 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2857 final Notification noti = new Notification.Builder(userContext)
2858 .setSmallIcon(smallIconId)
2859 .setContentTitle(mContext.getResources().getQuantityText(
2860 R.plurals.ssl_ca_cert_warning, numberOfCertificates))
2861 .setContentText(contentText)
2862 .setContentIntent(notifyIntent)
2863 .setPriority(Notification.PRIORITY_HIGH)
2865 .setColor(mContext.getColor(
2866 com.android.internal.R.color.system_notification_accent_color))
2869 mInjector.getNotificationManager().notifyAsUser(
2870 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2873 private List<String> getInstalledCaCertificates(UserHandle userHandle)
2874 throws RemoteException, RuntimeException {
2875 KeyChainConnection conn = null;
2877 conn = KeyChain.bindAsUser(mContext, userHandle);
2878 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
2879 List<String> result = new ArrayList<>(aliases.size());
2880 for (int i = 0; i < aliases.size(); i++) {
2881 result.add(aliases.get(i).string);
2884 } catch (InterruptedException e) {
2885 Thread.currentThread().interrupt();
2887 } catch (AssertionError e) {
2888 throw new RuntimeException(e);
2898 * @param adminReceiver The admin to add
2899 * @param refreshing true = update an active admin, no error
2902 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2906 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2909 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2910 Bundle onEnableData) {
2911 mContext.enforceCallingOrSelfPermission(
2912 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2913 enforceFullCrossUsersPermission(userHandle);
2915 DevicePolicyData policy = getUserData(userHandle);
2916 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2917 /* throwForMissionPermission= */ true);
2919 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2921 if (!info.getActivityInfo().applicationInfo.isInternal()) {
2922 throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2925 synchronized (this) {
2926 long ident = mInjector.binderClearCallingIdentity();
2928 final ActiveAdmin existingAdmin
2929 = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2930 if (!refreshing && existingAdmin != null) {
2931 throw new IllegalArgumentException("Admin is already added");
2933 if (policy.mRemovingAdmins.contains(adminReceiver)) {
2934 throw new IllegalArgumentException(
2935 "Trying to set an admin which is being removed");
2937 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2938 newAdmin.testOnlyAdmin =
2939 (existingAdmin != null) ? existingAdmin.testOnlyAdmin
2940 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
2941 policy.mAdminMap.put(adminReceiver, newAdmin);
2942 int replaceIndex = -1;
2943 final int N = policy.mAdminList.size();
2944 for (int i=0; i < N; i++) {
2945 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2946 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2951 if (replaceIndex == -1) {
2952 policy.mAdminList.add(newAdmin);
2953 enableIfNecessary(info.getPackageName(), userHandle);
2955 policy.mAdminList.set(replaceIndex, newAdmin);
2957 saveSettingsLocked(userHandle);
2958 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2959 onEnableData, null);
2961 mInjector.binderRestoreCallingIdentity(ident);
2967 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2971 enforceFullCrossUsersPermission(userHandle);
2972 synchronized (this) {
2973 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2978 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2982 enforceFullCrossUsersPermission(userHandle);
2983 synchronized (this) {
2984 DevicePolicyData policyData = getUserData(userHandle);
2985 return policyData.mRemovingAdmins.contains(adminReceiver);
2990 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2994 enforceFullCrossUsersPermission(userHandle);
2995 synchronized (this) {
2996 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2997 if (administrator == null) {
2998 throw new SecurityException("No active admin " + adminReceiver);
3000 return administrator.info.usesPolicy(policyId);
3005 @SuppressWarnings("unchecked")
3006 public List<ComponentName> getActiveAdmins(int userHandle) {
3008 return Collections.EMPTY_LIST;
3011 enforceFullCrossUsersPermission(userHandle);
3012 synchronized (this) {
3013 DevicePolicyData policy = getUserData(userHandle);
3014 final int N = policy.mAdminList.size();
3018 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3019 for (int i=0; i<N; i++) {
3020 res.add(policy.mAdminList.get(i).info.getComponent());
3027 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
3031 enforceFullCrossUsersPermission(userHandle);
3032 synchronized (this) {
3033 DevicePolicyData policy = getUserData(userHandle);
3034 final int N = policy.mAdminList.size();
3035 for (int i=0; i<N; i++) {
3036 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
3044 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
3048 Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
3049 enforceShell("forceRemoveActiveAdmin");
3050 long ident = mInjector.binderClearCallingIdentity();
3052 synchronized (this) {
3053 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
3054 throw new SecurityException("Attempt to remove non-test admin "
3055 + adminReceiver + " " + userHandle);
3058 // If admin is a device or profile owner tidy that up first.
3059 if (isDeviceOwner(adminReceiver, userHandle)) {
3060 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3062 if (isProfileOwner(adminReceiver, userHandle)) {
3063 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3064 userHandle, /* parent */ false);
3065 clearProfileOwnerLocked(admin, userHandle);
3068 // Remove the admin skipping sending the broadcast.
3069 removeAdminArtifacts(adminReceiver, userHandle);
3070 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3072 mInjector.binderRestoreCallingIdentity(ident);
3077 * Return if a given package has testOnly="true", in which case we'll relax certain rules
3080 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked}
3081 * to check wehter an active admin is test-only or not.
3083 * The system allows this flag to be changed when an app is updated, which is not good
3084 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3085 * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3087 private boolean isPackageTestOnly(String packageName, int userHandle) {
3088 final ApplicationInfo ai;
3090 ai = mIPackageManager.getApplicationInfo(packageName,
3091 (PackageManager.MATCH_DIRECT_BOOT_AWARE
3092 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3093 } catch (RemoteException e) {
3094 throw new IllegalStateException(e);
3097 throw new IllegalStateException("Couldn't find package: "
3098 + packageName + " on user " + userHandle);
3100 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3104 * See {@link #isPackageTestOnly}.
3106 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3107 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3108 return (admin != null) && admin.testOnlyAdmin;
3111 private void enforceShell(String method) {
3112 final int callingUid = Binder.getCallingUid();
3113 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3114 throw new SecurityException("Non-shell user attempted to call " + method);
3119 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3123 enforceFullCrossUsersPermission(userHandle);
3124 enforceUserUnlocked(userHandle);
3125 synchronized (this) {
3126 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3127 if (admin == null) {
3130 // Active device/profile owners must remain active admins.
3131 if (isDeviceOwner(adminReceiver, userHandle)
3132 || isProfileOwner(adminReceiver, userHandle)) {
3133 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3137 if (admin.getUid() != mInjector.binderGetCallingUid()) {
3138 mContext.enforceCallingOrSelfPermission(
3139 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3141 long ident = mInjector.binderClearCallingIdentity();
3143 removeActiveAdminLocked(adminReceiver, userHandle);
3145 mInjector.binderRestoreCallingIdentity(ident);
3151 public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3152 ComponentName profileOwner = getProfileOwner(userHandle);
3153 // Profile challenge is supported on N or newer release.
3154 return profileOwner != null &&
3155 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3159 public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3163 Preconditions.checkNotNull(who, "ComponentName is null");
3164 validateQualityConstant(quality);
3166 synchronized (this) {
3167 ActiveAdmin ap = getActiveAdminForCallerLocked(
3168 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3169 if (ap.passwordQuality != quality) {
3170 ap.passwordQuality = quality;
3171 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3177 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3179 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3181 enforceFullCrossUsersPermission(userHandle);
3182 synchronized (this) {
3183 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3186 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3187 return admin != null ? admin.passwordQuality : mode;
3190 // Return the strictest policy across all participating admins.
3191 List<ActiveAdmin> admins =
3192 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3193 final int N = admins.size();
3194 for (int i = 0; i < N; i++) {
3195 ActiveAdmin admin = admins.get(i);
3196 if (mode < admin.passwordQuality) {
3197 mode = admin.passwordQuality;
3204 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3205 int userHandle, boolean parent) {
3206 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3207 // If this user has a separate challenge, only return its restrictions.
3208 return getUserDataUnchecked(userHandle).mAdminList;
3210 // Return all admins for this user and the profiles that are visible from this
3211 // user that do not use a separate work challenge.
3212 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3213 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3214 DevicePolicyData policy = getUserData(userInfo.id);
3215 if (!userInfo.isManagedProfile()) {
3216 admins.addAll(policy.mAdminList);
3218 // For managed profiles, we always include the policies set on the parent
3219 // profile. Additionally, we include the ones set on the managed profile
3220 // if no separate challenge is in place.
3221 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3222 final int N = policy.mAdminList.size();
3223 for (int i = 0; i < N; i++) {
3224 ActiveAdmin admin = policy.mAdminList.get(i);
3225 if (admin.hasParentActiveAdmin()) {
3226 admins.add(admin.getParentActiveAdmin());
3228 if (!hasSeparateChallenge) {
3238 private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3239 long ident = mInjector.binderClearCallingIdentity();
3241 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3243 mInjector.binderRestoreCallingIdentity(ident);
3248 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3252 Preconditions.checkNotNull(who, "ComponentName is null");
3253 synchronized (this) {
3254 ActiveAdmin ap = getActiveAdminForCallerLocked(
3255 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3256 if (ap.minimumPasswordLength != length) {
3257 ap.minimumPasswordLength = length;
3258 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3264 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3268 enforceFullCrossUsersPermission(userHandle);
3269 synchronized (this) {
3273 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3274 return admin != null ? admin.minimumPasswordLength : length;
3277 // Return the strictest policy across all participating admins.
3278 List<ActiveAdmin> admins =
3279 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3280 final int N = admins.size();
3281 for (int i = 0; i < N; i++) {
3282 ActiveAdmin admin = admins.get(i);
3283 if (length < admin.minimumPasswordLength) {
3284 length = admin.minimumPasswordLength;
3292 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3296 Preconditions.checkNotNull(who, "ComponentName is null");
3297 synchronized (this) {
3298 ActiveAdmin ap = getActiveAdminForCallerLocked(
3299 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3300 if (ap.passwordHistoryLength != length) {
3301 ap.passwordHistoryLength = length;
3302 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3308 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3312 enforceFullCrossUsersPermission(userHandle);
3313 synchronized (this) {
3317 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3318 return admin != null ? admin.passwordHistoryLength : length;
3321 // Return the strictest policy across all participating admins.
3322 List<ActiveAdmin> admins =
3323 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3324 final int N = admins.size();
3325 for (int i = 0; i < N; i++) {
3326 ActiveAdmin admin = admins.get(i);
3327 if (length < admin.passwordHistoryLength) {
3328 length = admin.passwordHistoryLength;
3337 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3341 Preconditions.checkNotNull(who, "ComponentName is null");
3342 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3343 final int userHandle = mInjector.userHandleGetCallingUserId();
3344 synchronized (this) {
3345 ActiveAdmin ap = getActiveAdminForCallerLocked(
3346 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3347 // Calling this API automatically bumps the expiration date
3348 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3349 ap.passwordExpirationDate = expiration;
3350 ap.passwordExpirationTimeout = timeout;
3352 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3353 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3354 .format(new Date(expiration)));
3356 saveSettingsLocked(userHandle);
3358 // in case this is the first one, set the alarm on the appropriate user.
3359 setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3364 * Return a single admin's expiration cycle time, or the min of all cycle times.
3365 * Returns 0 if not configured.
3368 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3372 enforceFullCrossUsersPermission(userHandle);
3373 synchronized (this) {
3377 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3378 return admin != null ? admin.passwordExpirationTimeout : timeout;
3381 // Return the strictest policy across all participating admins.
3382 List<ActiveAdmin> admins =
3383 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3384 final int N = admins.size();
3385 for (int i = 0; i < N; i++) {
3386 ActiveAdmin admin = admins.get(i);
3387 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3388 && timeout > admin.passwordExpirationTimeout)) {
3389 timeout = admin.passwordExpirationTimeout;
3397 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3398 final int userId = UserHandle.getCallingUserId();
3399 List<String> changedProviders = null;
3401 synchronized (this) {
3402 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3403 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3404 if (activeAdmin.crossProfileWidgetProviders == null) {
3405 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3407 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3408 if (!providers.contains(packageName)) {
3409 providers.add(packageName);
3410 changedProviders = new ArrayList<>(providers);
3411 saveSettingsLocked(userId);
3415 if (changedProviders != null) {
3416 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3424 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3425 final int userId = UserHandle.getCallingUserId();
3426 List<String> changedProviders = null;
3428 synchronized (this) {
3429 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3430 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3431 if (activeAdmin.crossProfileWidgetProviders == null) {
3434 List<String> providers = activeAdmin.crossProfileWidgetProviders;
3435 if (providers.remove(packageName)) {
3436 changedProviders = new ArrayList<>(providers);
3437 saveSettingsLocked(userId);
3441 if (changedProviders != null) {
3442 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3450 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3451 synchronized (this) {
3452 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3453 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3454 if (activeAdmin.crossProfileWidgetProviders == null
3455 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3458 if (mInjector.binderIsCallingUidMyUid()) {
3459 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3461 return activeAdmin.crossProfileWidgetProviders;
3467 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3468 * Returns 0 if not configured.
3470 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3474 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3475 return admin != null ? admin.passwordExpirationDate : timeout;
3478 // Return the strictest policy across all participating admins.
3479 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3480 final int N = admins.size();
3481 for (int i = 0; i < N; i++) {
3482 ActiveAdmin admin = admins.get(i);
3483 if (timeout == 0L || (admin.passwordExpirationDate != 0
3484 && timeout > admin.passwordExpirationDate)) {
3485 timeout = admin.passwordExpirationDate;
3492 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3496 enforceFullCrossUsersPermission(userHandle);
3497 synchronized (this) {
3498 return getPasswordExpirationLocked(who, userHandle, parent);
3503 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3507 Preconditions.checkNotNull(who, "ComponentName is null");
3508 synchronized (this) {
3509 ActiveAdmin ap = getActiveAdminForCallerLocked(
3510 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3511 if (ap.minimumPasswordUpperCase != length) {
3512 ap.minimumPasswordUpperCase = length;
3513 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3519 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3523 enforceFullCrossUsersPermission(userHandle);
3524 synchronized (this) {
3528 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3529 return admin != null ? admin.minimumPasswordUpperCase : length;
3532 // Return the strictest policy across all participating admins.
3533 List<ActiveAdmin> admins =
3534 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3535 final int N = admins.size();
3536 for (int i = 0; i < N; i++) {
3537 ActiveAdmin admin = admins.get(i);
3538 if (length < admin.minimumPasswordUpperCase) {
3539 length = admin.minimumPasswordUpperCase;
3547 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3548 Preconditions.checkNotNull(who, "ComponentName is null");
3549 synchronized (this) {
3550 ActiveAdmin ap = getActiveAdminForCallerLocked(
3551 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3552 if (ap.minimumPasswordLowerCase != length) {
3553 ap.minimumPasswordLowerCase = length;
3554 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3560 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3564 enforceFullCrossUsersPermission(userHandle);
3565 synchronized (this) {
3569 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3570 return admin != null ? admin.minimumPasswordLowerCase : length;
3573 // Return the strictest policy across all participating admins.
3574 List<ActiveAdmin> admins =
3575 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3576 final int N = admins.size();
3577 for (int i = 0; i < N; i++) {
3578 ActiveAdmin admin = admins.get(i);
3579 if (length < admin.minimumPasswordLowerCase) {
3580 length = admin.minimumPasswordLowerCase;
3588 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3592 Preconditions.checkNotNull(who, "ComponentName is null");
3593 synchronized (this) {
3594 ActiveAdmin ap = getActiveAdminForCallerLocked(
3595 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3596 if (ap.minimumPasswordLetters != length) {
3597 ap.minimumPasswordLetters = length;
3598 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3604 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3608 enforceFullCrossUsersPermission(userHandle);
3609 synchronized (this) {
3613 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3614 return admin != null ? admin.minimumPasswordLetters : length;
3617 // Return the strictest policy across all participating admins.
3618 List<ActiveAdmin> admins =
3619 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3620 final int N = admins.size();
3621 for (int i = 0; i < N; i++) {
3622 ActiveAdmin admin = admins.get(i);
3623 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3626 if (length < admin.minimumPasswordLetters) {
3627 length = admin.minimumPasswordLetters;
3635 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3639 Preconditions.checkNotNull(who, "ComponentName is null");
3640 synchronized (this) {
3641 ActiveAdmin ap = getActiveAdminForCallerLocked(
3642 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3643 if (ap.minimumPasswordNumeric != length) {
3644 ap.minimumPasswordNumeric = length;
3645 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3651 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3655 enforceFullCrossUsersPermission(userHandle);
3656 synchronized (this) {
3660 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3661 return admin != null ? admin.minimumPasswordNumeric : length;
3664 // Return the strictest policy across all participating admins.
3665 List<ActiveAdmin> admins =
3666 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3667 final int N = admins.size();
3668 for (int i = 0; i < N; i++) {
3669 ActiveAdmin admin = admins.get(i);
3670 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3673 if (length < admin.minimumPasswordNumeric) {
3674 length = admin.minimumPasswordNumeric;
3682 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3686 Preconditions.checkNotNull(who, "ComponentName is null");
3687 synchronized (this) {
3688 ActiveAdmin ap = getActiveAdminForCallerLocked(
3689 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3690 if (ap.minimumPasswordSymbols != length) {
3691 ap.minimumPasswordSymbols = length;
3692 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3698 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3702 enforceFullCrossUsersPermission(userHandle);
3703 synchronized (this) {
3707 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3708 return admin != null ? admin.minimumPasswordSymbols : length;
3711 // Return the strictest policy across all participating admins.
3712 List<ActiveAdmin> admins =
3713 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3714 final int N = admins.size();
3715 for (int i = 0; i < N; i++) {
3716 ActiveAdmin admin = admins.get(i);
3717 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3720 if (length < admin.minimumPasswordSymbols) {
3721 length = admin.minimumPasswordSymbols;
3729 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3733 Preconditions.checkNotNull(who, "ComponentName is null");
3734 synchronized (this) {
3735 ActiveAdmin ap = getActiveAdminForCallerLocked(
3736 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3737 if (ap.minimumPasswordNonLetter != length) {
3738 ap.minimumPasswordNonLetter = length;
3739 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3745 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3749 enforceFullCrossUsersPermission(userHandle);
3750 synchronized (this) {
3754 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3755 return admin != null ? admin.minimumPasswordNonLetter : length;
3758 // Return the strictest policy across all participating admins.
3759 List<ActiveAdmin> admins =
3760 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3761 final int N = admins.size();
3762 for (int i = 0; i < N; i++) {
3763 ActiveAdmin admin = admins.get(i);
3764 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3767 if (length < admin.minimumPasswordNonLetter) {
3768 length = admin.minimumPasswordNonLetter;
3776 public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3780 enforceFullCrossUsersPermission(userHandle);
3782 synchronized (this) {
3783 // This API can only be called by an active device admin,
3784 // so try to retrieve it to check that the caller is one.
3785 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3786 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3787 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3792 public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3796 enforceFullCrossUsersPermission(userHandle);
3797 enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3799 synchronized (this) {
3800 int targetUser = getProfileParentId(userHandle);
3801 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3802 return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3806 private boolean isActivePasswordSufficientForUserLocked(
3807 DevicePolicyData policy, int userHandle, boolean parent) {
3808 enforceUserUnlocked(userHandle, parent);
3810 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
3811 if (policy.mActivePasswordQuality < requiredPasswordQuality) {
3814 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
3815 && policy.mActivePasswordLength < getPasswordMinimumLength(
3816 null, userHandle, parent)) {
3819 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3822 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3823 null, userHandle, parent)
3824 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3825 null, userHandle, parent)
3826 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3827 null, userHandle, parent)
3828 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3829 null, userHandle, parent)
3830 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3831 null, userHandle, parent)
3832 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3833 null, userHandle, parent);
3837 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3838 enforceFullCrossUsersPermission(userHandle);
3839 synchronized (this) {
3840 if (!isCallerWithSystemUid()) {
3841 // This API can only be called by an active device admin,
3842 // so try to retrieve it to check that the caller is one.
3843 getActiveAdminForCallerLocked(
3844 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3847 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3849 return policy.mFailedPasswordAttempts;
3854 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3858 Preconditions.checkNotNull(who, "ComponentName is null");
3859 synchronized (this) {
3860 // This API can only be called by an active device admin,
3861 // so try to retrieve it to check that the caller is one.
3862 getActiveAdminForCallerLocked(
3863 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3864 ActiveAdmin ap = getActiveAdminForCallerLocked(
3865 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3866 if (ap.maximumFailedPasswordsForWipe != num) {
3867 ap.maximumFailedPasswordsForWipe = num;
3868 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3874 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3878 enforceFullCrossUsersPermission(userHandle);
3879 synchronized (this) {
3880 ActiveAdmin admin = (who != null)
3881 ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3882 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3883 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3888 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3890 return UserHandle.USER_NULL;
3892 enforceFullCrossUsersPermission(userHandle);
3893 synchronized (this) {
3894 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3895 userHandle, parent);
3896 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3901 * Returns the admin with the strictest policy on maximum failed passwords for:
3903 * <li>this user if it has a separate profile challenge, or
3904 * <li>this user and all profiles that don't have their own challenge otherwise.
3906 * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3907 * the primary profile.
3908 * Returns {@code null} if no participating admin has that policy set.
3910 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3911 int userHandle, boolean parent) {
3913 ActiveAdmin strictestAdmin = null;
3915 // Return the strictest policy across all participating admins.
3916 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3917 final int N = admins.size();
3918 for (int i = 0; i < N; i++) {
3919 ActiveAdmin admin = admins.get(i);
3920 if (admin.maximumFailedPasswordsForWipe ==
3921 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3922 continue; // No max number of failed passwords policy set for this profile.
3925 // We always favor the primary profile if several profiles have the same value set.
3926 int userId = admin.getUserHandle().getIdentifier();
3928 count > admin.maximumFailedPasswordsForWipe ||
3929 (count == admin.maximumFailedPasswordsForWipe &&
3930 getUserInfo(userId).isPrimary())) {
3931 count = admin.maximumFailedPasswordsForWipe;
3932 strictestAdmin = admin;
3935 return strictestAdmin;
3938 private UserInfo getUserInfo(@UserIdInt int userId) {
3939 final long token = mInjector.binderClearCallingIdentity();
3941 return mUserManager.getUserInfo(userId);
3943 mInjector.binderRestoreCallingIdentity(token);
3948 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3952 final int callingUid = mInjector.binderGetCallingUid();
3953 final int userHandle = mInjector.userHandleGetCallingUserId();
3955 String password = passwordOrNull != null ? passwordOrNull : "";
3957 // Password resetting to empty/null is not allowed for managed profiles.
3958 if (TextUtils.isEmpty(password)) {
3959 enforceNotManagedProfile(userHandle, "clear the active password");
3963 synchronized (this) {
3964 // If caller has PO (or DO) it can change the password, so see if that's the case first.
3965 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3966 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3968 if (admin != null) {
3969 preN = getTargetSdk(admin.info.getPackageName(),
3970 userHandle) <= android.os.Build.VERSION_CODES.M;
3972 // Otherwise, make sure the caller has any active admin with the right policy.
3973 admin = getActiveAdminForCallerLocked(null,
3974 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3975 preN = getTargetSdk(admin.info.getPackageName(),
3976 userHandle) <= android.os.Build.VERSION_CODES.M;
3978 // As of N, password resetting to empty/null is not allowed anymore.
3979 // TODO Should we allow DO/PO to set an empty password?
3980 if (TextUtils.isEmpty(password)) {
3982 throw new SecurityException("Cannot call with null password");
3984 Slog.e(LOG_TAG, "Cannot call with null password");
3988 // As of N, password cannot be changed by the admin if it is already set.
3989 if (isLockScreenSecureUnchecked(userHandle)) {
3991 throw new SecurityException("Admin cannot change current password");
3993 Slog.e(LOG_TAG, "Admin cannot change current password");
3998 // Do not allow to reset password when current user has a managed profile
3999 if (!isManagedProfile(userHandle)) {
4000 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4001 if (userInfo.isManagedProfile()) {
4003 throw new IllegalStateException(
4004 "Cannot reset password on user has managed profile");
4006 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
4012 // Do not allow to reset password when user is locked
4013 if (!mUserManager.isUserUnlocked(userHandle)) {
4015 throw new IllegalStateException("Cannot reset password when user is locked");
4017 Slog.e(LOG_TAG, "Cannot reset password when user is locked");
4022 quality = getPasswordQuality(null, userHandle, /* parent */ false);
4023 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
4024 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4026 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
4027 int realQuality = LockPatternUtils.computePasswordQuality(password);
4028 if (realQuality < quality
4029 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4030 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
4031 + Integer.toHexString(realQuality)
4032 + " does not meet required quality 0x"
4033 + Integer.toHexString(quality));
4036 quality = Math.max(realQuality, quality);
4038 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
4039 if (password.length() < length) {
4040 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
4041 + " does not meet required length " + length);
4044 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4051 for (int i = 0; i < password.length(); i++) {
4052 char c = password.charAt(i);
4053 if (c >= 'A' && c <= 'Z') {
4056 } else if (c >= 'a' && c <= 'z') {
4059 } else if (c >= '0' && c <= '9') {
4067 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4068 if(letters < neededLetters) {
4069 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
4070 + " does not meet required number of letters " + neededLetters);
4073 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4074 if (numbers < neededNumbers) {
4075 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
4076 + " does not meet required number of numerical digits "
4080 int neededLowerCase = getPasswordMinimumLowerCase(
4081 null, userHandle, /* parent */ false);
4082 if (lowercase < neededLowerCase) {
4083 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
4084 + " does not meet required number of lowercase letters "
4088 int neededUpperCase = getPasswordMinimumUpperCase(
4089 null, userHandle, /* parent */ false);
4090 if (uppercase < neededUpperCase) {
4091 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
4092 + " does not meet required number of uppercase letters "
4096 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4097 if (symbols < neededSymbols) {
4098 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
4099 + " does not meet required number of special symbols " + neededSymbols);
4102 int neededNonLetter = getPasswordMinimumNonLetter(
4103 null, userHandle, /* parent */ false);
4104 if (nonletter < neededNonLetter) {
4105 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
4106 + " does not meet required number of non-letter characters "
4113 DevicePolicyData policy = getUserData(userHandle);
4114 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4115 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4119 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4120 boolean doNotAskCredentialsOnBoot =
4121 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4122 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4123 setDoNotAskCredentialsOnBoot();
4126 // Don't do this with the lock held, because it is going to call
4127 // back in to the service.
4128 final long ident = mInjector.binderClearCallingIdentity();
4130 if (!TextUtils.isEmpty(password)) {
4131 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4133 mLockPatternUtils.clearLock(userHandle);
4135 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4137 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4138 UserHandle.USER_ALL);
4140 synchronized (this) {
4141 int newOwner = requireEntry ? callingUid : -1;
4142 if (policy.mPasswordOwner != newOwner) {
4143 policy.mPasswordOwner = newOwner;
4144 saveSettingsLocked(userHandle);
4148 mInjector.binderRestoreCallingIdentity(ident);
4154 private boolean isLockScreenSecureUnchecked(int userId) {
4155 long ident = mInjector.binderClearCallingIdentity();
4157 return mLockPatternUtils.isSecure(userId);
4159 mInjector.binderRestoreCallingIdentity(ident);
4163 private void setDoNotAskCredentialsOnBoot() {
4164 synchronized (this) {
4165 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4166 if (!policyData.doNotAskCredentialsOnBoot) {
4167 policyData.doNotAskCredentialsOnBoot = true;
4168 saveSettingsLocked(UserHandle.USER_SYSTEM);
4174 public boolean getDoNotAskCredentialsOnBoot() {
4175 mContext.enforceCallingOrSelfPermission(
4176 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4177 synchronized (this) {
4178 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4179 return policyData.doNotAskCredentialsOnBoot;
4184 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4188 Preconditions.checkNotNull(who, "ComponentName is null");
4189 final int userHandle = mInjector.userHandleGetCallingUserId();
4190 synchronized (this) {
4191 ActiveAdmin ap = getActiveAdminForCallerLocked(
4192 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4193 if (ap.maximumTimeToUnlock != timeMs) {
4194 ap.maximumTimeToUnlock = timeMs;
4195 saveSettingsLocked(userHandle);
4196 updateMaximumTimeToLockLocked(userHandle);
4201 void updateMaximumTimeToLockLocked(int userHandle) {
4202 // Calculate the min timeout for all profiles - including the ones with a separate
4203 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4204 // challenge only and keep the screen on. However there is no easy way of doing that at the
4205 // moment so we set the screen off timeout regardless of whether it affects the parent user
4206 // or the profile challenge only.
4207 long timeMs = Long.MAX_VALUE;
4208 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4209 for (int profileId : profileIds) {
4210 DevicePolicyData policy = getUserDataUnchecked(profileId);
4211 final int N = policy.mAdminList.size();
4212 for (int i = 0; i < N; i++) {
4213 ActiveAdmin admin = policy.mAdminList.get(i);
4214 if (admin.maximumTimeToUnlock > 0
4215 && timeMs > admin.maximumTimeToUnlock) {
4216 timeMs = admin.maximumTimeToUnlock;
4218 // If userInfo.id is a managed profile, we also need to look at
4219 // the policies set on the parent.
4220 if (admin.hasParentActiveAdmin()) {
4221 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4222 if (parentAdmin.maximumTimeToUnlock > 0
4223 && timeMs > parentAdmin.maximumTimeToUnlock) {
4224 timeMs = parentAdmin.maximumTimeToUnlock;
4230 // We only store the last maximum time to lock on the parent profile. So if calling from a
4231 // managed profile, retrieve the policy for the parent.
4232 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4233 if (policy.mLastMaximumTimeToLock == timeMs) {
4236 policy.mLastMaximumTimeToLock = timeMs;
4238 final long ident = mInjector.binderClearCallingIdentity();
4240 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4241 // Make sure KEEP_SCREEN_ON is disabled, since that
4242 // would allow bypassing of the maximum time to lock.
4243 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4246 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4247 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4249 mInjector.binderRestoreCallingIdentity(ident);
4254 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4258 enforceFullCrossUsersPermission(userHandle);
4259 synchronized (this) {
4261 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4262 return admin != null ? admin.maximumTimeToUnlock : 0;
4264 // Return the strictest policy across all participating admins.
4265 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4266 userHandle, parent);
4267 return getMaximumTimeToLockPolicyFromAdmins(admins);
4272 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4276 enforceFullCrossUsersPermission(userHandle);
4277 synchronized (this) {
4278 // All admins for this user.
4279 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4280 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4281 DevicePolicyData policy = getUserData(userInfo.id);
4282 admins.addAll(policy.mAdminList);
4283 // If it is a managed profile, it may have parent active admins
4284 if (userInfo.isManagedProfile()) {
4285 for (ActiveAdmin admin : policy.mAdminList) {
4286 if (admin.hasParentActiveAdmin()) {
4287 admins.add(admin.getParentActiveAdmin());
4292 return getMaximumTimeToLockPolicyFromAdmins(admins);
4296 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4298 final int N = admins.size();
4299 for (int i = 0; i < N; i++) {
4300 ActiveAdmin admin = admins.get(i);
4302 time = admin.maximumTimeToUnlock;
4303 } else if (admin.maximumTimeToUnlock != 0
4304 && time > admin.maximumTimeToUnlock) {
4305 time = admin.maximumTimeToUnlock;
4312 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
4317 Preconditions.checkNotNull(who, "ComponentName is null");
4318 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
4319 // timeoutMs with value 0 means that the admin doesn't participate
4320 // timeoutMs is clamped to the interval in case the internal constants change in the future
4321 if (timeoutMs != 0 && timeoutMs < MINIMUM_STRONG_AUTH_TIMEOUT_MS) {
4322 timeoutMs = MINIMUM_STRONG_AUTH_TIMEOUT_MS;
4324 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
4325 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4328 final int userHandle = mInjector.userHandleGetCallingUserId();
4329 synchronized (this) {
4330 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4331 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4332 if (ap.strongAuthUnlockTimeout != timeoutMs) {
4333 ap.strongAuthUnlockTimeout = timeoutMs;
4334 saveSettingsLocked(userHandle);
4340 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
4341 * admins if who is null.
4342 * Returns 0 if not configured for the provided admin.
4345 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
4347 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4349 enforceFullCrossUsersPermission(userId);
4350 synchronized (this) {
4352 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
4353 return admin != null ? admin.strongAuthUnlockTimeout : 0;
4356 // Return the strictest policy across all participating admins.
4357 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
4359 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4360 for (int i = 0; i < admins.size(); i++) {
4361 final long timeout = admins.get(i).strongAuthUnlockTimeout;
4362 if (timeout != 0) { // take only participating admins into account
4363 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
4366 return Math.max(strongAuthUnlockTimeout, MINIMUM_STRONG_AUTH_TIMEOUT_MS);
4371 public void lockNow(boolean parent) {
4375 synchronized (this) {
4376 // This API can only be called by an active device admin,
4377 // so try to retrieve it to check that the caller is one.
4378 getActiveAdminForCallerLocked(
4379 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4381 int userToLock = mInjector.userHandleGetCallingUserId();
4383 // Unless this is a managed profile with work challenge enabled, lock all users.
4384 if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4385 userToLock = UserHandle.USER_ALL;
4387 final long ident = mInjector.binderClearCallingIdentity();
4389 mLockPatternUtils.requireStrongAuth(
4390 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4391 if (userToLock == UserHandle.USER_ALL) {
4392 // Power off the display
4393 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4394 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4395 mInjector.getIWindowManager().lockNow(null);
4397 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4399 } catch (RemoteException e) {
4401 mInjector.binderRestoreCallingIdentity(ident);
4407 public void enforceCanManageCaCerts(ComponentName who) {
4409 if (!isCallerDelegatedCertInstaller()) {
4410 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4413 synchronized (this) {
4414 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4419 private void enforceCanManageInstalledKeys(ComponentName who) {
4421 if (!isCallerDelegatedCertInstaller()) {
4422 throw new SecurityException("who == null, but caller is not cert installer");
4425 synchronized (this) {
4426 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4431 private boolean isCallerDelegatedCertInstaller() {
4432 final int callingUid = mInjector.binderGetCallingUid();
4433 final int userHandle = UserHandle.getUserId(callingUid);
4434 synchronized (this) {
4435 final DevicePolicyData policy = getUserData(userHandle);
4436 if (policy.mDelegatedCertInstallerPackage == null) {
4441 int uid = mContext.getPackageManager().getPackageUidAsUser(
4442 policy.mDelegatedCertInstallerPackage, userHandle);
4443 return uid == callingUid;
4444 } catch (NameNotFoundException e) {
4451 public boolean approveCaCert(String alias, int userId, boolean approval) {
4452 enforceManageUsers();
4453 synchronized (this) {
4454 Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4455 boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4459 saveSettingsLocked(userId);
4461 new MonitoringCertNotificationTask().execute(userId);
4466 public boolean isCaCertApproved(String alias, int userId) {
4467 enforceManageUsers();
4468 synchronized (this) {
4469 return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4473 private void removeCaApprovalsIfNeeded(int userId) {
4474 for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4475 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4476 if (userInfo.isManagedProfile()){
4477 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4480 synchronized (this) {
4481 getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4482 saveSettingsLocked(userInfo.id);
4485 new MonitoringCertNotificationTask().execute(userInfo.id);
4491 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4492 enforceCanManageCaCerts(admin);
4496 X509Certificate cert = parseCert(certBuffer);
4497 pemCert = Credentials.convertToPem(cert);
4498 } catch (CertificateException ce) {
4499 Log.e(LOG_TAG, "Problem converting cert", ce);
4501 } catch (IOException ioe) {
4502 Log.e(LOG_TAG, "Problem reading cert", ioe);
4506 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4507 final long id = mInjector.binderClearCallingIdentity();
4509 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4511 keyChainConnection.getService().installCaCertificate(pemCert);
4513 } catch (RemoteException e) {
4514 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4516 keyChainConnection.close();
4518 } catch (InterruptedException e1) {
4519 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4520 Thread.currentThread().interrupt();
4522 mInjector.binderRestoreCallingIdentity(id);
4527 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4528 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4529 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4534 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4535 enforceCanManageCaCerts(admin);
4537 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4538 final long id = mInjector.binderClearCallingIdentity();
4540 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4542 for (int i = 0 ; i < aliases.length; i++) {
4543 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4545 } catch (RemoteException e) {
4546 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4548 keyChainConnection.close();
4550 } catch (InterruptedException ie) {
4551 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4552 Thread.currentThread().interrupt();
4554 mInjector.binderRestoreCallingIdentity(id);
4559 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4560 String alias, boolean requestAccess) {
4561 enforceCanManageInstalledKeys(who);
4563 final int callingUid = mInjector.binderGetCallingUid();
4564 final long id = mInjector.binderClearCallingIdentity();
4566 final KeyChainConnection keyChainConnection =
4567 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4569 IKeyChainService keyChain = keyChainConnection.getService();
4570 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4573 if (requestAccess) {
4574 keyChain.setGrant(callingUid, alias, true);
4577 } catch (RemoteException e) {
4578 Log.e(LOG_TAG, "Installing certificate", e);
4580 keyChainConnection.close();
4582 } catch (InterruptedException e) {
4583 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4584 Thread.currentThread().interrupt();
4586 mInjector.binderRestoreCallingIdentity(id);
4592 public boolean removeKeyPair(ComponentName who, String alias) {
4593 enforceCanManageInstalledKeys(who);
4595 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4596 final long id = Binder.clearCallingIdentity();
4598 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4600 IKeyChainService keyChain = keyChainConnection.getService();
4601 return keyChain.removeKeyPair(alias);
4602 } catch (RemoteException e) {
4603 Log.e(LOG_TAG, "Removing keypair", e);
4605 keyChainConnection.close();
4607 } catch (InterruptedException e) {
4608 Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4609 Thread.currentThread().interrupt();
4611 Binder.restoreCallingIdentity(id);
4617 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4618 final IBinder response) {
4619 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4620 if (!isCallerWithSystemUid()) {
4624 final UserHandle caller = mInjector.binderGetCallingUserHandle();
4625 // If there is a profile owner, redirect to that; otherwise query the device owner.
4626 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4627 if (aliasChooser == null && caller.isSystem()) {
4628 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4629 if (deviceOwnerAdmin != null) {
4630 aliasChooser = deviceOwnerAdmin.info.getComponent();
4633 if (aliasChooser == null) {
4634 sendPrivateKeyAliasResponse(null, response);
4638 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4639 intent.setComponent(aliasChooser);
4640 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4641 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4642 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4643 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4644 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4646 final long id = mInjector.binderClearCallingIdentity();
4648 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4650 public void onReceive(Context context, Intent intent) {
4651 final String chosenAlias = getResultData();
4652 sendPrivateKeyAliasResponse(chosenAlias, response);
4654 }, null, Activity.RESULT_OK, null, null);
4656 mInjector.binderRestoreCallingIdentity(id);
4660 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4661 final IKeyChainAliasCallback keyChainAliasResponse =
4662 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4663 new AsyncTask<Void, Void, Void>() {
4665 protected Void doInBackground(Void... unused) {
4667 keyChainAliasResponse.alias(alias);
4668 } catch (Exception e) {
4669 // Catch everything (not just RemoteException): caller could throw a
4670 // RuntimeException back across processes.
4671 Log.e(LOG_TAG, "error while responding to callback", e);
4679 public void setCertInstallerPackage(ComponentName who, String installerPackage)
4680 throws SecurityException {
4681 int userHandle = UserHandle.getCallingUserId();
4682 synchronized (this) {
4683 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4684 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4685 if (installerPackage != null &&
4686 !isPackageInstalledForUser(installerPackage, userHandle)) {
4687 throw new IllegalArgumentException("Package " + installerPackage
4688 + " is not installed on the current user");
4691 DevicePolicyData policy = getUserData(userHandle);
4692 policy.mDelegatedCertInstallerPackage = installerPackage;
4693 saveSettingsLocked(userHandle);
4698 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4699 int userHandle = UserHandle.getCallingUserId();
4700 synchronized (this) {
4701 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4702 DevicePolicyData policy = getUserData(userHandle);
4703 return policy.mDelegatedCertInstallerPackage;
4708 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4709 * not installed and therefore not available.
4711 * @throws SecurityException if the caller is not a profile or device owner.
4712 * @throws UnsupportedOperationException if the package does not support being set as always-on.
4715 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4716 throws SecurityException {
4717 synchronized (this) {
4718 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4721 final int userId = mInjector.userHandleGetCallingUserId();
4722 final long token = mInjector.binderClearCallingIdentity();
4724 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4727 ConnectivityManager connectivityManager = (ConnectivityManager)
4728 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4729 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4730 throw new UnsupportedOperationException();
4733 mInjector.binderRestoreCallingIdentity(token);
4739 public String getAlwaysOnVpnPackage(ComponentName admin)
4740 throws SecurityException {
4741 synchronized (this) {
4742 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4745 final int userId = mInjector.userHandleGetCallingUserId();
4746 final long token = mInjector.binderClearCallingIdentity();
4748 ConnectivityManager connectivityManager = (ConnectivityManager)
4749 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4750 return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4752 mInjector.binderRestoreCallingIdentity(token);
4756 private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
4757 if (wipeExtRequested) {
4758 StorageManager sm = (StorageManager) mContext.getSystemService(
4759 Context.STORAGE_SERVICE);
4760 sm.wipeAdoptableDisks();
4763 RecoverySystem.rebootWipeUserData(mContext, reason);
4764 } catch (IOException | SecurityException e) {
4765 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4770 public void wipeData(int flags) {
4774 final int userHandle = mInjector.userHandleGetCallingUserId();
4775 enforceFullCrossUsersPermission(userHandle);
4777 final String source;
4778 synchronized (this) {
4779 // This API can only be called by an active device admin,
4780 // so try to retrieve it to check that the caller is one.
4781 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4782 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4783 source = admin.info.getComponent().flattenToShortString();
4785 long ident = mInjector.binderClearCallingIdentity();
4787 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4788 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4789 throw new SecurityException(
4790 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4792 PersistentDataBlockManager manager = (PersistentDataBlockManager)
4793 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4794 if (manager != null) {
4799 mInjector.binderRestoreCallingIdentity(ident);
4802 final boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4803 wipeDeviceNoLock(wipeExtRequested, userHandle,
4804 "DevicePolicyManager.wipeData() from " + source);
4807 private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
4808 final long ident = mInjector.binderClearCallingIdentity();
4810 if (userHandle == UserHandle.USER_SYSTEM) {
4811 wipeDataNoLock(wipeExtRequested, reason);
4813 mHandler.post(new Runnable() {
4817 IActivityManager am = mInjector.getIActivityManager();
4818 if (am.getCurrentUser().id == userHandle) {
4819 am.switchUser(UserHandle.USER_SYSTEM);
4822 boolean isManagedProfile = isManagedProfile(userHandle);
4823 if (!mUserManager.removeUser(userHandle)) {
4824 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4825 } else if (isManagedProfile) {
4826 sendWipeProfileNotification();
4828 } catch (RemoteException re) {
4835 mInjector.binderRestoreCallingIdentity(ident);
4839 private void sendWipeProfileNotification() {
4840 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4841 Notification notification = new Notification.Builder(mContext)
4842 .setSmallIcon(android.R.drawable.stat_sys_warning)
4843 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4844 .setContentText(contentText)
4845 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4846 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4848 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4851 private void clearWipeProfileNotification() {
4852 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4856 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4860 enforceFullCrossUsersPermission(userHandle);
4861 mContext.enforceCallingOrSelfPermission(
4862 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4864 synchronized (this) {
4865 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4866 if (admin == null) {
4867 result.sendResult(null);
4870 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4871 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4872 intent.setComponent(admin.info.getComponent());
4873 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4874 null, new BroadcastReceiver() {
4876 public void onReceive(Context context, Intent intent) {
4877 result.sendResult(getResultExtras(false));
4879 }, null, Activity.RESULT_OK, null, null);
4884 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4885 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4889 enforceFullCrossUsersPermission(userHandle);
4890 mContext.enforceCallingOrSelfPermission(
4891 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4893 // If the managed profile doesn't have a separate password, set the metrics to default
4894 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
4895 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4905 validateQualityConstant(quality);
4906 DevicePolicyData policy = getUserData(userHandle);
4907 synchronized (this) {
4908 policy.mActivePasswordQuality = quality;
4909 policy.mActivePasswordLength = length;
4910 policy.mActivePasswordLetters = letters;
4911 policy.mActivePasswordLowerCase = lowercase;
4912 policy.mActivePasswordUpperCase = uppercase;
4913 policy.mActivePasswordNumeric = numbers;
4914 policy.mActivePasswordSymbols = symbols;
4915 policy.mActivePasswordNonLetter = nonletter;
4920 public void reportPasswordChanged(int userId) {
4924 enforceFullCrossUsersPermission(userId);
4926 // Managed Profile password can only be changed when it has a separate challenge.
4927 if (!isSeparateProfileChallengeEnabled(userId)) {
4928 enforceNotManagedProfile(userId, "set the active password");
4931 mContext.enforceCallingOrSelfPermission(
4932 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4934 DevicePolicyData policy = getUserData(userId);
4936 long ident = mInjector.binderClearCallingIdentity();
4938 synchronized (this) {
4939 policy.mFailedPasswordAttempts = 0;
4940 saveSettingsLocked(userId);
4941 updatePasswordExpirationsLocked(userId);
4942 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
4944 // Send a broadcast to each profile using this password as its primary unlock.
4945 sendAdminCommandForLockscreenPoliciesLocked(
4946 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4947 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
4949 removeCaApprovalsIfNeeded(userId);
4951 mInjector.binderRestoreCallingIdentity(ident);
4956 * Called any time the device password is updated. Resets all password expiration clocks.
4958 private void updatePasswordExpirationsLocked(int userHandle) {
4959 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4960 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4961 userHandle, /* parent */ false);
4962 final int N = admins.size();
4963 for (int i = 0; i < N; i++) {
4964 ActiveAdmin admin = admins.get(i);
4965 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4966 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4967 long timeout = admin.passwordExpirationTimeout;
4968 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4969 admin.passwordExpirationDate = expiration;
4972 for (int affectedUserId : affectedUserIds) {
4973 saveSettingsLocked(affectedUserId);
4978 public void reportFailedPasswordAttempt(int userHandle) {
4979 enforceFullCrossUsersPermission(userHandle);
4980 if (!isSeparateProfileChallengeEnabled(userHandle)) {
4981 enforceNotManagedProfile(userHandle,
4982 "report failed password attempt if separate profile challenge is not in place");
4984 mContext.enforceCallingOrSelfPermission(
4985 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4987 final long ident = mInjector.binderClearCallingIdentity();
4989 boolean wipeData = false;
4991 synchronized (this) {
4992 DevicePolicyData policy = getUserData(userHandle);
4993 policy.mFailedPasswordAttempts++;
4994 saveSettingsLocked(userHandle);
4996 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4997 userHandle, /* parent */ false);
4998 int max = strictestAdmin != null
4999 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
5000 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
5001 // Wipe the user/profile associated with the policy that was violated. This
5002 // is not necessarily calling user: if the policy that fired was from a
5003 // managed profile rather than the main user profile, we wipe former only.
5005 identifier = strictestAdmin.getUserHandle().getIdentifier();
5008 sendAdminCommandForLockscreenPoliciesLocked(
5009 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
5010 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5014 // Call without holding lock.
5015 wipeDeviceNoLock(false, identifier,
5016 "reportFailedPasswordAttempt()");
5019 mInjector.binderRestoreCallingIdentity(ident);
5022 if (mInjector.securityLogIsLoggingEnabled()) {
5023 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5024 /*method strength*/ 1);
5029 public void reportSuccessfulPasswordAttempt(int userHandle) {
5030 enforceFullCrossUsersPermission(userHandle);
5031 mContext.enforceCallingOrSelfPermission(
5032 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5034 synchronized (this) {
5035 DevicePolicyData policy = getUserData(userHandle);
5036 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
5037 long ident = mInjector.binderClearCallingIdentity();
5039 policy.mFailedPasswordAttempts = 0;
5040 policy.mPasswordOwner = -1;
5041 saveSettingsLocked(userHandle);
5043 sendAdminCommandForLockscreenPoliciesLocked(
5044 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
5045 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5048 mInjector.binderRestoreCallingIdentity(ident);
5053 if (mInjector.securityLogIsLoggingEnabled()) {
5054 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5055 /*method strength*/ 1);
5060 public void reportFailedFingerprintAttempt(int userHandle) {
5061 enforceFullCrossUsersPermission(userHandle);
5062 mContext.enforceCallingOrSelfPermission(
5063 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5064 if (mInjector.securityLogIsLoggingEnabled()) {
5065 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5066 /*method strength*/ 0);
5071 public void reportSuccessfulFingerprintAttempt(int userHandle) {
5072 enforceFullCrossUsersPermission(userHandle);
5073 mContext.enforceCallingOrSelfPermission(
5074 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5075 if (mInjector.securityLogIsLoggingEnabled()) {
5076 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5077 /*method strength*/ 0);
5082 public void reportKeyguardDismissed(int userHandle) {
5083 enforceFullCrossUsersPermission(userHandle);
5084 mContext.enforceCallingOrSelfPermission(
5085 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5087 if (mInjector.securityLogIsLoggingEnabled()) {
5088 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
5093 public void reportKeyguardSecured(int userHandle) {
5094 enforceFullCrossUsersPermission(userHandle);
5095 mContext.enforceCallingOrSelfPermission(
5096 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5098 if (mInjector.securityLogIsLoggingEnabled()) {
5099 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
5104 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
5105 String exclusionList) {
5109 synchronized(this) {
5110 Preconditions.checkNotNull(who, "ComponentName is null");
5112 // Only check if system user has set global proxy. We don't allow other users to set it.
5113 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5114 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5115 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
5117 // Scan through active admins and find if anyone has already
5118 // set the global proxy.
5119 Set<ComponentName> compSet = policy.mAdminMap.keySet();
5120 for (ComponentName component : compSet) {
5121 ActiveAdmin ap = policy.mAdminMap.get(component);
5122 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
5123 // Another admin already sets the global proxy
5124 // Return it to the caller.
5129 // If the user is not system, don't set the global proxy. Fail silently.
5130 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
5131 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
5132 + UserHandle.getCallingUserId() + " is not permitted.");
5135 if (proxySpec == null) {
5136 admin.specifiesGlobalProxy = false;
5137 admin.globalProxySpec = null;
5138 admin.globalProxyExclusionList = null;
5141 admin.specifiesGlobalProxy = true;
5142 admin.globalProxySpec = proxySpec;
5143 admin.globalProxyExclusionList = exclusionList;
5146 // Reset the global proxy accordingly
5147 // Do this using system permissions, as apps cannot write to secure settings
5148 long origId = mInjector.binderClearCallingIdentity();
5150 resetGlobalProxyLocked(policy);
5152 mInjector.binderRestoreCallingIdentity(origId);
5159 public ComponentName getGlobalProxyAdmin(int userHandle) {
5163 enforceFullCrossUsersPermission(userHandle);
5164 synchronized(this) {
5165 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5166 // Scan through active admins and find if anyone has already
5167 // set the global proxy.
5168 final int N = policy.mAdminList.size();
5169 for (int i = 0; i < N; i++) {
5170 ActiveAdmin ap = policy.mAdminList.get(i);
5171 if (ap.specifiesGlobalProxy) {
5172 // Device admin sets the global proxy
5173 // Return it to the caller.
5174 return ap.info.getComponent();
5178 // No device admin sets the global proxy.
5183 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5184 synchronized (this) {
5185 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5187 long token = mInjector.binderClearCallingIdentity();
5189 ConnectivityManager connectivityManager = (ConnectivityManager)
5190 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5191 connectivityManager.setGlobalProxy(proxyInfo);
5193 mInjector.binderRestoreCallingIdentity(token);
5197 private void resetGlobalProxyLocked(DevicePolicyData policy) {
5198 final int N = policy.mAdminList.size();
5199 for (int i = 0; i < N; i++) {
5200 ActiveAdmin ap = policy.mAdminList.get(i);
5201 if (ap.specifiesGlobalProxy) {
5202 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5206 // No device admins defining global proxies - reset global proxy settings to none
5207 saveGlobalProxyLocked(null, null);
5210 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5211 if (exclusionList == null) {
5214 if (proxySpec == null) {
5217 // Remove white spaces
5218 proxySpec = proxySpec.trim();
5219 String data[] = proxySpec.split(":");
5220 int proxyPort = 8080;
5221 if (data.length > 1) {
5223 proxyPort = Integer.parseInt(data[1]);
5224 } catch (NumberFormatException e) {}
5226 exclusionList = exclusionList.trim();
5228 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5229 if (!proxyProperties.isValid()) {
5230 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5233 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5234 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5235 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5240 * Set the storage encryption request for a single admin. Returns the new total request
5241 * status (for all admins).
5244 public int setStorageEncryption(ComponentName who, boolean encrypt) {
5246 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5248 Preconditions.checkNotNull(who, "ComponentName is null");
5249 final int userHandle = UserHandle.getCallingUserId();
5250 synchronized (this) {
5251 // Check for permissions
5252 // Only system user can set storage encryption
5253 if (userHandle != UserHandle.USER_SYSTEM) {
5254 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5255 + UserHandle.getCallingUserId() + " is not permitted.");
5259 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5260 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5262 // Quick exit: If the filesystem does not support encryption, we can exit early.
5263 if (!isEncryptionSupported()) {
5264 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5267 // (1) Record the value for the admin so it's sticky
5268 if (ap.encryptionRequested != encrypt) {
5269 ap.encryptionRequested = encrypt;
5270 saveSettingsLocked(userHandle);
5273 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5274 // (2) Compute "max" for all admins
5275 boolean newRequested = false;
5276 final int N = policy.mAdminList.size();
5277 for (int i = 0; i < N; i++) {
5278 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5281 // Notify OS of new request
5282 setEncryptionRequested(newRequested);
5284 // Return the new global request status
5286 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5287 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5292 * Get the current storage encryption request status for a given admin, or aggregate of all
5296 public boolean getStorageEncryption(ComponentName who, int userHandle) {
5300 enforceFullCrossUsersPermission(userHandle);
5301 synchronized (this) {
5302 // Check for permissions if a particular caller is specified
5304 // When checking for a single caller, status is based on caller's request
5305 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5306 return ap != null ? ap.encryptionRequested : false;
5309 // If no particular caller is specified, return the aggregate set of requests.
5310 // This is short circuited by returning true on the first hit.
5311 DevicePolicyData policy = getUserData(userHandle);
5312 final int N = policy.mAdminList.size();
5313 for (int i = 0; i < N; i++) {
5314 if (policy.mAdminList.get(i).encryptionRequested) {
5323 * Get the current encryption status of the device.
5326 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5328 // Ok to return current status.
5330 enforceFullCrossUsersPermission(userHandle);
5332 // It's not critical here, but let's make sure the package name is correct, in case
5333 // we start using it for different purposes.
5334 ensureCallerPackage(callerPackage);
5336 final ApplicationInfo ai;
5338 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5339 } catch (RemoteException e) {
5340 throw new SecurityException(e);
5343 boolean legacyApp = false;
5344 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5348 final int rawStatus = getEncryptionStatus();
5349 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5350 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5356 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
5358 private boolean isEncryptionSupported() {
5359 // Note, this can be implemented as
5360 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5361 // But is provided as a separate internal method if there's a faster way to do a
5362 // simple check for supported-or-not.
5363 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5367 * Hook to low-levels: Reporting the current status of encryption.
5368 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5369 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5370 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5371 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5372 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5374 private int getEncryptionStatus() {
5375 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5376 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5377 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5378 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5379 } else if (mInjector.storageManagerIsEncrypted()) {
5380 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5381 } else if (mInjector.storageManagerIsEncryptable()) {
5382 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5384 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5389 * Hook to low-levels: If needed, record the new admin setting for encryption.
5391 private void setEncryptionRequested(boolean encrypt) {
5395 * Set whether the screen capture is disabled for the user managed by the specified admin.
5398 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5402 Preconditions.checkNotNull(who, "ComponentName is null");
5403 final int userHandle = UserHandle.getCallingUserId();
5404 synchronized (this) {
5405 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5406 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5407 if (ap.disableScreenCapture != disabled) {
5408 ap.disableScreenCapture = disabled;
5409 saveSettingsLocked(userHandle);
5410 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5416 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5417 * active admin (if given admin is null).
5420 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5424 synchronized (this) {
5426 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5427 return (admin != null) ? admin.disableScreenCapture : false;
5430 DevicePolicyData policy = getUserData(userHandle);
5431 final int N = policy.mAdminList.size();
5432 for (int i = 0; i < N; i++) {
5433 ActiveAdmin admin = policy.mAdminList.get(i);
5434 if (admin.disableScreenCapture) {
5442 private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5443 final boolean disabled) {
5444 mHandler.post(new Runnable() {
5448 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5449 } catch (RemoteException e) {
5450 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5457 * Set whether auto time is required by the specified admin (must be device owner).
5460 public void setAutoTimeRequired(ComponentName who, boolean required) {
5464 Preconditions.checkNotNull(who, "ComponentName is null");
5465 final int userHandle = UserHandle.getCallingUserId();
5466 synchronized (this) {
5467 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5468 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5469 if (admin.requireAutoTime != required) {
5470 admin.requireAutoTime = required;
5471 saveSettingsLocked(userHandle);
5475 // Turn AUTO_TIME on in settings if it is required
5477 long ident = mInjector.binderClearCallingIdentity();
5479 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5481 mInjector.binderRestoreCallingIdentity(ident);
5487 * Returns whether or not auto time is required by the device owner.
5490 public boolean getAutoTimeRequired() {
5494 synchronized (this) {
5495 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5496 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5501 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5505 Preconditions.checkNotNull(who, "ComponentName is null");
5506 // Allow setting this policy to true only if there is a split system user.
5507 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5508 throw new UnsupportedOperationException(
5509 "Cannot force ephemeral users on systems without split system user.");
5511 boolean removeAllUsers = false;
5512 synchronized (this) {
5513 final ActiveAdmin deviceOwner =
5514 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5515 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5516 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5517 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5518 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5519 removeAllUsers = forceEphemeralUsers;
5522 if (removeAllUsers) {
5523 long identitity = mInjector.binderClearCallingIdentity();
5525 mUserManagerInternal.removeAllUsers();
5527 mInjector.binderRestoreCallingIdentity(identitity);
5533 public boolean getForceEphemeralUsers(ComponentName who) {
5537 Preconditions.checkNotNull(who, "ComponentName is null");
5538 synchronized (this) {
5539 final ActiveAdmin deviceOwner =
5540 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5541 return deviceOwner.forceEphemeralUsers;
5545 private boolean isDeviceOwnerManagedSingleUserDevice() {
5546 synchronized (this) {
5547 if (!mOwners.hasDeviceOwner()) {
5551 final long callingIdentity = mInjector.binderClearCallingIdentity();
5553 if (mInjector.userManagerIsSplitSystemUser()) {
5554 // In split system user mode, only allow the case where the device owner is managing
5555 // the only non-system user of the device
5556 return (mUserManager.getUserCount() == 2
5557 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5559 return mUserManager.getUserCount() == 1;
5562 mInjector.binderRestoreCallingIdentity(callingIdentity);
5566 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5567 synchronized (this) {
5568 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5570 if (!isDeviceOwnerManagedSingleUserDevice()) {
5571 throw new SecurityException(
5572 "There should only be one user, managed by Device Owner");
5577 public boolean requestBugreport(ComponentName who) {
5581 Preconditions.checkNotNull(who, "ComponentName is null");
5582 ensureDeviceOwnerManagingSingleUser(who);
5584 if (mRemoteBugreportServiceIsActive.get()
5585 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5586 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5590 final long callingIdentity = mInjector.binderClearCallingIdentity();
5592 ActivityManagerNative.getDefault().requestBugReport(
5593 ActivityManager.BUGREPORT_OPTION_REMOTE);
5595 mRemoteBugreportServiceIsActive.set(true);
5596 mRemoteBugreportSharingAccepted.set(false);
5597 registerRemoteBugreportReceivers();
5598 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5599 RemoteBugreportUtils.buildNotification(mContext,
5600 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5601 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5602 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5604 } catch (RemoteException re) {
5605 // should never happen
5606 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5609 mInjector.binderRestoreCallingIdentity(callingIdentity);
5613 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5614 Intent intent = new Intent(action);
5615 intent.setComponent(mOwners.getDeviceOwnerComponent());
5616 if (extras != null) {
5617 intent.putExtras(extras);
5619 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5622 private synchronized String getDeviceOwnerRemoteBugreportUri() {
5623 return mOwners.getDeviceOwnerRemoteBugreportUri();
5626 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5627 String bugreportHash) {
5628 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5631 private void registerRemoteBugreportReceivers() {
5633 IntentFilter filterFinished = new IntentFilter(
5634 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5635 RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5636 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5637 } catch (IntentFilter.MalformedMimeTypeException e) {
5638 // should never happen, as setting a constant
5639 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5641 IntentFilter filterConsent = new IntentFilter();
5642 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5643 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5644 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5647 private void onBugreportFinished(Intent intent) {
5648 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5649 mRemoteBugreportServiceIsActive.set(false);
5650 Uri bugreportUri = intent.getData();
5651 String bugreportUriString = null;
5652 if (bugreportUri != null) {
5653 bugreportUriString = bugreportUri.toString();
5655 String bugreportHash = intent.getStringExtra(
5656 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5657 if (mRemoteBugreportSharingAccepted.get()) {
5658 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5659 mInjector.getNotificationManager().cancel(LOG_TAG,
5660 RemoteBugreportUtils.NOTIFICATION_ID);
5662 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5663 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5664 RemoteBugreportUtils.buildNotification(mContext,
5665 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5668 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5671 private void onBugreportFailed() {
5672 mRemoteBugreportServiceIsActive.set(false);
5673 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5674 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5675 mRemoteBugreportSharingAccepted.set(false);
5676 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5677 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5678 Bundle extras = new Bundle();
5679 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5680 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5681 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5682 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5683 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5686 private void onBugreportSharingAccepted() {
5687 mRemoteBugreportSharingAccepted.set(true);
5688 String bugreportUriString = null;
5689 String bugreportHash = null;
5690 synchronized (this) {
5691 bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5692 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5694 if (bugreportUriString != null) {
5695 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5696 } else if (mRemoteBugreportServiceIsActive.get()) {
5697 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5698 RemoteBugreportUtils.buildNotification(mContext,
5699 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5704 private void onBugreportSharingDeclined() {
5705 if (mRemoteBugreportServiceIsActive.get()) {
5706 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5707 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5708 mRemoteBugreportServiceIsActive.set(false);
5709 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5710 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5712 mRemoteBugreportSharingAccepted.set(false);
5713 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5714 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5717 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5718 String bugreportHash) {
5719 ParcelFileDescriptor pfd = null;
5721 if (bugreportUriString == null) {
5722 throw new FileNotFoundException();
5724 Uri bugreportUri = Uri.parse(bugreportUriString);
5725 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5727 synchronized (this) {
5728 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5729 intent.setComponent(mOwners.getDeviceOwnerComponent());
5730 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5731 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5732 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
5733 bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5734 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5736 } catch (FileNotFoundException e) {
5737 Bundle extras = new Bundle();
5738 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5739 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5740 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5746 } catch (IOException ex) {
5749 mRemoteBugreportSharingAccepted.set(false);
5750 setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5755 * Disables all device cameras according to the specified admin.
5758 public void setCameraDisabled(ComponentName who, boolean disabled) {
5762 Preconditions.checkNotNull(who, "ComponentName is null");
5763 final int userHandle = mInjector.userHandleGetCallingUserId();
5764 synchronized (this) {
5765 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5766 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5767 if (ap.disableCamera != disabled) {
5768 ap.disableCamera = disabled;
5769 saveSettingsLocked(userHandle);
5772 // Tell the user manager that the restrictions have changed.
5773 pushUserRestrictions(userHandle);
5777 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5781 public boolean getCameraDisabled(ComponentName who, int userHandle) {
5782 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5785 private boolean getCameraDisabled(ComponentName who, int userHandle,
5786 boolean mergeDeviceOwnerRestriction) {
5790 synchronized (this) {
5792 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5793 return (admin != null) ? admin.disableCamera : false;
5795 // First, see if DO has set it. If so, it's device-wide.
5796 if (mergeDeviceOwnerRestriction) {
5797 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5798 if (deviceOwner != null && deviceOwner.disableCamera) {
5803 // Then check each device admin on the user.
5804 DevicePolicyData policy = getUserData(userHandle);
5805 // Determine whether or not the device camera is disabled for any active admins.
5806 final int N = policy.mAdminList.size();
5807 for (int i = 0; i < N; i++) {
5808 ActiveAdmin admin = policy.mAdminList.get(i);
5809 if (admin.disableCamera) {
5818 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5822 Preconditions.checkNotNull(who, "ComponentName is null");
5823 final int userHandle = mInjector.userHandleGetCallingUserId();
5824 if (isManagedProfile(userHandle)) {
5826 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5828 which = which & PROFILE_KEYGUARD_FEATURES;
5831 synchronized (this) {
5832 ActiveAdmin ap = getActiveAdminForCallerLocked(
5833 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5834 if (ap.disabledKeyguardFeatures != which) {
5835 ap.disabledKeyguardFeatures = which;
5836 saveSettingsLocked(userHandle);
5842 * Gets the disabled state for features in keyguard for the given admin,
5843 * or the aggregate of all active admins if who is null.
5846 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5850 enforceFullCrossUsersPermission(userHandle);
5851 final long ident = mInjector.binderClearCallingIdentity();
5853 synchronized (this) {
5855 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5856 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5859 final List<ActiveAdmin> admins;
5860 if (!parent && isManagedProfile(userHandle)) {
5861 // If we are being asked about a managed profile, just return keyguard features
5862 // disabled by admins in the profile.
5863 admins = getUserDataUnchecked(userHandle).mAdminList;
5865 // Otherwise return those set by admins in the user and its profiles.
5866 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5869 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5870 final int N = admins.size();
5871 for (int i = 0; i < N; i++) {
5872 ActiveAdmin admin = admins.get(i);
5873 int userId = admin.getUserHandle().getIdentifier();
5874 boolean isRequestedUser = !parent && (userId == userHandle);
5875 if (isRequestedUser || !isManagedProfile(userId)) {
5876 // If we are being asked explicitly about this user
5877 // return all disabled features even if its a managed profile.
5878 which |= admin.disabledKeyguardFeatures;
5880 // Otherwise a managed profile is only allowed to disable
5881 // some features on the parent user.
5882 which |= (admin.disabledKeyguardFeatures
5883 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5889 mInjector.binderRestoreCallingIdentity(ident);
5894 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5898 Preconditions.checkNotNull(who, "ComponentName is null");
5899 Preconditions.checkNotNull(packageList, "packageList is null");
5900 final int userHandle = UserHandle.getCallingUserId();
5901 synchronized (this) {
5902 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5903 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5904 admin.keepUninstalledPackages = packageList;
5905 saveSettingsLocked(userHandle);
5906 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5911 public List<String> getKeepUninstalledPackages(ComponentName who) {
5912 Preconditions.checkNotNull(who, "ComponentName is null");
5916 // TODO In split system user mode, allow apps on user 0 to query the list
5917 synchronized (this) {
5918 // Check if this is the device owner who is calling
5919 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5920 return getKeepUninstalledPackagesLocked();
5924 private List<String> getKeepUninstalledPackagesLocked() {
5925 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5926 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5930 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5935 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5936 throw new IllegalArgumentException("Invalid component " + admin
5937 + " for device owner");
5939 final boolean hasIncompatibleAccountsOrNonAdb =
5940 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin);
5941 synchronized (this) {
5942 enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb);
5943 if (getActiveAdminUncheckedLocked(admin, userId) == null
5944 || getUserData(userId).mRemovingAdmins.contains(admin)) {
5945 throw new IllegalArgumentException("Not active admin: " + admin);
5948 // Shutting down backup manager service permanently.
5949 long ident = mInjector.binderClearCallingIdentity();
5951 if (mInjector.getIBackupManager() != null) {
5952 mInjector.getIBackupManager()
5953 .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5955 } catch (RemoteException e) {
5956 throw new IllegalStateException("Failed deactivating backup service.", e);
5958 mInjector.binderRestoreCallingIdentity(ident);
5961 mOwners.setDeviceOwner(admin, ownerName, userId);
5962 mOwners.writeDeviceOwner();
5963 updateDeviceOwnerLocked();
5964 setDeviceOwnerSystemPropertyLocked();
5965 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5967 ident = mInjector.binderClearCallingIdentity();
5969 // TODO Send to system too?
5970 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5972 mInjector.binderRestoreCallingIdentity(ident);
5974 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
5979 public boolean isDeviceOwner(ComponentName who, int userId) {
5980 synchronized (this) {
5981 return mOwners.hasDeviceOwner()
5982 && mOwners.getDeviceOwnerUserId() == userId
5983 && mOwners.getDeviceOwnerComponent().equals(who);
5987 public boolean isProfileOwner(ComponentName who, int userId) {
5988 final ComponentName profileOwner = getProfileOwner(userId);
5989 return who != null && who.equals(profileOwner);
5993 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5997 if (!callingUserOnly) {
5998 enforceManageUsers();
6000 synchronized (this) {
6001 if (!mOwners.hasDeviceOwner()) {
6004 if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
6005 mOwners.getDeviceOwnerUserId()) {
6008 return mOwners.getDeviceOwnerComponent();
6013 public int getDeviceOwnerUserId() {
6015 return UserHandle.USER_NULL;
6017 enforceManageUsers();
6018 synchronized (this) {
6019 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
6024 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires
6028 public String getDeviceOwnerName() {
6032 enforceManageUsers();
6033 synchronized (this) {
6034 if (!mOwners.hasDeviceOwner()) {
6037 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
6038 // Should setDeviceOwner/ProfileOwner still take a name?
6039 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
6040 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
6044 // Returns the active device owner or null if there is no device owner.
6046 ActiveAdmin getDeviceOwnerAdminLocked() {
6047 ComponentName component = mOwners.getDeviceOwnerComponent();
6048 if (component == null) {
6052 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
6053 final int n = policy.mAdminList.size();
6054 for (int i = 0; i < n; i++) {
6055 ActiveAdmin admin = policy.mAdminList.get(i);
6056 if (component.equals(admin.info.getComponent())) {
6060 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
6065 public void clearDeviceOwner(String packageName) {
6066 Preconditions.checkNotNull(packageName, "packageName is null");
6067 final int callingUid = mInjector.binderGetCallingUid();
6069 int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
6070 UserHandle.getUserId(callingUid));
6071 if (uid != callingUid) {
6072 throw new SecurityException("Invalid packageName");
6074 } catch (NameNotFoundException e) {
6075 throw new SecurityException(e);
6077 synchronized (this) {
6078 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6079 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6080 if (!mOwners.hasDeviceOwner()
6081 || !deviceOwnerComponent.getPackageName().equals(packageName)
6082 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
6083 throw new SecurityException(
6084 "clearDeviceOwner can only be called by the device owner");
6086 enforceUserUnlocked(deviceOwnerUserId);
6088 final ActiveAdmin admin = getDeviceOwnerAdminLocked();
6089 long ident = mInjector.binderClearCallingIdentity();
6091 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
6092 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
6094 mInjector.binderRestoreCallingIdentity(ident);
6096 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
6100 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
6101 if (admin != null) {
6102 admin.disableCamera = false;
6103 admin.userRestrictions = null;
6104 admin.forceEphemeralUsers = false;
6105 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
6107 clearUserPoliciesLocked(userId);
6109 mOwners.clearDeviceOwner();
6110 mOwners.writeDeviceOwner();
6111 updateDeviceOwnerLocked();
6112 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
6114 if (mInjector.getIBackupManager() != null) {
6115 // Reactivate backup service.
6116 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6118 } catch (RemoteException e) {
6119 throw new IllegalStateException("Failed reactivating backup service.", e);
6124 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6129 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6130 throw new IllegalArgumentException("Component " + who
6131 + " not installed for userId:" + userHandle);
6133 final boolean hasIncompatibleAccountsOrNonAdb =
6134 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who);
6135 synchronized (this) {
6136 enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb);
6138 if (getActiveAdminUncheckedLocked(who, userHandle) == null
6139 || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6140 throw new IllegalArgumentException("Not active admin: " + who);
6143 mOwners.setProfileOwner(who, ownerName, userHandle);
6144 mOwners.writeProfileOwner(userHandle);
6145 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6151 public void clearProfileOwner(ComponentName who) {
6155 final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
6156 final int userId = callingUser.getIdentifier();
6157 enforceNotManagedProfile(userId, "clear profile owner");
6158 enforceUserUnlocked(userId);
6159 // Check if this is the profile owner who is calling
6160 final ActiveAdmin admin =
6161 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6162 synchronized (this) {
6163 final long ident = mInjector.binderClearCallingIdentity();
6165 clearProfileOwnerLocked(admin, userId);
6166 removeActiveAdminLocked(who, userId);
6168 mInjector.binderRestoreCallingIdentity(ident);
6170 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6174 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6175 if (admin != null) {
6176 admin.disableCamera = false;
6177 admin.userRestrictions = null;
6179 clearUserPoliciesLocked(userId);
6180 mOwners.removeProfileOwner(userId);
6181 mOwners.writeProfileOwner(userId);
6185 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6186 Preconditions.checkNotNull(who, "ComponentName is null");
6191 synchronized (this) {
6192 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6193 long token = mInjector.binderClearCallingIdentity();
6195 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6197 mInjector.binderRestoreCallingIdentity(token);
6203 public CharSequence getDeviceOwnerLockScreenInfo() {
6204 return mLockPatternUtils.getDeviceOwnerInfo();
6207 private void clearUserPoliciesLocked(int userId) {
6208 // Reset some of the user-specific policies
6209 DevicePolicyData policy = getUserData(userId);
6210 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6211 policy.mDelegatedCertInstallerPackage = null;
6212 policy.mApplicationRestrictionsManagingPackage = null;
6213 policy.mStatusBarDisabled = false;
6214 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6215 saveSettingsLocked(userId);
6218 mIPackageManager.updatePermissionFlagsForAllApps(
6219 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6220 0 /* flagValues */, userId);
6221 pushUserRestrictions(userId);
6222 } catch (RemoteException re) {
6223 // Shouldn't happen.
6228 public boolean hasUserSetupCompleted() {
6229 return hasUserSetupCompleted(UserHandle.getCallingUserId());
6232 // This checks only if the Setup Wizard has run. Since Wear devices pair before
6233 // completing Setup Wizard, and pairing involves transferring user data, calling
6234 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
6235 private boolean hasUserSetupCompleted(int userHandle) {
6239 return getUserData(userHandle).mUserSetupComplete;
6242 private boolean hasPaired(int userHandle) {
6246 return getUserData(userHandle).mPaired;
6250 public int getUserProvisioningState() {
6252 return DevicePolicyManager.STATE_USER_UNMANAGED;
6254 int userHandle = mInjector.userHandleGetCallingUserId();
6255 return getUserProvisioningState(userHandle);
6258 private int getUserProvisioningState(int userHandle) {
6259 return getUserData(userHandle).mUserProvisioningState;
6263 public void setUserProvisioningState(int newState, int userHandle) {
6268 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6269 && getManagedUserId(userHandle) == -1) {
6270 // No managed device, user or profile, so setting provisioning state makes no sense.
6271 throw new IllegalStateException("Not allowed to change provisioning state unless a "
6272 + "device or profile owner is set.");
6275 synchronized (this) {
6276 boolean transitionCheckNeeded = true;
6278 // Calling identity/permission checks.
6279 final int callingUid = mInjector.binderGetCallingUid();
6280 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6281 // ADB shell can only move directly from un-managed to finalized as part of directly
6282 // setting profile-owner or device-owner.
6283 if (getUserProvisioningState(userHandle) !=
6284 DevicePolicyManager.STATE_USER_UNMANAGED
6285 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6286 throw new IllegalStateException("Not allowed to change provisioning state "
6287 + "unless current provisioning state is unmanaged, and new state is "
6290 transitionCheckNeeded = false;
6292 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6293 enforceCanManageProfileAndDeviceOwners();
6296 final DevicePolicyData policyData = getUserData(userHandle);
6297 if (transitionCheckNeeded) {
6298 // Optional state transition check for non-ADB case.
6299 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6301 policyData.mUserProvisioningState = newState;
6302 saveSettingsLocked(userHandle);
6306 private void checkUserProvisioningStateTransition(int currentState, int newState) {
6307 // Valid transitions for normal use-cases.
6308 switch (currentState) {
6309 case DevicePolicyManager.STATE_USER_UNMANAGED:
6310 // Can move to any state from unmanaged (except itself as an edge case)..
6311 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6315 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6316 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6317 // Can only move to finalized from these states.
6318 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6322 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6323 // Current user has a managed-profile, but current user is not managed, so
6324 // rather than moving to finalized state, go back to unmanaged once
6325 // profile provisioning is complete.
6326 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6330 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6331 // Cannot transition out of finalized.
6335 // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6336 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6337 + "from state [" + currentState + "]");
6341 public void setProfileEnabled(ComponentName who) {
6345 Preconditions.checkNotNull(who, "ComponentName is null");
6346 synchronized (this) {
6347 // Check if this is the profile owner who is calling
6348 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6349 final int userId = UserHandle.getCallingUserId();
6350 enforceManagedProfile(userId, "enable the profile");
6352 long id = mInjector.binderClearCallingIdentity();
6354 mUserManager.setUserEnabled(userId);
6355 UserInfo parent = mUserManager.getProfileParent(userId);
6356 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6357 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6358 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6359 Intent.FLAG_RECEIVER_FOREGROUND);
6360 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6362 mInjector.binderRestoreCallingIdentity(id);
6368 public void setProfileName(ComponentName who, String profileName) {
6369 Preconditions.checkNotNull(who, "ComponentName is null");
6370 int userId = UserHandle.getCallingUserId();
6371 // Check if this is the profile owner (includes device owner).
6372 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6374 long id = mInjector.binderClearCallingIdentity();
6376 mUserManager.setUserName(userId, profileName);
6378 mInjector.binderRestoreCallingIdentity(id);
6383 public ComponentName getProfileOwner(int userHandle) {
6388 synchronized (this) {
6389 return mOwners.getProfileOwnerComponent(userHandle);
6393 // Returns the active profile owner for this user or null if the current user has no
6396 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6397 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6398 if (profileOwner == null) {
6401 DevicePolicyData policy = getUserData(userHandle);
6402 final int n = policy.mAdminList.size();
6403 for (int i = 0; i < n; i++) {
6404 ActiveAdmin admin = policy.mAdminList.get(i);
6405 if (profileOwner.equals(admin.info.getComponent())) {
6413 public String getProfileOwnerName(int userHandle) {
6417 enforceManageUsers();
6418 ComponentName profileOwner = getProfileOwner(userHandle);
6419 if (profileOwner == null) {
6422 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6426 * Canonical name for a given package.
6428 private String getApplicationLabel(String packageName, int userHandle) {
6429 long token = mInjector.binderClearCallingIdentity();
6431 final Context userContext;
6433 UserHandle handle = new UserHandle(userHandle);
6434 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6435 } catch (PackageManager.NameNotFoundException nnfe) {
6436 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6439 ApplicationInfo appInfo = userContext.getApplicationInfo();
6440 CharSequence result = null;
6441 if (appInfo != null) {
6442 PackageManager pm = userContext.getPackageManager();
6443 result = pm.getApplicationLabel(appInfo);
6445 return result != null ? result.toString() : null;
6447 mInjector.binderRestoreCallingIdentity(token);
6452 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6454 * The profile owner can only be set before the user setup phase has completed,
6457 * - adb unless hasIncompatibleAccountsOrNonAdb is true.
6459 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle,
6460 boolean hasIncompatibleAccountsOrNonAdb) {
6461 UserInfo info = getUserInfo(userHandle);
6463 // User doesn't exist.
6464 throw new IllegalArgumentException(
6465 "Attempted to set profile owner for invalid userId: " + userHandle);
6467 if (info.isGuest()) {
6468 throw new IllegalStateException("Cannot set a profile owner on a guest");
6470 if (mOwners.hasProfileOwner(userHandle)) {
6471 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6472 + "is already set.");
6474 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6475 throw new IllegalStateException("Trying to set the profile owner, but the user "
6476 + "already has a device owner.");
6478 int callingUid = mInjector.binderGetCallingUid();
6479 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6480 if ((mIsWatch || hasUserSetupCompleted(userHandle))
6481 && hasIncompatibleAccountsOrNonAdb) {
6482 throw new IllegalStateException("Not allowed to set the profile owner because "
6483 + "there are already some accounts on the profile");
6487 enforceCanManageProfileAndDeviceOwners();
6488 if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
6489 throw new IllegalStateException("Cannot set the profile owner on a user which is "
6490 + "already set-up");
6495 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6498 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId,
6499 boolean hasIncompatibleAccountsOrNonAdb) {
6500 int callingUid = mInjector.binderGetCallingUid();
6501 boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6503 enforceCanManageProfileAndDeviceOwners();
6506 final int code = checkSetDeviceOwnerPreConditionLocked(owner, userId, isAdb,
6507 hasIncompatibleAccountsOrNonAdb);
6511 case CODE_HAS_DEVICE_OWNER:
6512 throw new IllegalStateException(
6513 "Trying to set the device owner, but device owner is already set.");
6514 case CODE_USER_HAS_PROFILE_OWNER:
6515 throw new IllegalStateException("Trying to set the device owner, but the user "
6516 + "already has a profile owner.");
6517 case CODE_USER_NOT_RUNNING:
6518 throw new IllegalStateException("User not running: " + userId);
6519 case CODE_NOT_SYSTEM_USER:
6520 throw new IllegalStateException("User is not system user");
6521 case CODE_USER_SETUP_COMPLETED:
6522 throw new IllegalStateException(
6523 "Cannot set the device owner if the device is already set-up");
6524 case CODE_NONSYSTEM_USER_EXISTS:
6525 throw new IllegalStateException("Not allowed to set the device owner because there "
6526 + "are already several users on the device");
6527 case CODE_ACCOUNTS_NOT_EMPTY:
6528 throw new IllegalStateException("Not allowed to set the device owner because there "
6529 + "are already some accounts on the device");
6530 case CODE_HAS_PAIRED:
6531 throw new IllegalStateException("Not allowed to set the device owner because this "
6532 + "device has already paired");
6534 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6538 private void enforceUserUnlocked(int userId) {
6539 // Since we're doing this operation on behalf of an app, we only
6540 // want to use the actual "unlocked" state.
6541 Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6542 "User must be running and unlocked");
6545 private void enforceUserUnlocked(int userId, boolean parent) {
6547 enforceUserUnlocked(getProfileParentId(userId));
6549 enforceUserUnlocked(userId);
6553 private void enforceManageUsers() {
6554 final int callingUid = mInjector.binderGetCallingUid();
6555 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6556 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6560 private void enforceFullCrossUsersPermission(int userHandle) {
6561 enforceSystemUserOrPermission(userHandle,
6562 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6565 private void enforceCrossUsersPermission(int userHandle) {
6566 enforceSystemUserOrPermission(userHandle,
6567 android.Manifest.permission.INTERACT_ACROSS_USERS);
6570 private void enforceSystemUserOrPermission(int userHandle, String permission) {
6571 if (userHandle < 0) {
6572 throw new IllegalArgumentException("Invalid userId " + userHandle);
6574 final int callingUid = mInjector.binderGetCallingUid();
6575 if (userHandle == UserHandle.getUserId(callingUid)) {
6578 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6579 mContext.enforceCallingOrSelfPermission(permission,
6580 "Must be system or have " + permission + " permission");
6584 private void enforceManagedProfile(int userHandle, String message) {
6585 if(!isManagedProfile(userHandle)) {
6586 throw new SecurityException("You can not " + message + " outside a managed profile.");
6590 private void enforceNotManagedProfile(int userHandle, String message) {
6591 if(isManagedProfile(userHandle)) {
6592 throw new SecurityException("You can not " + message + " for a managed profile.");
6596 private void enforceDeviceOwnerOrManageUsers() {
6597 synchronized (this) {
6598 if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6599 mInjector.binderGetCallingUid()) != null) {
6603 enforceManageUsers();
6606 private void ensureCallerPackage(@Nullable String packageName) {
6607 if (packageName == null) {
6608 Preconditions.checkState(isCallerWithSystemUid(),
6609 "Only caller can omit package name");
6611 final int callingUid = mInjector.binderGetCallingUid();
6612 final int userId = mInjector.userHandleGetCallingUserId();
6614 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6615 packageName, 0, userId);
6616 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6617 } catch (RemoteException e) {
6623 private boolean isCallerWithSystemUid() {
6624 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6627 private int getProfileParentId(int userHandle) {
6628 final long ident = mInjector.binderClearCallingIdentity();
6630 UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6631 return parentUser != null ? parentUser.id : userHandle;
6633 mInjector.binderRestoreCallingIdentity(ident);
6637 private int getCredentialOwner(int userHandle, boolean parent) {
6638 final long ident = mInjector.binderClearCallingIdentity();
6641 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6642 if (parentProfile != null) {
6643 userHandle = parentProfile.id;
6646 return mUserManager.getCredentialOwnerProfile(userHandle);
6648 mInjector.binderRestoreCallingIdentity(ident);
6652 private boolean isManagedProfile(int userHandle) {
6653 return getUserInfo(userHandle).isManagedProfile();
6656 private void enableIfNecessary(String packageName, int userId) {
6658 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6659 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6661 if (ai.enabledSetting
6662 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6663 mIPackageManager.setApplicationEnabledSetting(packageName,
6664 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6665 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6667 } catch (RemoteException e) {
6672 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6673 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6674 != PackageManager.PERMISSION_GRANTED) {
6676 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6677 + mInjector.binderGetCallingPid()
6678 + ", uid=" + mInjector.binderGetCallingUid());
6682 synchronized (this) {
6683 pw.println("Current Device Policy Manager state:");
6684 mOwners.dump(" ", pw);
6685 int userCount = mUserData.size();
6686 for (int u = 0; u < userCount; u++) {
6687 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6689 pw.println(" Enabled Device Admins (User " + policy.mUserHandle
6690 + ", provisioningState: " + policy.mUserProvisioningState + "):");
6691 final int N = policy.mAdminList.size();
6692 for (int i=0; i<N; i++) {
6693 ActiveAdmin ap = policy.mAdminList.get(i);
6695 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
6700 if (!policy.mRemovingAdmins.isEmpty()) {
6701 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
6702 + policy.mRemovingAdmins);
6706 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
6709 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6713 private String getEncryptionStatusName(int encryptionStatus) {
6714 switch (encryptionStatus) {
6715 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6717 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6718 return "block default key";
6719 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6721 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6723 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6724 return "unsupported";
6725 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6726 return "activating";
6733 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6734 ComponentName activity) {
6735 Preconditions.checkNotNull(who, "ComponentName is null");
6736 final int userHandle = UserHandle.getCallingUserId();
6737 synchronized (this) {
6738 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6740 long id = mInjector.binderClearCallingIdentity();
6742 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6743 } catch (RemoteException re) {
6746 mInjector.binderRestoreCallingIdentity(id);
6752 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6753 Preconditions.checkNotNull(who, "ComponentName is null");
6754 final int userHandle = UserHandle.getCallingUserId();
6755 synchronized (this) {
6756 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6758 long id = mInjector.binderClearCallingIdentity();
6760 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6761 } catch (RemoteException re) {
6764 mInjector.binderRestoreCallingIdentity(id);
6770 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6771 String packageName) {
6772 Preconditions.checkNotNull(admin, "ComponentName is null");
6774 final int userHandle = mInjector.userHandleGetCallingUserId();
6775 synchronized (this) {
6776 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6777 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6780 DevicePolicyData policy = getUserData(userHandle);
6781 policy.mApplicationRestrictionsManagingPackage = packageName;
6782 saveSettingsLocked(userHandle);
6788 public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6789 Preconditions.checkNotNull(admin, "ComponentName is null");
6791 final int userHandle = mInjector.userHandleGetCallingUserId();
6792 synchronized (this) {
6793 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6794 DevicePolicyData policy = getUserData(userHandle);
6795 return policy.mApplicationRestrictionsManagingPackage;
6800 public boolean isCallerApplicationRestrictionsManagingPackage() {
6801 final int callingUid = mInjector.binderGetCallingUid();
6802 final int userHandle = UserHandle.getUserId(callingUid);
6803 synchronized (this) {
6804 final DevicePolicyData policy = getUserData(userHandle);
6805 if (policy.mApplicationRestrictionsManagingPackage == null) {
6810 int uid = mContext.getPackageManager().getPackageUidAsUser(
6811 policy.mApplicationRestrictionsManagingPackage, userHandle);
6812 return uid == callingUid;
6813 } catch (NameNotFoundException e) {
6819 private void enforceCanManageApplicationRestrictions(ComponentName who) {
6821 synchronized (this) {
6822 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6824 } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6825 throw new SecurityException(
6826 "No admin component given, and caller cannot manage application restrictions "
6827 + "for other apps.");
6832 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6833 enforceCanManageApplicationRestrictions(who);
6835 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6836 final long id = mInjector.binderClearCallingIdentity();
6838 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6840 mInjector.binderRestoreCallingIdentity(id);
6845 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6846 PersistableBundle args, boolean parent) {
6850 Preconditions.checkNotNull(admin, "admin is null");
6851 Preconditions.checkNotNull(agent, "agent is null");
6852 final int userHandle = UserHandle.getCallingUserId();
6853 synchronized (this) {
6854 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6855 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6856 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6857 saveSettingsLocked(userHandle);
6862 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6863 ComponentName agent, int userHandle, boolean parent) {
6867 Preconditions.checkNotNull(agent, "agent null");
6868 enforceFullCrossUsersPermission(userHandle);
6870 synchronized (this) {
6871 final String componentName = agent.flattenToString();
6872 if (admin != null) {
6873 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6874 if (ap == null) return null;
6875 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6876 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6877 List<PersistableBundle> result = new ArrayList<>();
6878 result.add(trustAgentInfo.options);
6882 // Return strictest policy for this user and profiles that are visible from this user.
6883 List<PersistableBundle> result = null;
6884 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6885 // of the options. If any admin doesn't have options, discard options for the rest
6887 List<ActiveAdmin> admins =
6888 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6889 boolean allAdminsHaveOptions = true;
6890 final int N = admins.size();
6891 for (int i = 0; i < N; i++) {
6892 final ActiveAdmin active = admins.get(i);
6894 final boolean disablesTrust = (active.disabledKeyguardFeatures
6895 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6896 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6897 if (info != null && info.options != null && !info.options.isEmpty()) {
6898 if (disablesTrust) {
6899 if (result == null) {
6900 result = new ArrayList<>();
6902 result.add(info.options);
6904 Log.w(LOG_TAG, "Ignoring admin " + active.info
6905 + " because it has trust options but doesn't declare "
6906 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6908 } else if (disablesTrust) {
6909 allAdminsHaveOptions = false;
6913 return allAdminsHaveOptions ? result : null;
6918 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6919 Preconditions.checkNotNull(who, "ComponentName is null");
6920 synchronized (this) {
6921 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6923 int userHandle = UserHandle.getCallingUserId();
6924 DevicePolicyData userData = getUserData(userHandle);
6925 userData.mRestrictionsProvider = permissionProvider;
6926 saveSettingsLocked(userHandle);
6931 public ComponentName getRestrictionsProvider(int userHandle) {
6932 synchronized (this) {
6933 if (!isCallerWithSystemUid()) {
6934 throw new SecurityException("Only the system can query the permission provider");
6936 DevicePolicyData userData = getUserData(userHandle);
6937 return userData != null ? userData.mRestrictionsProvider : null;
6942 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6943 Preconditions.checkNotNull(who, "ComponentName is null");
6944 int callingUserId = UserHandle.getCallingUserId();
6945 synchronized (this) {
6946 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6948 long id = mInjector.binderClearCallingIdentity();
6950 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6951 if (parent == null) {
6952 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6956 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6957 mIPackageManager.addCrossProfileIntentFilter(
6958 filter, who.getPackageName(), callingUserId, parent.id, 0);
6960 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6961 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6962 parent.id, callingUserId, 0);
6964 } catch (RemoteException re) {
6967 mInjector.binderRestoreCallingIdentity(id);
6973 public void clearCrossProfileIntentFilters(ComponentName who) {
6974 Preconditions.checkNotNull(who, "ComponentName is null");
6975 int callingUserId = UserHandle.getCallingUserId();
6976 synchronized (this) {
6977 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6978 long id = mInjector.binderClearCallingIdentity();
6980 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6981 if (parent == null) {
6982 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6986 // Removing those that go from the managed profile to the parent.
6987 mIPackageManager.clearCrossProfileIntentFilters(
6988 callingUserId, who.getPackageName());
6989 // And those that go from the parent to the managed profile.
6990 // If we want to support multiple managed profiles, we will have to only remove
6991 // those that have callingUserId as their target.
6992 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6993 } catch (RemoteException re) {
6996 mInjector.binderRestoreCallingIdentity(id);
7002 * @return true if all packages in enabledPackages are either in the list
7003 * permittedList or are a system app.
7005 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
7006 List<String> permittedList, int userIdToCheck) {
7007 long id = mInjector.binderClearCallingIdentity();
7009 // If we have an enabled packages list for a managed profile the packages
7010 // we should check are installed for the parent user.
7011 UserInfo user = getUserInfo(userIdToCheck);
7012 if (user.isManagedProfile()) {
7013 userIdToCheck = user.profileGroupId;
7016 for (String enabledPackage : enabledPackages) {
7017 boolean systemService = false;
7019 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
7020 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
7021 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7022 } catch (RemoteException e) {
7023 Log.i(LOG_TAG, "Can't talk to package managed", e);
7025 if (!systemService && !permittedList.contains(enabledPackage)) {
7030 mInjector.binderRestoreCallingIdentity(id);
7035 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
7036 // Not using AccessibilityManager.getInstance because that guesses
7037 // at the user you require based on callingUid and caches for a given
7039 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
7040 IAccessibilityManager service = iBinder == null
7041 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
7042 return new AccessibilityManager(mContext, service, userId);
7046 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
7050 Preconditions.checkNotNull(who, "ComponentName is null");
7052 if (packageList != null) {
7053 int userId = UserHandle.getCallingUserId();
7054 List<AccessibilityServiceInfo> enabledServices = null;
7055 long id = mInjector.binderClearCallingIdentity();
7057 UserInfo user = getUserInfo(userId);
7058 if (user.isManagedProfile()) {
7059 userId = user.profileGroupId;
7061 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
7062 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
7063 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
7065 mInjector.binderRestoreCallingIdentity(id);
7068 if (enabledServices != null) {
7069 List<String> enabledPackages = new ArrayList<String>();
7070 for (AccessibilityServiceInfo service : enabledServices) {
7071 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
7073 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7075 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
7076 + "because it contains already enabled accesibility services.");
7082 synchronized (this) {
7083 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7084 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7085 admin.permittedAccessiblityServices = packageList;
7086 saveSettingsLocked(UserHandle.getCallingUserId());
7092 public List getPermittedAccessibilityServices(ComponentName who) {
7096 Preconditions.checkNotNull(who, "ComponentName is null");
7098 synchronized (this) {
7099 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7100 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7101 return admin.permittedAccessiblityServices;
7106 public List getPermittedAccessibilityServicesForUser(int userId) {
7110 synchronized (this) {
7111 List<String> result = null;
7112 // If we have multiple profiles we return the intersection of the
7113 // permitted lists. This can happen in cases where we have a device
7114 // and profile owner.
7115 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7116 for (int profileId : profileIds) {
7117 // Just loop though all admins, only device or profiles
7118 // owners can have permitted lists set.
7119 DevicePolicyData policy = getUserDataUnchecked(profileId);
7120 final int N = policy.mAdminList.size();
7121 for (int j = 0; j < N; j++) {
7122 ActiveAdmin admin = policy.mAdminList.get(j);
7123 List<String> fromAdmin = admin.permittedAccessiblityServices;
7124 if (fromAdmin != null) {
7125 if (result == null) {
7126 result = new ArrayList<>(fromAdmin);
7128 result.retainAll(fromAdmin);
7134 // If we have a permitted list add all system accessibility services.
7135 if (result != null) {
7136 long id = mInjector.binderClearCallingIdentity();
7138 UserInfo user = getUserInfo(userId);
7139 if (user.isManagedProfile()) {
7140 userId = user.profileGroupId;
7142 AccessibilityManager accessibilityManager =
7143 getAccessibilityManagerForUser(userId);
7144 List<AccessibilityServiceInfo> installedServices =
7145 accessibilityManager.getInstalledAccessibilityServiceList();
7147 if (installedServices != null) {
7148 for (AccessibilityServiceInfo service : installedServices) {
7149 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7150 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7151 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7152 result.add(serviceInfo.packageName);
7157 mInjector.binderRestoreCallingIdentity(id);
7166 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7171 Preconditions.checkNotNull(who, "ComponentName is null");
7172 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7173 if (!isCallerWithSystemUid()){
7174 throw new SecurityException(
7175 "Only the system can query if an accessibility service is disabled by admin");
7177 synchronized (this) {
7178 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7179 if (admin == null) {
7182 if (admin.permittedAccessiblityServices == null) {
7185 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7186 admin.permittedAccessiblityServices, userHandle);
7190 private boolean checkCallerIsCurrentUserOrProfile() {
7191 int callingUserId = UserHandle.getCallingUserId();
7192 long token = mInjector.binderClearCallingIdentity();
7194 UserInfo currentUser;
7195 UserInfo callingUser = getUserInfo(callingUserId);
7197 currentUser = mInjector.getIActivityManager().getCurrentUser();
7198 } catch (RemoteException e) {
7199 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7203 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7204 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7205 + "of a user that isn't the foreground user.");
7208 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7209 Slog.e(LOG_TAG, "Cannot set permitted input methods "
7210 + "of a user that isn't the foreground user.");
7214 mInjector.binderRestoreCallingIdentity(token);
7220 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7224 Preconditions.checkNotNull(who, "ComponentName is null");
7226 // TODO When InputMethodManager supports per user calls remove
7227 // this restriction.
7228 if (!checkCallerIsCurrentUserOrProfile()) {
7232 if (packageList != null) {
7233 // InputMethodManager fetches input methods for current user.
7234 // So this can only be set when calling user is the current user
7235 // or parent is current user in case of managed profiles.
7236 InputMethodManager inputMethodManager =
7237 mContext.getSystemService(InputMethodManager.class);
7238 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7240 if (enabledImes != null) {
7241 List<String> enabledPackages = new ArrayList<String>();
7242 for (InputMethodInfo ime : enabledImes) {
7243 enabledPackages.add(ime.getPackageName());
7245 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7246 mInjector.binderGetCallingUserHandle().getIdentifier())) {
7247 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7248 + "because it contains already enabled input method.");
7254 synchronized (this) {
7255 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7256 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7257 admin.permittedInputMethods = packageList;
7258 saveSettingsLocked(UserHandle.getCallingUserId());
7264 public List getPermittedInputMethods(ComponentName who) {
7268 Preconditions.checkNotNull(who, "ComponentName is null");
7270 synchronized (this) {
7271 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7272 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7273 return admin.permittedInputMethods;
7278 public List getPermittedInputMethodsForCurrentUser() {
7279 UserInfo currentUser;
7281 currentUser = mInjector.getIActivityManager().getCurrentUser();
7282 } catch (RemoteException e) {
7283 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7284 // Activity managed is dead, just allow all IMEs
7288 int userId = currentUser.id;
7289 synchronized (this) {
7290 List<String> result = null;
7291 // If we have multiple profiles we return the intersection of the
7292 // permitted lists. This can happen in cases where we have a device
7293 // and profile owner.
7294 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7295 for (int profileId : profileIds) {
7296 // Just loop though all admins, only device or profiles
7297 // owners can have permitted lists set.
7298 DevicePolicyData policy = getUserDataUnchecked(profileId);
7299 final int N = policy.mAdminList.size();
7300 for (int j = 0; j < N; j++) {
7301 ActiveAdmin admin = policy.mAdminList.get(j);
7302 List<String> fromAdmin = admin.permittedInputMethods;
7303 if (fromAdmin != null) {
7304 if (result == null) {
7305 result = new ArrayList<String>(fromAdmin);
7307 result.retainAll(fromAdmin);
7313 // If we have a permitted list add all system input methods.
7314 if (result != null) {
7315 InputMethodManager inputMethodManager =
7316 mContext.getSystemService(InputMethodManager.class);
7317 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7318 long id = mInjector.binderClearCallingIdentity();
7321 for (InputMethodInfo ime : imes) {
7322 ServiceInfo serviceInfo = ime.getServiceInfo();
7323 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7324 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7325 result.add(serviceInfo.packageName);
7330 mInjector.binderRestoreCallingIdentity(id);
7338 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7343 Preconditions.checkNotNull(who, "ComponentName is null");
7344 Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7345 if (!isCallerWithSystemUid()) {
7346 throw new SecurityException(
7347 "Only the system can query if an input method is disabled by admin");
7349 synchronized (this) {
7350 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7351 if (admin == null) {
7354 if (admin.permittedInputMethods == null) {
7357 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7358 admin.permittedInputMethods, userHandle);
7362 private void sendAdminEnabledBroadcastLocked(int userHandle) {
7363 DevicePolicyData policyData = getUserData(userHandle);
7364 if (policyData.mAdminBroadcastPending) {
7365 // Send the initialization data to profile owner and delete the data
7366 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7367 if (admin != null) {
7368 PersistableBundle initBundle = policyData.mInitBundle;
7369 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7370 initBundle == null ? null : new Bundle(initBundle), null);
7372 policyData.mInitBundle = null;
7373 policyData.mAdminBroadcastPending = false;
7374 saveSettingsLocked(userHandle);
7379 public UserHandle createAndManageUser(ComponentName admin, String name,
7380 ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7381 Preconditions.checkNotNull(admin, "admin is null");
7382 Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7383 if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7384 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7385 + admin + " are not in the same package");
7387 // Only allow the system user to use this method
7388 if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7389 throw new SecurityException("createAndManageUser was called from non-system user");
7391 if (!mInjector.userManagerIsSplitSystemUser()
7392 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7393 throw new IllegalArgumentException(
7394 "Ephemeral users are only supported on systems with a split system user.");
7397 UserHandle user = null;
7398 synchronized (this) {
7399 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7401 final long id = mInjector.binderClearCallingIdentity();
7403 int userInfoFlags = 0;
7404 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7405 userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7407 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7409 if (userInfo != null) {
7410 user = userInfo.getUserHandle();
7413 mInjector.binderRestoreCallingIdentity(id);
7420 final long id = mInjector.binderClearCallingIdentity();
7422 final String adminPkg = admin.getPackageName();
7424 final int userHandle = user.getIdentifier();
7426 // Install the profile owner if not present.
7427 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7428 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7430 } catch (RemoteException e) {
7431 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7432 + "removing created user", e);
7433 mUserManager.removeUser(user.getIdentifier());
7437 setActiveAdmin(profileOwner, true, userHandle);
7438 // User is not started yet, the broadcast by setActiveAdmin will not be received.
7439 // So we store adminExtras for broadcasting when the user starts for first time.
7440 synchronized(this) {
7441 DevicePolicyData policyData = getUserData(userHandle);
7442 policyData.mInitBundle = adminExtras;
7443 policyData.mAdminBroadcastPending = true;
7444 saveSettingsLocked(userHandle);
7446 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7447 setProfileOwner(profileOwner, ownerName, userHandle);
7449 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7450 Settings.Secure.putIntForUser(mContext.getContentResolver(),
7451 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7456 mInjector.binderRestoreCallingIdentity(id);
7461 public boolean removeUser(ComponentName who, UserHandle userHandle) {
7462 Preconditions.checkNotNull(who, "ComponentName is null");
7463 synchronized (this) {
7464 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7466 long id = mInjector.binderClearCallingIdentity();
7468 return mUserManager.removeUser(userHandle.getIdentifier());
7470 mInjector.binderRestoreCallingIdentity(id);
7476 public boolean switchUser(ComponentName who, UserHandle userHandle) {
7477 Preconditions.checkNotNull(who, "ComponentName is null");
7478 synchronized (this) {
7479 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7481 long id = mInjector.binderClearCallingIdentity();
7483 int userId = UserHandle.USER_SYSTEM;
7484 if (userHandle != null) {
7485 userId = userHandle.getIdentifier();
7487 return mInjector.getIActivityManager().switchUser(userId);
7488 } catch (RemoteException e) {
7489 Log.e(LOG_TAG, "Couldn't switch user", e);
7492 mInjector.binderRestoreCallingIdentity(id);
7498 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7499 enforceCanManageApplicationRestrictions(who);
7501 final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7502 final long id = mInjector.binderClearCallingIdentity();
7504 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7505 // if no restrictions were saved, mUserManager.getApplicationRestrictions
7506 // returns null, but DPM method should return an empty Bundle as per JavaDoc
7507 return bundle != null ? bundle : Bundle.EMPTY;
7509 mInjector.binderRestoreCallingIdentity(id);
7514 public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7515 boolean suspended) {
7516 Preconditions.checkNotNull(who, "ComponentName is null");
7517 int callingUserId = UserHandle.getCallingUserId();
7518 synchronized (this) {
7519 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7521 long id = mInjector.binderClearCallingIdentity();
7523 return mIPackageManager.setPackagesSuspendedAsUser(
7524 packageNames, suspended, callingUserId);
7525 } catch (RemoteException re) {
7526 // Shouldn't happen.
7527 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7529 mInjector.binderRestoreCallingIdentity(id);
7531 return packageNames;
7536 public boolean isPackageSuspended(ComponentName who, String packageName) {
7537 Preconditions.checkNotNull(who, "ComponentName is null");
7538 int callingUserId = UserHandle.getCallingUserId();
7539 synchronized (this) {
7540 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7542 long id = mInjector.binderClearCallingIdentity();
7544 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7545 } catch (RemoteException re) {
7546 // Shouldn't happen.
7547 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7549 mInjector.binderRestoreCallingIdentity(id);
7556 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7557 Preconditions.checkNotNull(who, "ComponentName is null");
7558 if (!UserRestrictionsUtils.isValidRestriction(key)) {
7562 final int userHandle = mInjector.userHandleGetCallingUserId();
7563 synchronized (this) {
7564 ActiveAdmin activeAdmin =
7565 getActiveAdminForCallerLocked(who,
7566 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7567 final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7568 if (isDeviceOwner) {
7569 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7570 throw new SecurityException("Device owner cannot set user restriction " + key);
7572 } else { // profile owner
7573 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7574 throw new SecurityException("Profile owner cannot set user restriction " + key);
7578 // Save the restriction to ActiveAdmin.
7579 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7580 saveSettingsLocked(userHandle);
7582 pushUserRestrictions(userHandle);
7584 sendChangedNotification(userHandle);
7588 private void pushUserRestrictions(int userId) {
7589 synchronized (this) {
7590 final Bundle global;
7591 final Bundle local = new Bundle();
7592 if (mOwners.isDeviceOwnerUserId(userId)) {
7593 global = new Bundle();
7595 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7596 if (deviceOwner == null) {
7597 return; // Shouldn't happen.
7600 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7602 // DO can disable camera globally.
7603 if (deviceOwner.disableCamera) {
7604 global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7609 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7610 if (profileOwner != null) {
7611 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7614 // Also merge in *local* camera restriction.
7615 if (getCameraDisabled(/* who= */ null,
7616 userId, /* mergeDeviceOwnerRestriction= */ false)) {
7617 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7619 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7624 public Bundle getUserRestrictions(ComponentName who) {
7628 Preconditions.checkNotNull(who, "ComponentName is null");
7629 synchronized (this) {
7630 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7631 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7632 return activeAdmin.userRestrictions;
7637 public boolean setApplicationHidden(ComponentName who, String packageName,
7639 Preconditions.checkNotNull(who, "ComponentName is null");
7640 int callingUserId = UserHandle.getCallingUserId();
7641 synchronized (this) {
7642 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7644 long id = mInjector.binderClearCallingIdentity();
7646 return mIPackageManager.setApplicationHiddenSettingAsUser(
7647 packageName, hidden, callingUserId);
7648 } catch (RemoteException re) {
7650 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7652 mInjector.binderRestoreCallingIdentity(id);
7659 public boolean isApplicationHidden(ComponentName who, String packageName) {
7660 Preconditions.checkNotNull(who, "ComponentName is null");
7661 int callingUserId = UserHandle.getCallingUserId();
7662 synchronized (this) {
7663 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7665 long id = mInjector.binderClearCallingIdentity();
7667 return mIPackageManager.getApplicationHiddenSettingAsUser(
7668 packageName, callingUserId);
7669 } catch (RemoteException re) {
7671 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7673 mInjector.binderRestoreCallingIdentity(id);
7680 public void enableSystemApp(ComponentName who, String packageName) {
7681 Preconditions.checkNotNull(who, "ComponentName is null");
7682 synchronized (this) {
7683 // This API can only be called by an active device admin,
7684 // so try to retrieve it to check that the caller is one.
7685 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7687 int userId = UserHandle.getCallingUserId();
7688 long id = mInjector.binderClearCallingIdentity();
7692 Slog.v(LOG_TAG, "installing " + packageName + " for "
7696 int parentUserId = getProfileParentId(userId);
7697 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7698 throw new IllegalArgumentException("Only system apps can be enabled this way.");
7702 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7704 } catch (RemoteException re) {
7706 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7708 mInjector.binderRestoreCallingIdentity(id);
7714 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7715 Preconditions.checkNotNull(who, "ComponentName is null");
7716 synchronized (this) {
7717 // This API can only be called by an active device admin,
7718 // so try to retrieve it to check that the caller is one.
7719 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7721 int userId = UserHandle.getCallingUserId();
7722 long id = mInjector.binderClearCallingIdentity();
7725 int parentUserId = getProfileParentId(userId);
7726 List<ResolveInfo> activitiesToEnable = mIPackageManager
7727 .queryIntentActivities(intent,
7728 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7729 PackageManager.MATCH_DIRECT_BOOT_AWARE
7730 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7735 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7737 int numberOfAppsInstalled = 0;
7738 if (activitiesToEnable != null) {
7739 for (ResolveInfo info : activitiesToEnable) {
7740 if (info.activityInfo != null) {
7741 String packageName = info.activityInfo.packageName;
7742 if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7743 numberOfAppsInstalled++;
7744 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7746 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7752 return numberOfAppsInstalled;
7753 } catch (RemoteException e) {
7755 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7758 mInjector.binderRestoreCallingIdentity(id);
7763 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7764 throws RemoteException {
7765 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7767 if (appInfo == null) {
7768 throw new IllegalArgumentException("The application " + packageName +
7769 " is not present on this device");
7771 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7775 public void setAccountManagementDisabled(ComponentName who, String accountType,
7780 Preconditions.checkNotNull(who, "ComponentName is null");
7781 synchronized (this) {
7782 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7783 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7785 ap.accountTypesWithManagementDisabled.add(accountType);
7787 ap.accountTypesWithManagementDisabled.remove(accountType);
7789 saveSettingsLocked(UserHandle.getCallingUserId());
7794 public String[] getAccountTypesWithManagementDisabled() {
7795 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7799 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7800 enforceFullCrossUsersPermission(userId);
7804 synchronized (this) {
7805 DevicePolicyData policy = getUserData(userId);
7806 final int N = policy.mAdminList.size();
7807 ArraySet<String> resultSet = new ArraySet<>();
7808 for (int i = 0; i < N; i++) {
7809 ActiveAdmin admin = policy.mAdminList.get(i);
7810 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7812 return resultSet.toArray(new String[resultSet.size()]);
7817 public void setUninstallBlocked(ComponentName who, String packageName,
7818 boolean uninstallBlocked) {
7819 Preconditions.checkNotNull(who, "ComponentName is null");
7820 final int userId = UserHandle.getCallingUserId();
7821 synchronized (this) {
7822 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7824 long id = mInjector.binderClearCallingIdentity();
7826 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7827 } catch (RemoteException re) {
7828 // Shouldn't happen.
7829 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7831 mInjector.binderRestoreCallingIdentity(id);
7837 public boolean isUninstallBlocked(ComponentName who, String packageName) {
7838 // This function should return true if and only if the package is blocked by
7839 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7840 // when the package is a system app, or when it is an active device admin.
7841 final int userId = UserHandle.getCallingUserId();
7843 synchronized (this) {
7845 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7848 long id = mInjector.binderClearCallingIdentity();
7850 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7851 } catch (RemoteException re) {
7852 // Shouldn't happen.
7853 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7855 mInjector.binderRestoreCallingIdentity(id);
7862 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7866 Preconditions.checkNotNull(who, "ComponentName is null");
7867 synchronized (this) {
7868 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7869 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7870 if (admin.disableCallerId != disabled) {
7871 admin.disableCallerId = disabled;
7872 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7878 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7882 Preconditions.checkNotNull(who, "ComponentName is null");
7883 synchronized (this) {
7884 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7885 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7886 return admin.disableCallerId;
7891 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7892 enforceCrossUsersPermission(userId);
7893 synchronized (this) {
7894 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7895 return (admin != null) ? admin.disableCallerId : false;
7900 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7904 Preconditions.checkNotNull(who, "ComponentName is null");
7905 synchronized (this) {
7906 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7907 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7908 if (admin.disableContactsSearch != disabled) {
7909 admin.disableContactsSearch = disabled;
7910 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7916 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7920 Preconditions.checkNotNull(who, "ComponentName is null");
7921 synchronized (this) {
7922 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7923 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7924 return admin.disableContactsSearch;
7929 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7930 enforceCrossUsersPermission(userId);
7931 synchronized (this) {
7932 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7933 return (admin != null) ? admin.disableContactsSearch : false;
7938 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7939 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7940 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7941 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7942 final int callingUserId = UserHandle.getCallingUserId();
7944 final long ident = mInjector.binderClearCallingIdentity();
7946 synchronized (this) {
7947 final int managedUserId = getManagedUserId(callingUserId);
7948 if (managedUserId < 0) {
7951 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7954 "Cross-profile contacts access disabled for user " + managedUserId);
7958 ContactsInternal.startQuickContactWithErrorToastForUser(
7959 mContext, intent, new UserHandle(managedUserId));
7962 mInjector.binderRestoreCallingIdentity(ident);
7967 * @return true if cross-profile QuickContact is disabled
7969 private boolean isCrossProfileQuickContactDisabled(int userId) {
7970 return getCrossProfileCallerIdDisabledForUser(userId)
7971 && getCrossProfileContactsSearchDisabledForUser(userId);
7975 * @return the user ID of the managed user that is linked to the current user, if any.
7978 public int getManagedUserId(int callingUserId) {
7980 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7983 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7984 if (ui.id == callingUserId || !ui.isManagedProfile()) {
7985 continue; // Caller user self, or not a managed profile. Skip.
7988 Log.v(LOG_TAG, "Managed user=" + ui.id);
7993 Log.v(LOG_TAG, "Managed user not found.");
7999 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
8003 Preconditions.checkNotNull(who, "ComponentName is null");
8004 synchronized (this) {
8005 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8006 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8007 if (admin.disableBluetoothContactSharing != disabled) {
8008 admin.disableBluetoothContactSharing = disabled;
8009 saveSettingsLocked(UserHandle.getCallingUserId());
8015 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
8019 Preconditions.checkNotNull(who, "ComponentName is null");
8020 synchronized (this) {
8021 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8022 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8023 return admin.disableBluetoothContactSharing;
8028 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
8029 // TODO: Should there be a check to make sure this relationship is
8030 // within a profile group?
8031 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
8032 synchronized (this) {
8033 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8034 return (admin != null) ? admin.disableBluetoothContactSharing : false;
8039 * Sets which packages may enter lock task mode.
8041 * <p>This function can only be called by the device owner or alternatively by the profile owner
8042 * in case the user is affiliated.
8044 * @param packages The list of packages allowed to enter lock task mode.
8047 public void setLockTaskPackages(ComponentName who, String[] packages)
8048 throws SecurityException {
8049 Preconditions.checkNotNull(who, "ComponentName is null");
8050 synchronized (this) {
8051 ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
8052 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
8053 ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
8054 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
8055 if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
8056 int userHandle = mInjector.userHandleGetCallingUserId();
8057 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
8059 throw new SecurityException("Admin " + who +
8060 " is neither the device owner or affiliated user's profile owner.");
8065 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
8066 DevicePolicyData policy = getUserData(userHandle);
8067 policy.mLockTaskPackages = packages;
8069 // Store the settings persistently.
8070 saveSettingsLocked(userHandle);
8071 updateLockTaskPackagesLocked(packages, userHandle);
8075 * This function returns the list of components allowed to start the task lock mode.
8078 public String[] getLockTaskPackages(ComponentName who) {
8079 Preconditions.checkNotNull(who, "ComponentName is null");
8080 synchronized (this) {
8081 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8082 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
8083 final List<String> packages = getLockTaskPackagesLocked(userHandle);
8084 return packages.toArray(new String[packages.size()]);
8088 private List<String> getLockTaskPackagesLocked(int userHandle) {
8089 final DevicePolicyData policy = getUserData(userHandle);
8090 return policy.mLockTaskPackages;
8094 * This function lets the caller know whether the given package is allowed to start the
8096 * @param pkg The package to check
8099 public boolean isLockTaskPermitted(String pkg) {
8100 // Get current user's devicepolicy
8101 int uid = mInjector.binderGetCallingUid();
8102 int userHandle = UserHandle.getUserId(uid);
8103 DevicePolicyData policy = getUserData(userHandle);
8104 synchronized (this) {
8105 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
8106 String lockTaskPackage = policy.mLockTaskPackages.get(i);
8108 // If the given package equals one of the packages stored our list,
8109 // we allow this package to start lock task mode.
8110 if (lockTaskPackage.equals(pkg)) {
8119 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
8120 if (!isCallerWithSystemUid()) {
8121 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
8123 synchronized (this) {
8124 final DevicePolicyData policy = getUserData(userHandle);
8125 Bundle adminExtras = new Bundle();
8126 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
8127 for (ActiveAdmin admin : policy.mAdminList) {
8128 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
8129 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
8130 if (ownsDevice || ownsProfile) {
8132 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
8135 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
8143 public void setGlobalSetting(ComponentName who, String setting, String value) {
8144 Preconditions.checkNotNull(who, "ComponentName is null");
8146 synchronized (this) {
8147 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8149 // Some settings are no supported any more. However we do not want to throw a
8150 // SecurityException to avoid breaking apps.
8151 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
8152 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
8156 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
8157 throw new SecurityException(String.format(
8158 "Permission denial: device owners cannot update %1$s", setting));
8161 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
8162 // ignore if it contradicts an existing policy
8163 long timeMs = getMaximumTimeToLock(
8164 who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
8165 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
8170 long id = mInjector.binderClearCallingIdentity();
8172 mInjector.settingsGlobalPutString(setting, value);
8174 mInjector.binderRestoreCallingIdentity(id);
8180 public void setSecureSetting(ComponentName who, String setting, String value) {
8181 Preconditions.checkNotNull(who, "ComponentName is null");
8182 int callingUserId = mInjector.userHandleGetCallingUserId();
8184 synchronized (this) {
8185 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8187 if (isDeviceOwner(who, callingUserId)) {
8188 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
8189 throw new SecurityException(String.format(
8190 "Permission denial: Device owners cannot update %1$s", setting));
8192 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
8193 throw new SecurityException(String.format(
8194 "Permission denial: Profile owners cannot update %1$s", setting));
8197 long id = mInjector.binderClearCallingIdentity();
8199 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
8201 mInjector.binderRestoreCallingIdentity(id);
8207 public void setMasterVolumeMuted(ComponentName who, boolean on) {
8208 Preconditions.checkNotNull(who, "ComponentName is null");
8209 synchronized (this) {
8210 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8211 setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
8216 public boolean isMasterVolumeMuted(ComponentName who) {
8217 Preconditions.checkNotNull(who, "ComponentName is null");
8218 synchronized (this) {
8219 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8221 AudioManager audioManager =
8222 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
8223 return audioManager.isMasterMute();
8228 public void setUserIcon(ComponentName who, Bitmap icon) {
8229 synchronized (this) {
8230 Preconditions.checkNotNull(who, "ComponentName is null");
8231 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8233 int userId = UserHandle.getCallingUserId();
8234 long id = mInjector.binderClearCallingIdentity();
8236 mUserManagerInternal.setUserIcon(userId, icon);
8238 mInjector.binderRestoreCallingIdentity(id);
8244 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8245 Preconditions.checkNotNull(who, "ComponentName is null");
8246 synchronized (this) {
8247 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8249 final int userId = UserHandle.getCallingUserId();
8251 long ident = mInjector.binderClearCallingIdentity();
8253 // disallow disabling the keyguard if a password is currently set
8254 if (disabled && mLockPatternUtils.isSecure(userId)) {
8257 mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8259 mInjector.binderRestoreCallingIdentity(ident);
8265 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8266 int userId = UserHandle.getCallingUserId();
8267 synchronized (this) {
8268 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8269 DevicePolicyData policy = getUserData(userId);
8270 if (policy.mStatusBarDisabled != disabled) {
8271 if (!setStatusBarDisabledInternal(disabled, userId)) {
8274 policy.mStatusBarDisabled = disabled;
8275 saveSettingsLocked(userId);
8281 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8282 long ident = mInjector.binderClearCallingIdentity();
8284 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8285 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8286 if (statusBarService != null) {
8287 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8288 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8289 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8290 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8293 } catch (RemoteException e) {
8294 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8296 mInjector.binderRestoreCallingIdentity(ident);
8302 * We need to update the internal state of whether a user has completed setup or a
8303 * device has paired once. After that, we ignore any changes that reset the
8304 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
8305 * as we don't trust any apps that might try to reset them.
8307 * Unfortunately, we don't know which user's setup state was changed, so we write all of
8310 void updateUserSetupCompleteAndPaired() {
8311 List<UserInfo> users = mUserManager.getUsers(true);
8312 final int N = users.size();
8313 for (int i = 0; i < N; i++) {
8314 int userHandle = users.get(i).id;
8315 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8317 DevicePolicyData policy = getUserData(userHandle);
8318 if (!policy.mUserSetupComplete) {
8319 policy.mUserSetupComplete = true;
8320 synchronized (this) {
8321 saveSettingsLocked(userHandle);
8325 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
8327 DevicePolicyData policy = getUserData(userHandle);
8328 if (!policy.mPaired) {
8329 policy.mPaired = true;
8330 synchronized (this) {
8331 saveSettingsLocked(userHandle);
8338 private class SetupContentObserver extends ContentObserver {
8340 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8341 Settings.Secure.USER_SETUP_COMPLETE);
8342 private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8343 Settings.Global.DEVICE_PROVISIONED);
8344 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
8346 public SetupContentObserver(Handler handler) {
8351 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8352 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8354 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
8359 public void onChange(boolean selfChange, Uri uri) {
8360 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
8361 updateUserSetupCompleteAndPaired();
8362 } else if (mDeviceProvisioned.equals(uri)) {
8363 synchronized (DevicePolicyManagerService.this) {
8364 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8365 // is delayed until device is marked as provisioned.
8366 setDeviceOwnerSystemPropertyLocked();
8373 final class LocalService extends DevicePolicyManagerInternal {
8374 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8377 public List<String> getCrossProfileWidgetProviders(int profileId) {
8378 synchronized (DevicePolicyManagerService.this) {
8379 if (mOwners == null) {
8380 return Collections.emptyList();
8382 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8383 if (ownerComponent == null) {
8384 return Collections.emptyList();
8387 DevicePolicyData policy = getUserDataUnchecked(profileId);
8388 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8390 if (admin == null || admin.crossProfileWidgetProviders == null
8391 || admin.crossProfileWidgetProviders.isEmpty()) {
8392 return Collections.emptyList();
8395 return admin.crossProfileWidgetProviders;
8400 public void addOnCrossProfileWidgetProvidersChangeListener(
8401 OnCrossProfileWidgetProvidersChangeListener listener) {
8402 synchronized (DevicePolicyManagerService.this) {
8403 if (mWidgetProviderListeners == null) {
8404 mWidgetProviderListeners = new ArrayList<>();
8406 if (!mWidgetProviderListeners.contains(listener)) {
8407 mWidgetProviderListeners.add(listener);
8413 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8414 synchronized(DevicePolicyManagerService.this) {
8415 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8419 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8420 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8421 synchronized (DevicePolicyManagerService.this) {
8422 listeners = new ArrayList<>(mWidgetProviderListeners);
8424 final int listenerCount = listeners.size();
8425 for (int i = 0; i < listenerCount; i++) {
8426 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8427 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8432 public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
8433 Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8434 intent.putExtra(Intent.EXTRA_USER_ID, userId);
8435 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8437 // This method is called from AM with its lock held, so don't take the DPMS lock.
8440 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8441 if (profileOwner != null) {
8442 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
8446 final Pair<Integer, ComponentName> deviceOwner =
8447 mOwners.getDeviceOwnerUserIdAndComponent();
8448 if (deviceOwner != null && deviceOwner.first == userId) {
8449 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
8453 // We're not specifying the device admin because there isn't one.
8459 * Returns true if specified admin is allowed to limit passwords and has a
8460 * {@code passwordQuality} of at least {@code minPasswordQuality}
8462 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8463 if (admin.passwordQuality < minPasswordQuality) {
8466 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8470 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8471 if (policy != null && !policy.isValid()) {
8472 throw new IllegalArgumentException("Invalid system update policy.");
8474 synchronized (this) {
8475 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8476 if (policy == null) {
8477 mOwners.clearSystemUpdatePolicy();
8479 mOwners.setSystemUpdatePolicy(policy);
8481 mOwners.writeDeviceOwner();
8483 mContext.sendBroadcastAsUser(
8484 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8489 public SystemUpdatePolicy getSystemUpdatePolicy() {
8490 if (UserManager.isDeviceInDemoMode(mContext)) {
8491 // Pretending to have an automatic update policy when the device is in retail demo
8492 // mode. This will allow the device to download and install an ota without
8493 // any user interaction.
8494 return SystemUpdatePolicy.createAutomaticInstallPolicy();
8496 synchronized (this) {
8497 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
8498 if (policy != null && !policy.isValid()) {
8499 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8507 * Checks if the caller of the method is the device owner app.
8509 * @param callerUid UID of the caller.
8510 * @return true if the caller is the device owner app
8513 boolean isCallerDeviceOwner(int callerUid) {
8514 synchronized (this) {
8515 if (!mOwners.hasDeviceOwner()) {
8518 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8521 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8523 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8525 for (String pkg : pkgs) {
8526 if (deviceOwnerPackageName.equals(pkg)) {
8536 public void notifyPendingSystemUpdate(long updateReceivedTime) {
8537 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8538 "Only the system update service can broadcast update information");
8540 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8541 Slog.w(LOG_TAG, "Only the system update service in the system user " +
8542 "can broadcast update information.");
8545 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8546 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8547 updateReceivedTime);
8549 synchronized (this) {
8550 final String deviceOwnerPackage =
8551 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8553 if (deviceOwnerPackage == null) {
8556 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8558 ActivityInfo[] receivers = null;
8560 receivers = mContext.getPackageManager().getPackageInfo(
8561 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8562 } catch (NameNotFoundException e) {
8563 Log.e(LOG_TAG, "Cannot find device owner package", e);
8565 if (receivers != null) {
8566 long ident = mInjector.binderClearCallingIdentity();
8568 for (int i = 0; i < receivers.length; i++) {
8569 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8570 intent.setComponent(new ComponentName(deviceOwnerPackage,
8571 receivers[i].name));
8572 mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8576 mInjector.binderRestoreCallingIdentity(ident);
8583 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8584 int userId = UserHandle.getCallingUserId();
8585 synchronized (this) {
8586 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8587 DevicePolicyData userPolicy = getUserData(userId);
8588 if (userPolicy.mPermissionPolicy != policy) {
8589 userPolicy.mPermissionPolicy = policy;
8590 saveSettingsLocked(userId);
8596 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8597 int userId = UserHandle.getCallingUserId();
8598 synchronized (this) {
8599 DevicePolicyData userPolicy = getUserData(userId);
8600 return userPolicy.mPermissionPolicy;
8605 public boolean setPermissionGrantState(ComponentName admin, String packageName,
8606 String permission, int grantState) throws RemoteException {
8607 UserHandle user = mInjector.binderGetCallingUserHandle();
8608 synchronized (this) {
8609 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8610 long ident = mInjector.binderClearCallingIdentity();
8612 if (getTargetSdk(packageName, user.getIdentifier())
8613 < android.os.Build.VERSION_CODES.M) {
8616 final PackageManager packageManager = mContext.getPackageManager();
8617 switch (grantState) {
8618 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8619 packageManager.grantRuntimePermission(packageName, permission, user);
8620 packageManager.updatePermissionFlags(permission, packageName,
8621 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8622 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8625 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8626 packageManager.revokeRuntimePermission(packageName,
8628 packageManager.updatePermissionFlags(permission, packageName,
8629 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8630 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8633 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8634 packageManager.updatePermissionFlags(permission, packageName,
8635 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8639 } catch (SecurityException se) {
8642 mInjector.binderRestoreCallingIdentity(ident);
8648 public int getPermissionGrantState(ComponentName admin, String packageName,
8649 String permission) throws RemoteException {
8650 PackageManager packageManager = mContext.getPackageManager();
8652 UserHandle user = mInjector.binderGetCallingUserHandle();
8653 synchronized (this) {
8654 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8655 long ident = mInjector.binderClearCallingIdentity();
8657 int granted = mIPackageManager.checkPermission(permission,
8658 packageName, user.getIdentifier());
8659 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8660 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8661 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8662 // Not controlled by policy
8663 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8665 // Policy controlled so return result based on permission grant state
8666 return granted == PackageManager.PERMISSION_GRANTED
8667 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8668 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8671 mInjector.binderRestoreCallingIdentity(ident);
8676 boolean isPackageInstalledForUser(String packageName, int userHandle) {
8678 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8680 return (pi != null) && (pi.applicationInfo.flags != 0);
8681 } catch (RemoteException re) {
8682 throw new RuntimeException("Package manager has died", re);
8687 public boolean isProvisioningAllowed(String action) {
8692 final int callingUserId = mInjector.userHandleGetCallingUserId();
8693 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8694 if (!hasFeatureManagedUsers()) {
8697 synchronized (this) {
8698 if (mOwners.hasDeviceOwner()) {
8699 if (!mInjector.userManagerIsSplitSystemUser()) {
8700 // Only split-system-user systems support managed-profiles in combination with
8704 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8705 // Only system device-owner supports managed-profiles. Non-system device-owner
8709 if (callingUserId == UserHandle.USER_SYSTEM) {
8710 // Managed-profiles cannot be setup on the system user, only regular users.
8715 if (getProfileOwner(callingUserId) != null) {
8716 // Managed user cannot have a managed profile.
8719 final long ident = mInjector.binderClearCallingIdentity();
8721 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8725 mInjector.binderRestoreCallingIdentity(ident);
8728 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8729 return isDeviceOwnerProvisioningAllowed(callingUserId);
8730 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8731 if (!hasFeatureManagedUsers()) {
8734 if (!mInjector.userManagerIsSplitSystemUser()) {
8735 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8738 if (callingUserId == UserHandle.USER_SYSTEM) {
8739 // System user cannot be a managed user.
8742 if (hasUserSetupCompleted(callingUserId)) {
8745 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8749 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8750 if (!mInjector.userManagerIsSplitSystemUser()) {
8751 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8754 return isDeviceOwnerProvisioningAllowed(callingUserId);
8756 throw new IllegalArgumentException("Unknown provisioning action " + action);
8760 * The device owner can only be set before the setup phase of the primary user has completed,
8761 * except for adb command if no accounts or additional users are present on the device.
8763 private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreConditionLocked(
8764 @Nullable ComponentName owner, int deviceOwnerUserId, boolean isAdb,
8765 boolean hasIncompatibleAccountsOrNonAdb) {
8766 if (mOwners.hasDeviceOwner()) {
8767 return CODE_HAS_DEVICE_OWNER;
8769 if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8770 return CODE_USER_HAS_PROFILE_OWNER;
8772 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8773 return CODE_USER_NOT_RUNNING;
8775 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8776 return CODE_HAS_PAIRED;
8779 // if shell command runs after user setup completed check device status. Otherwise, OK.
8780 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8781 if (!mInjector.userManagerIsSplitSystemUser()) {
8782 if (mUserManager.getUserCount() > 1) {
8783 return CODE_NONSYSTEM_USER_EXISTS;
8785 if (hasIncompatibleAccountsOrNonAdb) {
8786 return CODE_ACCOUNTS_NOT_EMPTY;
8789 // STOPSHIP Do proper check in split user mode
8794 if (!mInjector.userManagerIsSplitSystemUser()) {
8795 // In non-split user mode, DO has to be user 0
8796 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8797 return CODE_NOT_SYSTEM_USER;
8799 // In non-split user mode, only provision DO before setup wizard completes
8800 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8801 return CODE_USER_SETUP_COMPLETED;
8804 // STOPSHIP Do proper check in split user mode
8810 private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8811 synchronized (this) {
8812 return CODE_OK == checkSetDeviceOwnerPreConditionLocked(
8813 /* owner unknown */ null, deviceOwnerUserId, /* isAdb */ false,
8814 /* hasIncompatibleAccountsOrNonAdb=*/ true);
8818 private boolean hasFeatureManagedUsers() {
8820 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8821 } catch (RemoteException e) {
8827 public String getWifiMacAddress(ComponentName admin) {
8828 // Make sure caller has DO.
8829 synchronized (this) {
8830 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8833 final long ident = mInjector.binderClearCallingIdentity();
8835 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8836 if (wifiInfo == null) {
8839 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8841 mInjector.binderRestoreCallingIdentity(ident);
8846 * Returns the target sdk version number that the given packageName was built for
8847 * in the given user.
8849 private int getTargetSdk(String packageName, int userId) {
8850 final ApplicationInfo ai;
8852 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8853 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8854 return targetSdkVersion;
8855 } catch (RemoteException e) {
8862 public boolean isManagedProfile(ComponentName admin) {
8863 synchronized (this) {
8864 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8866 final int callingUserId = mInjector.userHandleGetCallingUserId();
8867 final UserInfo user = getUserInfo(callingUserId);
8868 return user != null && user.isManagedProfile();
8872 public boolean isSystemOnlyUser(ComponentName admin) {
8873 synchronized (this) {
8874 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8876 final int callingUserId = mInjector.userHandleGetCallingUserId();
8877 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8881 public void reboot(ComponentName admin) {
8882 Preconditions.checkNotNull(admin);
8883 // Make sure caller has DO.
8884 synchronized (this) {
8885 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8887 long ident = mInjector.binderClearCallingIdentity();
8889 // Make sure there are no ongoing calls on the device.
8890 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8891 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8893 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8895 mInjector.binderRestoreCallingIdentity(ident);
8900 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8904 Preconditions.checkNotNull(who, "ComponentName is null");
8905 final int userHandle = mInjector.userHandleGetCallingUserId();
8906 synchronized (this) {
8907 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8908 mInjector.binderGetCallingUid());
8909 if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8910 admin.shortSupportMessage = message;
8911 saveSettingsLocked(userHandle);
8917 public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8921 Preconditions.checkNotNull(who, "ComponentName is null");
8922 synchronized (this) {
8923 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8924 mInjector.binderGetCallingUid());
8925 return admin.shortSupportMessage;
8930 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8934 Preconditions.checkNotNull(who, "ComponentName is null");
8935 final int userHandle = mInjector.userHandleGetCallingUserId();
8936 synchronized (this) {
8937 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8938 mInjector.binderGetCallingUid());
8939 if (!TextUtils.equals(admin.longSupportMessage, message)) {
8940 admin.longSupportMessage = message;
8941 saveSettingsLocked(userHandle);
8947 public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8951 Preconditions.checkNotNull(who, "ComponentName is null");
8952 synchronized (this) {
8953 ActiveAdmin admin = getActiveAdminForUidLocked(who,
8954 mInjector.binderGetCallingUid());
8955 return admin.longSupportMessage;
8960 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8964 Preconditions.checkNotNull(who, "ComponentName is null");
8965 if (!isCallerWithSystemUid()) {
8966 throw new SecurityException("Only the system can query support message for user");
8968 synchronized (this) {
8969 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8970 if (admin != null) {
8971 return admin.shortSupportMessage;
8978 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8982 Preconditions.checkNotNull(who, "ComponentName is null");
8983 if (!isCallerWithSystemUid()) {
8984 throw new SecurityException("Only the system can query support message for user");
8986 synchronized (this) {
8987 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8988 if (admin != null) {
8989 return admin.longSupportMessage;
8996 public void setOrganizationColor(@NonNull ComponentName who, int color) {
9000 Preconditions.checkNotNull(who, "ComponentName is null");
9001 final int userHandle = mInjector.userHandleGetCallingUserId();
9002 enforceManagedProfile(userHandle, "set organization color");
9003 synchronized (this) {
9004 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9005 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9006 admin.organizationColor = color;
9007 saveSettingsLocked(userHandle);
9012 public void setOrganizationColorForUser(int color, int userId) {
9016 enforceFullCrossUsersPermission(userId);
9017 enforceManageUsers();
9018 enforceManagedProfile(userId, "set organization color");
9019 synchronized (this) {
9020 ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9021 admin.organizationColor = color;
9022 saveSettingsLocked(userId);
9027 public int getOrganizationColor(@NonNull ComponentName who) {
9029 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9031 Preconditions.checkNotNull(who, "ComponentName is null");
9032 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
9033 synchronized (this) {
9034 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9035 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9036 return admin.organizationColor;
9041 public int getOrganizationColorForUser(int userHandle) {
9043 return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9045 enforceFullCrossUsersPermission(userHandle);
9046 enforceManagedProfile(userHandle, "get organization color");
9047 synchronized (this) {
9048 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9049 return (profileOwner != null)
9050 ? profileOwner.organizationColor
9051 : ActiveAdmin.DEF_ORGANIZATION_COLOR;
9056 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
9060 Preconditions.checkNotNull(who, "ComponentName is null");
9061 final int userHandle = mInjector.userHandleGetCallingUserId();
9062 enforceManagedProfile(userHandle, "set organization name");
9063 synchronized (this) {
9064 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9065 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9066 if (!TextUtils.equals(admin.organizationName, text)) {
9067 admin.organizationName = (text == null || text.length() == 0)
9068 ? null : text.toString();
9069 saveSettingsLocked(userHandle);
9075 public CharSequence getOrganizationName(@NonNull ComponentName who) {
9079 Preconditions.checkNotNull(who, "ComponentName is null");
9080 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
9081 synchronized(this) {
9082 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9083 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9084 return admin.organizationName;
9089 public CharSequence getOrganizationNameForUser(int userHandle) {
9093 enforceFullCrossUsersPermission(userHandle);
9094 enforceManagedProfile(userHandle, "get organization name");
9095 synchronized (this) {
9096 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9097 return (profileOwner != null)
9098 ? profileOwner.organizationName
9104 public void setAffiliationIds(ComponentName admin, List<String> ids) {
9105 final Set<String> affiliationIds = new ArraySet<String>(ids);
9106 final int callingUserId = mInjector.userHandleGetCallingUserId();
9108 synchronized (this) {
9109 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9110 getUserData(callingUserId).mAffiliationIds = affiliationIds;
9111 saveSettingsLocked(callingUserId);
9112 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
9113 // Affiliation ids specified by the device owner are additionally stored in
9114 // UserHandle.USER_SYSTEM's DevicePolicyData.
9115 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
9116 saveSettingsLocked(UserHandle.USER_SYSTEM);
9122 public boolean isAffiliatedUser() {
9123 final int callingUserId = mInjector.userHandleGetCallingUserId();
9125 synchronized (this) {
9126 if (mOwners.getDeviceOwnerUserId() == callingUserId) {
9127 // The user that the DO is installed on is always affiliated.
9130 final ComponentName profileOwner = getProfileOwner(callingUserId);
9131 if (profileOwner == null
9132 || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
9135 final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
9136 final Set<String> deviceAffiliationIds =
9137 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
9138 for (String id : userAffiliationIds) {
9139 if (deviceAffiliationIds.contains(id)) {
9147 private synchronized void disableDeviceOwnerManagedSingleUserFeaturesIfNeeded() {
9148 final boolean isSingleUserManagedDevice = isDeviceOwnerManagedSingleUserDevice();
9150 // disable security logging if needed
9151 if (!isSingleUserManagedDevice) {
9152 mInjector.securityLogSetLoggingEnabledProperty(false);
9153 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user managed"
9157 // disable backup service if needed
9158 // note: when clearing DO, the backup service shouldn't be disabled if it was enabled by
9160 if (mOwners.hasDeviceOwner() && !isSingleUserManagedDevice) {
9161 setBackupServiceEnabledInternal(false);
9162 Slog.w(LOG_TAG, "Backup is off as it's a managed device that has more that one user.");
9165 // disable network logging if needed
9166 if (!isSingleUserManagedDevice) {
9167 setNetworkLoggingActiveInternal(false);
9168 Slog.w(LOG_TAG, "Network logging turned off as it's no longer a single user managed"
9170 // if there still is a device owner, disable logging policy, otherwise the admin
9172 if (mOwners.hasDeviceOwner()) {
9173 getDeviceOwnerAdminLocked().isNetworkLoggingEnabled = false;
9174 saveSettingsLocked(mOwners.getDeviceOwnerUserId());
9180 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
9181 Preconditions.checkNotNull(admin);
9182 ensureDeviceOwnerManagingSingleUser(admin);
9184 synchronized (this) {
9185 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
9188 mInjector.securityLogSetLoggingEnabledProperty(enabled);
9190 mSecurityLogMonitor.start();
9192 mSecurityLogMonitor.stop();
9198 public boolean isSecurityLoggingEnabled(ComponentName admin) {
9199 Preconditions.checkNotNull(admin);
9200 synchronized (this) {
9201 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9202 return mInjector.securityLogGetLoggingEnabledProperty();
9207 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
9208 Preconditions.checkNotNull(admin);
9209 ensureDeviceOwnerManagingSingleUser(admin);
9211 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
9215 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
9217 SecurityLog.readPreviousEvents(output);
9218 return new ParceledListSlice<SecurityEvent>(output);
9219 } catch (IOException e) {
9220 Slog.w(LOG_TAG, "Fail to read previous events" , e);
9221 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
9226 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
9227 Preconditions.checkNotNull(admin);
9228 ensureDeviceOwnerManagingSingleUser(admin);
9230 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
9231 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
9234 private void enforceCanManageDeviceAdmin() {
9235 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
9239 private void enforceCanManageProfileAndDeviceOwners() {
9240 mContext.enforceCallingOrSelfPermission(
9241 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
9245 public boolean isUninstallInQueue(final String packageName) {
9246 enforceCanManageDeviceAdmin();
9247 final int userId = mInjector.userHandleGetCallingUserId();
9248 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9249 synchronized (this) {
9250 return mPackagesToRemove.contains(packageUserPair);
9255 public void uninstallPackageWithActiveAdmins(final String packageName) {
9256 enforceCanManageDeviceAdmin();
9257 Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
9259 final int userId = mInjector.userHandleGetCallingUserId();
9261 enforceUserUnlocked(userId);
9263 final ComponentName profileOwner = getProfileOwner(userId);
9264 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
9265 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
9268 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
9269 if (getDeviceOwnerUserId() == userId && deviceOwner != null
9270 && packageName.equals(deviceOwner.getPackageName())) {
9271 throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
9274 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9275 synchronized (this) {
9276 mPackagesToRemove.add(packageUserPair);
9279 // All active admins on the user.
9280 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
9282 // Active admins in the target package.
9283 final List<ComponentName> packageActiveAdmins = new ArrayList<>();
9284 if (allActiveAdmins != null) {
9285 for (ComponentName activeAdmin : allActiveAdmins) {
9286 if (packageName.equals(activeAdmin.getPackageName())) {
9287 packageActiveAdmins.add(activeAdmin);
9288 removeActiveAdmin(activeAdmin, userId);
9292 if (packageActiveAdmins.size() == 0) {
9293 startUninstallIntent(packageName, userId);
9295 mHandler.postDelayed(new Runnable() {
9298 for (ComponentName activeAdmin : packageActiveAdmins) {
9299 removeAdminArtifacts(activeAdmin, userId);
9301 startUninstallIntent(packageName, userId);
9303 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9308 public boolean isDeviceProvisioned() {
9309 return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9312 private void removePackageIfRequired(final String packageName, final int userId) {
9313 if (!packageHasActiveAdmins(packageName, userId)) {
9314 // Will not do anything if uninstall was not requested or was already started.
9315 startUninstallIntent(packageName, userId);
9319 private void startUninstallIntent(final String packageName, final int userId) {
9320 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9321 synchronized (this) {
9322 if (!mPackagesToRemove.contains(packageUserPair)) {
9323 // Do nothing if uninstall was not requested or was already started.
9326 mPackagesToRemove.remove(packageUserPair);
9329 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9330 // Package does not exist. Nothing to do.
9333 } catch (RemoteException re) {
9334 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9337 try { // force stop the package before uninstalling
9338 mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9339 } catch (RemoteException re) {
9340 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9342 final Uri packageURI = Uri.parse("package:" + packageName);
9343 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9344 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9345 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9349 * Removes the admin from the policy. Ideally called after the admin's
9350 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9352 * @param adminReceiver The admin to remove
9353 * @param userHandle The user for which this admin has to be removed.
9355 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9356 synchronized (this) {
9357 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9358 if (admin == null) {
9361 final DevicePolicyData policy = getUserData(userHandle);
9362 final boolean doProxyCleanup = admin.info.usesPolicy(
9363 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9364 policy.mAdminList.remove(admin);
9365 policy.mAdminMap.remove(adminReceiver);
9366 validatePasswordOwnerLocked(policy);
9367 if (doProxyCleanup) {
9368 resetGlobalProxyLocked(policy);
9370 saveSettingsLocked(userHandle);
9371 updateMaximumTimeToLockLocked(userHandle);
9372 policy.mRemovingAdmins.remove(adminReceiver);
9374 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
9376 // The removed admin might have disabled camera, so update user
9378 pushUserRestrictions(userHandle);
9382 public void setDeviceProvisioningConfigApplied() {
9383 enforceManageUsers();
9384 synchronized (this) {
9385 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9386 policy.mDeviceProvisioningConfigApplied = true;
9387 saveSettingsLocked(UserHandle.USER_SYSTEM);
9392 public boolean isDeviceProvisioningConfigApplied() {
9393 enforceManageUsers();
9394 synchronized (this) {
9395 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9396 return policy.mDeviceProvisioningConfigApplied;
9401 * Return true if a given user has any accounts that'll prevent installing a device or profile
9402 * owner {@code owner}.
9403 * - If the user has no accounts, then return false.
9404 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
9405 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
9406 * ..._DISALLOWED, return true.
9407 * - Otherwise return false.
9409 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used
9410 * when the caller is not ADB.
9412 * DO NOT CALL IT WITH THE DPMS LOCK HELD.
9414 private boolean hasIncompatibleAccountsOrNonAdbNoLock(
9415 int userId, @Nullable ComponentName owner) {
9416 final boolean isAdb = (mInjector.binderGetCallingUid() == Process.SHELL_UID)
9417 || (mInjector.binderGetCallingUid() == Process.ROOT_UID);
9422 if (Thread.holdsLock(this)) {
9423 Slog.wtf(LOG_TAG, "hasIncompatibleAccountsNoLock() called with the DPMS lock held.");
9427 final long token = mInjector.binderClearCallingIdentity();
9429 final AccountManager am = AccountManager.get(mContext);
9430 final Account accounts[] = am.getAccountsAsUser(userId);
9431 if (accounts.length == 0) {
9434 synchronized (this) {
9435 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
9437 "Non test-only owner can't be installed with existing accounts.");
9442 final String[] feature_allow =
9443 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
9444 final String[] feature_disallow =
9445 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
9447 boolean compatible = true;
9448 for (Account account : accounts) {
9449 if (hasAccountFeatures(am, account, feature_disallow)) {
9450 Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
9454 if (!hasAccountFeatures(am, account, feature_allow)) {
9455 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
9461 Log.w(LOG_TAG, "All accounts are compatible");
9463 Log.e(LOG_TAG, "Found incompatible accounts");
9467 mInjector.binderRestoreCallingIdentity(token);
9471 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
9473 return am.hasFeatures(account, features, null, null).getResult();
9474 } catch (Exception e) {
9475 Log.w(LOG_TAG, "Failed to get account feature", e);
9481 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
9482 Preconditions.checkNotNull(admin);
9486 ensureDeviceOwnerManagingSingleUser(admin);
9487 setBackupServiceEnabledInternal(enabled);
9490 private synchronized void setBackupServiceEnabledInternal(boolean enabled) {
9491 long ident = mInjector.binderClearCallingIdentity();
9493 IBackupManager ibm = mInjector.getIBackupManager();
9495 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
9497 } catch (RemoteException e) {
9498 throw new IllegalStateException(
9499 "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
9501 mInjector.binderRestoreCallingIdentity(ident);
9506 public boolean isBackupServiceEnabled(ComponentName admin) {
9507 Preconditions.checkNotNull(admin);
9511 synchronized (this) {
9512 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9514 IBackupManager ibm = mInjector.getIBackupManager();
9515 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
9516 } catch (RemoteException e) {
9517 throw new IllegalStateException("Failed requesting backup service state.", e);
9523 public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
9527 Preconditions.checkNotNull(admin);
9528 ensureDeviceOwnerManagingSingleUser(admin);
9530 if (enabled == isNetworkLoggingEnabledInternalLocked()) {
9531 // already in the requested state
9534 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9535 deviceOwner.isNetworkLoggingEnabled = enabled;
9537 deviceOwner.numNetworkLoggingNotifications = 0;
9538 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
9540 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
9542 setNetworkLoggingActiveInternal(enabled);
9545 private synchronized void setNetworkLoggingActiveInternal(boolean active) {
9546 final long callingIdentity = mInjector.binderClearCallingIdentity();
9549 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
9550 if (!mNetworkLogger.startNetworkLogging()) {
9551 mNetworkLogger = null;
9552 Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
9553 + " service not being available yet.");
9555 sendNetworkLoggingNotificationLocked();
9557 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
9558 mNetworkLogger = null;
9559 Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
9560 + " service not being available yet.");
9562 mNetworkLogger = null;
9563 mInjector.getNotificationManager().cancel(NETWORK_LOGGING_NOTIFICATION_ID);
9566 mInjector.binderRestoreCallingIdentity(callingIdentity);
9571 public boolean isNetworkLoggingEnabled(ComponentName admin) {
9575 synchronized (this) {
9576 enforceDeviceOwnerOrManageUsers();
9577 return isNetworkLoggingEnabledInternalLocked();
9581 private boolean isNetworkLoggingEnabledInternalLocked() {
9582 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9583 return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
9587 * A maximum of 1200 events are returned, and the total marshalled size is in the order of
9588 * 100kB, so returning a List instead of ParceledListSlice is acceptable.
9589 * Ideally this would be done with ParceledList, however it only supports homogeneous types.
9591 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
9594 public synchronized List<NetworkEvent> retrieveNetworkLogs(ComponentName admin,
9599 Preconditions.checkNotNull(admin);
9600 ensureDeviceOwnerManagingSingleUser(admin);
9602 if (mNetworkLogger == null) {
9605 return isNetworkLoggingEnabledInternalLocked()
9606 ? mNetworkLogger.retrieveLogs(batchToken)
9610 private void sendNetworkLoggingNotificationLocked() {
9611 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9612 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
9615 if (deviceOwner.numNetworkLoggingNotifications >=
9616 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
9619 final long now = System.currentTimeMillis();
9620 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
9623 deviceOwner.numNetworkLoggingNotifications++;
9624 if (deviceOwner.numNetworkLoggingNotifications
9625 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
9626 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
9628 deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
9630 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
9631 intent.setPackage("com.android.systemui");
9632 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
9633 UserHandle.CURRENT);
9634 Notification notification = new Notification.Builder(mContext)
9635 .setSmallIcon(R.drawable.ic_qs_network_logging)
9636 .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
9637 .setContentText(mContext.getString(R.string.network_logging_notification_text))
9638 .setTicker(mContext.getString(R.string.network_logging_notification_title))
9640 .setContentIntent(pendingIntent)
9642 mInjector.getNotificationManager().notify(NETWORK_LOGGING_NOTIFICATION_ID, notification);
9643 saveSettingsLocked(mOwners.getDeviceOwnerUserId());