2 * Copyright (C) 2010 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.server.devicepolicy;
19 import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
20 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
21 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
22 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
23 import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
24 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
25 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
26 import static org.xmlpull.v1.XmlPullParser.END_TAG;
27 import static org.xmlpull.v1.XmlPullParser.TEXT;
29 import android.Manifest.permission;
30 import android.accessibilityservice.AccessibilityServiceInfo;
31 import android.accounts.AccountManager;
32 import android.app.Activity;
33 import android.app.ActivityManagerNative;
34 import android.app.AlarmManager;
35 import android.app.AppGlobals;
36 import android.app.IActivityManager;
37 import android.app.Notification;
38 import android.app.NotificationManager;
39 import android.app.PendingIntent;
40 import android.app.StatusBarManager;
41 import android.app.admin.DeviceAdminInfo;
42 import android.app.admin.DeviceAdminReceiver;
43 import android.app.admin.DevicePolicyManager;
44 import android.app.admin.DevicePolicyManagerInternal;
45 import android.app.admin.IDevicePolicyManager;
46 import android.app.admin.SystemUpdatePolicy;
47 import android.app.backup.IBackupManager;
48 import android.app.trust.TrustManager;
49 import android.content.BroadcastReceiver;
50 import android.content.ComponentName;
51 import android.content.ContentResolver;
52 import android.content.Context;
53 import android.content.Intent;
54 import android.content.IntentFilter;
55 import android.content.pm.ActivityInfo;
56 import android.content.pm.ApplicationInfo;
57 import android.content.pm.IPackageManager;
58 import android.content.pm.PackageManager;
59 import android.content.pm.PackageManager.NameNotFoundException;
60 import android.content.pm.PermissionInfo;
61 import android.content.pm.ResolveInfo;
62 import android.content.pm.ServiceInfo;
63 import android.content.pm.UserInfo;
64 import android.database.ContentObserver;
65 import android.graphics.Bitmap;
66 import android.media.AudioManager;
67 import android.media.IAudioService;
68 import android.net.ConnectivityManager;
69 import android.net.ProxyInfo;
70 import android.net.Uri;
71 import android.os.AsyncTask;
72 import android.os.Binder;
73 import android.os.Bundle;
74 import android.os.Environment;
75 import android.os.FileUtils;
76 import android.os.Handler;
77 import android.os.IBinder;
78 import android.os.PersistableBundle;
79 import android.os.PowerManager;
80 import android.os.PowerManagerInternal;
81 import android.os.Process;
82 import android.os.RecoverySystem;
83 import android.os.RemoteCallback;
84 import android.os.RemoteException;
85 import android.os.ServiceManager;
86 import android.os.SystemClock;
87 import android.os.SystemProperties;
88 import android.os.UserHandle;
89 import android.os.UserManager;
90 import android.os.storage.StorageManager;
91 import android.provider.ContactsContract.QuickContact;
92 import android.provider.ContactsInternal;
93 import android.provider.Settings;
94 import android.security.Credentials;
95 import android.security.IKeyChainAliasCallback;
96 import android.security.IKeyChainService;
97 import android.security.KeyChain;
98 import android.security.KeyChain.KeyChainConnection;
99 import android.service.persistentdata.PersistentDataBlockManager;
100 import android.text.TextUtils;
101 import android.util.EventLog;
102 import android.util.Log;
103 import android.util.PrintWriterPrinter;
104 import android.util.Printer;
105 import android.util.Slog;
106 import android.util.SparseArray;
107 import android.util.Xml;
108 import android.view.IWindowManager;
109 import android.view.accessibility.AccessibilityManager;
110 import android.view.accessibility.IAccessibilityManager;
111 import android.view.inputmethod.InputMethodInfo;
112 import android.view.inputmethod.InputMethodManager;
114 import com.android.internal.R;
115 import com.android.internal.statusbar.IStatusBarService;
116 import com.android.internal.util.FastXmlSerializer;
117 import com.android.internal.util.JournaledFile;
118 import com.android.internal.util.Preconditions;
119 import com.android.internal.util.XmlUtils;
120 import com.android.internal.widget.LockPatternUtils;
121 import com.android.server.LocalServices;
122 import com.android.server.SystemService;
123 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
125 import org.xmlpull.v1.XmlPullParser;
126 import org.xmlpull.v1.XmlPullParserException;
127 import org.xmlpull.v1.XmlSerializer;
129 import java.io.ByteArrayInputStream;
131 import java.io.FileDescriptor;
132 import java.io.FileInputStream;
133 import java.io.FileNotFoundException;
134 import java.io.FileOutputStream;
135 import java.io.IOException;
136 import java.io.PrintWriter;
137 import java.nio.charset.StandardCharsets;
138 import java.security.cert.CertificateException;
139 import java.security.cert.CertificateFactory;
140 import java.security.cert.X509Certificate;
141 import java.text.DateFormat;
142 import java.util.ArrayList;
143 import java.util.Arrays;
144 import java.util.Collections;
145 import java.util.Date;
146 import java.util.HashMap;
147 import java.util.HashSet;
148 import java.util.List;
149 import java.util.Map.Entry;
150 import java.util.Set;
153 * Implementation of the device policy APIs.
155 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
157 private static final String LOG_TAG = "DevicePolicyManagerService";
159 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
161 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
163 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
165 private static final String TAG_STATUS_BAR = "statusbar";
167 private static final String ATTR_DISABLED = "disabled";
169 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
170 "do-not-ask-credentials-on-boot";
172 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
174 private static final long MS_PER_DAY = 86400 * 1000;
176 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
178 protected static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
179 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
181 private static final int MONITORING_CERT_NOTIFICATION_ID = R.string.ssl_ca_cert_warning;
182 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
184 private static final boolean DBG = false;
186 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
187 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
188 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
190 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
192 private static final int STATUS_BAR_DISABLE_MASK =
193 StatusBarManager.DISABLE_EXPAND |
194 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
195 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
196 StatusBarManager.DISABLE_SEARCH;
198 private static final int STATUS_BAR_DISABLE2_MASK =
199 StatusBarManager.DISABLE2_QUICK_SETTINGS;
201 private static final Set<String> DEVICE_OWNER_USER_RESTRICTIONS;
203 DEVICE_OWNER_USER_RESTRICTIONS = new HashSet();
204 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_USB_FILE_TRANSFER);
205 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_TETHERING);
206 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_NETWORK_RESET);
207 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_FACTORY_RESET);
208 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADD_USER);
209 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
210 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
211 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
212 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_UNMUTE_MICROPHONE);
213 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADJUST_VOLUME);
214 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SMS);
215 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_FUN);
216 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SAFE_BOOT);
217 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CREATE_WINDOWS);
220 // The following user restrictions cannot be changed by any active admin, including device
221 // owner and profile owner.
222 private static final Set<String> IMMUTABLE_USER_RESTRICTIONS;
224 IMMUTABLE_USER_RESTRICTIONS = new HashSet();
225 IMMUTABLE_USER_RESTRICTIONS.add(UserManager.DISALLOW_WALLPAPER);
228 private static final Set<String> SECURE_SETTINGS_WHITELIST;
229 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
230 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
231 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
233 SECURE_SETTINGS_WHITELIST = new HashSet();
234 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
235 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
236 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
238 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new HashSet();
239 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
240 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
242 GLOBAL_SETTINGS_WHITELIST = new HashSet();
243 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
244 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
245 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
246 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
247 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
248 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
249 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
250 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
252 GLOBAL_SETTINGS_DEPRECATED = new HashSet();
253 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
254 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
255 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
256 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
257 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
260 // Keyguard features that when set of a profile will affect the profiles
262 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
263 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
264 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
266 // Keyguard features that are allowed to be set on a managed profile
267 private static final int PROFILE_KEYGUARD_FEATURES =
268 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
269 | DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
271 final Context mContext;
272 final UserManager mUserManager;
273 final PowerManager.WakeLock mWakeLock;
275 final LocalService mLocalService;
277 final PowerManager mPowerManager;
278 final PowerManagerInternal mPowerManagerInternal;
280 IWindowManager mIWindowManager;
281 NotificationManager mNotificationManager;
283 // Stores and loads state on device and profile owners.
284 private DeviceOwner mDeviceOwner;
286 private final Binder mToken = new Binder();
289 * Whether or not device admin feature is supported. If it isn't return defaults for all
292 private boolean mHasFeature;
294 public static final class Lifecycle extends SystemService {
295 private DevicePolicyManagerService mService;
297 public Lifecycle(Context context) {
299 mService = new DevicePolicyManagerService(context);
303 public void onStart() {
304 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
308 public void onBootPhase(int phase) {
309 if (phase == PHASE_LOCK_SETTINGS_READY) {
310 mService.systemReady();
315 public static class DevicePolicyData {
316 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
317 int mActivePasswordLength = 0;
318 int mActivePasswordUpperCase = 0;
319 int mActivePasswordLowerCase = 0;
320 int mActivePasswordLetters = 0;
321 int mActivePasswordNumeric = 0;
322 int mActivePasswordSymbols = 0;
323 int mActivePasswordNonLetter = 0;
324 int mFailedPasswordAttempts = 0;
327 int mPasswordOwner = -1;
328 long mLastMaximumTimeToLock = -1;
329 boolean mUserSetupComplete = false;
330 int mPermissionPolicy;
332 final HashMap<ComponentName, ActiveAdmin> mAdminMap = new HashMap<>();
333 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
334 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
336 // This is the list of component allowed to start lock task mode.
337 List<String> mLockTaskPackages = new ArrayList<>();
339 boolean mStatusBarDisabled = false;
341 ComponentName mRestrictionsProvider;
343 String mDelegatedCertInstallerPackage;
345 boolean doNotAskCredentialsOnBoot = false;
347 public DevicePolicyData(int userHandle) {
348 mUserHandle = userHandle;
352 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
354 Handler mHandler = new Handler();
356 BroadcastReceiver mReceiver = new BroadcastReceiver() {
358 public void onReceive(Context context, Intent intent) {
359 final String action = intent.getAction();
360 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
362 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
363 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
364 if (DBG) Slog.v(LOG_TAG, "Sending password expiration notifications for action "
365 + action + " for user " + userHandle);
366 mHandler.post(new Runnable() {
369 handlePasswordExpirationNotification(userHandle);
373 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
374 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
375 new MonitoringCertNotificationTask().execute(intent);
377 if (Intent.ACTION_USER_REMOVED.equals(action)) {
378 removeUserData(userHandle);
379 } else if (Intent.ACTION_USER_STARTED.equals(action)
380 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
382 if (Intent.ACTION_USER_STARTED.equals(action)) {
383 // Reset the policy data
384 synchronized (DevicePolicyManagerService.this) {
385 mUserData.remove(userHandle);
388 handlePackagesChanged(null /* check all admins */, userHandle);
389 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
390 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
391 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
392 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
393 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
394 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
395 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
396 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
397 clearWipeProfileNotification();
402 static class ActiveAdmin {
403 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
404 private static final String TAG_DISABLE_CAMERA = "disable-camera";
405 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
406 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
407 = "disable-bt-contacts-sharing";
408 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
409 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
410 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
411 private static final String TAG_ACCOUNT_TYPE = "account-type";
412 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
413 = "permitted-accessiblity-services";
414 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
415 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
416 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
417 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
418 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
419 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
420 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
421 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
422 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
423 private static final String TAG_PERMITTED_IMES = "permitted-imes";
424 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
425 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
426 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
427 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
428 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
429 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
430 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
431 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
432 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
433 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
434 private static final String ATTR_VALUE = "value";
435 private static final String TAG_PASSWORD_QUALITY = "password-quality";
436 private static final String TAG_POLICIES = "policies";
437 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
438 "cross-profile-widget-providers";
439 private static final String TAG_PROVIDER = "provider";
440 private static final String TAG_PACKAGE_LIST_ITEM = "item";
442 final DeviceAdminInfo info;
444 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
446 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
447 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
449 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
450 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
452 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
453 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
455 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
456 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
458 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
459 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
461 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
462 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
464 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
465 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
467 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
468 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
470 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
471 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
473 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
474 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
476 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
477 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
479 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
480 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
482 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
484 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
486 boolean encryptionRequested = false;
487 boolean disableCamera = false;
488 boolean disableCallerId = false;
489 boolean disableBluetoothContactSharing = true;
490 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
491 boolean requireAutoTime = false; // Can only be set by a device owner.
493 static class TrustAgentInfo {
494 public PersistableBundle options;
495 TrustAgentInfo(PersistableBundle bundle) {
500 Set<String> accountTypesWithManagementDisabled = new HashSet<String>();
502 // The list of permitted accessibility services package namesas set by a profile
503 // or device owner. Null means all accessibility services are allowed, empty means
504 // none except system services are allowed.
505 List<String> permittedAccessiblityServices;
507 // The list of permitted input methods package names as set by a profile or device owner.
508 // Null means all input methods are allowed, empty means none except system imes are
510 List<String> permittedInputMethods;
512 // TODO: review implementation decisions with frameworks team
513 boolean specifiesGlobalProxy = false;
514 String globalProxySpec = null;
515 String globalProxyExclusionList = null;
517 HashMap<String, TrustAgentInfo> trustAgentInfos = new HashMap<String, TrustAgentInfo>();
519 List<String> crossProfileWidgetProviders;
521 ActiveAdmin(DeviceAdminInfo _info) {
525 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
527 public UserHandle getUserHandle() {
528 return new UserHandle(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
531 void writeToXml(XmlSerializer out)
532 throws IllegalArgumentException, IllegalStateException, IOException {
533 out.startTag(null, TAG_POLICIES);
534 info.writePoliciesToXml(out);
535 out.endTag(null, TAG_POLICIES);
536 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
537 out.startTag(null, TAG_PASSWORD_QUALITY);
538 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
539 out.endTag(null, TAG_PASSWORD_QUALITY);
540 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
541 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
542 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
543 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
545 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
546 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
547 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
548 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
550 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
551 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
552 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
553 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
555 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
556 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
557 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
558 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
560 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
561 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
562 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
563 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
565 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
566 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
567 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
568 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
570 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
571 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
572 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
573 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
575 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
576 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
577 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
578 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
581 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
582 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
583 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
584 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
586 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
587 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
588 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
589 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
591 if (specifiesGlobalProxy) {
592 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
593 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
594 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
595 if (globalProxySpec != null) {
596 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
597 out.attribute(null, ATTR_VALUE, globalProxySpec);
598 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
600 if (globalProxyExclusionList != null) {
601 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
602 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
603 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
606 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
607 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
608 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
609 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
611 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
612 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
613 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
614 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
616 if (encryptionRequested) {
617 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
618 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
619 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
622 out.startTag(null, TAG_DISABLE_CAMERA);
623 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
624 out.endTag(null, TAG_DISABLE_CAMERA);
626 if (disableCallerId) {
627 out.startTag(null, TAG_DISABLE_CALLER_ID);
628 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
629 out.endTag(null, TAG_DISABLE_CALLER_ID);
631 if (disableBluetoothContactSharing) {
632 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
633 out.attribute(null, ATTR_VALUE,
634 Boolean.toString(disableBluetoothContactSharing));
635 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
637 if (disableScreenCapture) {
638 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
639 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
640 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
642 if (requireAutoTime) {
643 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
644 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
645 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
647 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
648 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
649 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
650 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
652 if (!accountTypesWithManagementDisabled.isEmpty()) {
653 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
654 for (String ac : accountTypesWithManagementDisabled) {
655 out.startTag(null, TAG_ACCOUNT_TYPE);
656 out.attribute(null, ATTR_VALUE, ac);
657 out.endTag(null, TAG_ACCOUNT_TYPE);
659 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
661 if (!trustAgentInfos.isEmpty()) {
662 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
663 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
664 for (Entry<String, TrustAgentInfo> entry : set) {
665 TrustAgentInfo trustAgentInfo = entry.getValue();
666 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
667 out.attribute(null, ATTR_VALUE, entry.getKey());
668 if (trustAgentInfo.options != null) {
669 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
671 trustAgentInfo.options.saveToXml(out);
672 } catch (XmlPullParserException e) {
673 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
675 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
677 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
679 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
681 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
682 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
683 final int providerCount = crossProfileWidgetProviders.size();
684 for (int i = 0; i < providerCount; i++) {
685 String provider = crossProfileWidgetProviders.get(i);
686 out.startTag(null, TAG_PROVIDER);
687 out.attribute(null, ATTR_VALUE, provider);
688 out.endTag(null, TAG_PROVIDER);
690 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
692 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
693 permittedAccessiblityServices);
694 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
697 void writePackageListToXml(XmlSerializer out, String outerTag,
698 List<String> packageList)
699 throws IllegalArgumentException, IllegalStateException, IOException {
700 if (packageList == null) {
704 out.startTag(null, outerTag);
705 for (String packageName : packageList) {
706 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
707 out.attribute(null, ATTR_VALUE, packageName);
708 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
710 out.endTag(null, outerTag);
713 void readFromXml(XmlPullParser parser)
714 throws XmlPullParserException, IOException {
715 int outerDepth = parser.getDepth();
717 while ((type=parser.next()) != END_DOCUMENT
718 && (type != END_TAG || parser.getDepth() > outerDepth)) {
719 if (type == END_TAG || type == TEXT) {
722 String tag = parser.getName();
723 if (TAG_POLICIES.equals(tag)) {
724 info.readPoliciesFromXml(parser);
725 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
726 passwordQuality = Integer.parseInt(
727 parser.getAttributeValue(null, ATTR_VALUE));
728 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
729 minimumPasswordLength = Integer.parseInt(
730 parser.getAttributeValue(null, ATTR_VALUE));
731 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
732 passwordHistoryLength = Integer.parseInt(
733 parser.getAttributeValue(null, ATTR_VALUE));
734 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
735 minimumPasswordUpperCase = Integer.parseInt(
736 parser.getAttributeValue(null, ATTR_VALUE));
737 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
738 minimumPasswordLowerCase = Integer.parseInt(
739 parser.getAttributeValue(null, ATTR_VALUE));
740 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
741 minimumPasswordLetters = Integer.parseInt(
742 parser.getAttributeValue(null, ATTR_VALUE));
743 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
744 minimumPasswordNumeric = Integer.parseInt(
745 parser.getAttributeValue(null, ATTR_VALUE));
746 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
747 minimumPasswordSymbols = Integer.parseInt(
748 parser.getAttributeValue(null, ATTR_VALUE));
749 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
750 minimumPasswordNonLetter = Integer.parseInt(
751 parser.getAttributeValue(null, ATTR_VALUE));
752 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
753 maximumTimeToUnlock = Long.parseLong(
754 parser.getAttributeValue(null, ATTR_VALUE));
755 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
756 maximumFailedPasswordsForWipe = Integer.parseInt(
757 parser.getAttributeValue(null, ATTR_VALUE));
758 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
759 specifiesGlobalProxy = Boolean.parseBoolean(
760 parser.getAttributeValue(null, ATTR_VALUE));
761 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
763 parser.getAttributeValue(null, ATTR_VALUE);
764 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
765 globalProxyExclusionList =
766 parser.getAttributeValue(null, ATTR_VALUE);
767 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
768 passwordExpirationTimeout = Long.parseLong(
769 parser.getAttributeValue(null, ATTR_VALUE));
770 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
771 passwordExpirationDate = Long.parseLong(
772 parser.getAttributeValue(null, ATTR_VALUE));
773 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
774 encryptionRequested = Boolean.parseBoolean(
775 parser.getAttributeValue(null, ATTR_VALUE));
776 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
777 disableCamera = Boolean.parseBoolean(
778 parser.getAttributeValue(null, ATTR_VALUE));
779 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
780 disableCallerId = Boolean.parseBoolean(
781 parser.getAttributeValue(null, ATTR_VALUE));
782 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
783 disableBluetoothContactSharing = Boolean.parseBoolean(parser
784 .getAttributeValue(null, ATTR_VALUE));
785 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
786 disableScreenCapture = Boolean.parseBoolean(
787 parser.getAttributeValue(null, ATTR_VALUE));
788 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
789 requireAutoTime= Boolean.parseBoolean(
790 parser.getAttributeValue(null, ATTR_VALUE));
791 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
792 disabledKeyguardFeatures = Integer.parseInt(
793 parser.getAttributeValue(null, ATTR_VALUE));
794 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
795 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
796 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
797 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
798 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
799 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
800 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
801 permittedAccessiblityServices = readPackageList(parser, tag);
802 } else if (TAG_PERMITTED_IMES.equals(tag)) {
803 permittedInputMethods = readPackageList(parser, tag);
805 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
806 XmlUtils.skipCurrentTag(parser);
811 private List<String> readPackageList(XmlPullParser parser,
812 String tag) throws XmlPullParserException, IOException {
813 List<String> result = new ArrayList<String>();
814 int outerDepth = parser.getDepth();
816 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
817 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
818 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
821 String outerTag = parser.getName();
822 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
823 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
824 if (packageName != null) {
825 result.add(packageName);
827 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
830 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
836 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
837 throws XmlPullParserException, IOException {
838 int outerDepthDAM = parser.getDepth();
840 Set<String> result = new HashSet<String>();
841 while ((typeDAM=parser.next()) != END_DOCUMENT
842 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
843 if (typeDAM == END_TAG || typeDAM == TEXT) {
846 String tagDAM = parser.getName();
847 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
848 result.add(parser.getAttributeValue(null, ATTR_VALUE));
850 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
856 private HashMap<String, TrustAgentInfo> getAllTrustAgentInfos(
857 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
858 int outerDepthDAM = parser.getDepth();
860 HashMap<String, TrustAgentInfo> result = new HashMap<String, TrustAgentInfo>();
861 while ((typeDAM=parser.next()) != END_DOCUMENT
862 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
863 if (typeDAM == END_TAG || typeDAM == TEXT) {
866 String tagDAM = parser.getName();
867 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
868 final String component = parser.getAttributeValue(null, ATTR_VALUE);
869 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
870 result.put(component, trustAgentInfo);
872 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
878 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
879 throws XmlPullParserException, IOException {
880 int outerDepthDAM = parser.getDepth();
882 TrustAgentInfo result = new TrustAgentInfo(null);
883 while ((typeDAM=parser.next()) != END_DOCUMENT
884 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
885 if (typeDAM == END_TAG || typeDAM == TEXT) {
888 String tagDAM = parser.getName();
889 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
890 PersistableBundle bundle = new PersistableBundle();
891 bundle.restoreFromXml(parser);
892 result.options = bundle;
894 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
900 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
901 throws XmlPullParserException, IOException {
902 int outerDepthDAM = parser.getDepth();
904 ArrayList<String> result = null;
905 while ((typeDAM=parser.next()) != END_DOCUMENT
906 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
907 if (typeDAM == END_TAG || typeDAM == TEXT) {
910 String tagDAM = parser.getName();
911 if (TAG_PROVIDER.equals(tagDAM)) {
912 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
913 if (result == null) {
914 result = new ArrayList<>();
916 result.add(provider);
918 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
924 void dump(String prefix, PrintWriter pw) {
925 pw.print(prefix); pw.print("uid="); pw.println(getUid());
926 pw.print(prefix); pw.println("policies:");
927 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
929 for (int i=0; i<pols.size(); i++) {
930 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
933 pw.print(prefix); pw.print("passwordQuality=0x");
934 pw.println(Integer.toHexString(passwordQuality));
935 pw.print(prefix); pw.print("minimumPasswordLength=");
936 pw.println(minimumPasswordLength);
937 pw.print(prefix); pw.print("passwordHistoryLength=");
938 pw.println(passwordHistoryLength);
939 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
940 pw.println(minimumPasswordUpperCase);
941 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
942 pw.println(minimumPasswordLowerCase);
943 pw.print(prefix); pw.print("minimumPasswordLetters=");
944 pw.println(minimumPasswordLetters);
945 pw.print(prefix); pw.print("minimumPasswordNumeric=");
946 pw.println(minimumPasswordNumeric);
947 pw.print(prefix); pw.print("minimumPasswordSymbols=");
948 pw.println(minimumPasswordSymbols);
949 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
950 pw.println(minimumPasswordNonLetter);
951 pw.print(prefix); pw.print("maximumTimeToUnlock=");
952 pw.println(maximumTimeToUnlock);
953 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
954 pw.println(maximumFailedPasswordsForWipe);
955 pw.print(prefix); pw.print("specifiesGlobalProxy=");
956 pw.println(specifiesGlobalProxy);
957 pw.print(prefix); pw.print("passwordExpirationTimeout=");
958 pw.println(passwordExpirationTimeout);
959 pw.print(prefix); pw.print("passwordExpirationDate=");
960 pw.println(passwordExpirationDate);
961 if (globalProxySpec != null) {
962 pw.print(prefix); pw.print("globalProxySpec=");
963 pw.println(globalProxySpec);
965 if (globalProxyExclusionList != null) {
966 pw.print(prefix); pw.print("globalProxyEclusionList=");
967 pw.println(globalProxyExclusionList);
969 pw.print(prefix); pw.print("encryptionRequested=");
970 pw.println(encryptionRequested);
971 pw.print(prefix); pw.print("disableCamera=");
972 pw.println(disableCamera);
973 pw.print(prefix); pw.print("disableCallerId=");
974 pw.println(disableCallerId);
975 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
976 pw.println(disableBluetoothContactSharing);
977 pw.print(prefix); pw.print("disableScreenCapture=");
978 pw.println(disableScreenCapture);
979 pw.print(prefix); pw.print("requireAutoTime=");
980 pw.println(requireAutoTime);
981 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
982 pw.println(disabledKeyguardFeatures);
983 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
984 pw.println(crossProfileWidgetProviders);
985 if (!(permittedAccessiblityServices == null)) {
986 pw.print(prefix); pw.print("permittedAccessibilityServices=");
987 pw.println(permittedAccessiblityServices.toString());
989 if (!(permittedInputMethods == null)) {
990 pw.print(prefix); pw.print("permittedInputMethods=");
991 pw.println(permittedInputMethods.toString());
996 private void handlePackagesChanged(String packageName, int userHandle) {
997 boolean removed = false;
998 if (DBG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
999 DevicePolicyData policy = getUserData(userHandle);
1000 IPackageManager pm = AppGlobals.getPackageManager();
1001 synchronized (this) {
1002 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1003 ActiveAdmin aa = policy.mAdminList.get(i);
1005 // If we're checking all packages or if the specific one we're checking matches,
1006 // then check if the package and receiver still exist.
1007 final String adminPackage = aa.info.getPackageName();
1008 if (packageName == null || packageName.equals(adminPackage)) {
1009 if (pm.getPackageInfo(adminPackage, 0, userHandle) == null
1010 || pm.getReceiverInfo(aa.info.getComponent(), 0, userHandle)
1013 policy.mAdminList.remove(i);
1014 policy.mAdminMap.remove(aa.info.getComponent());
1017 } catch (RemoteException re) {
1022 validatePasswordOwnerLocked(policy);
1023 syncDeviceCapabilitiesLocked(policy);
1024 saveSettingsLocked(policy.mUserHandle);
1027 if (policy.mDelegatedCertInstallerPackage != null &&
1028 (packageName == null
1029 || packageName.equals(policy.mDelegatedCertInstallerPackage))) {
1031 // Check if delegated cert installer package is removed.
1032 if (pm.getPackageInfo(
1033 policy.mDelegatedCertInstallerPackage, 0, userHandle) == null) {
1034 policy.mDelegatedCertInstallerPackage = null;
1035 saveSettingsLocked(policy.mUserHandle);
1037 } catch (RemoteException e) {
1045 * Instantiates the service.
1047 public DevicePolicyManagerService(Context context) {
1049 mUserManager = UserManager.get(mContext);
1050 mHasFeature = context.getPackageManager().hasSystemFeature(
1051 PackageManager.FEATURE_DEVICE_ADMIN);
1052 mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1053 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
1054 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DPM");
1055 mLocalService = new LocalService();
1057 // Skip the rest of the initialization
1060 IntentFilter filter = new IntentFilter();
1061 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1062 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1063 filter.addAction(Intent.ACTION_USER_REMOVED);
1064 filter.addAction(Intent.ACTION_USER_STARTED);
1065 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1066 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1067 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1068 filter = new IntentFilter();
1069 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1070 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1071 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1072 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1073 filter.addDataScheme("package");
1074 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1075 filter = new IntentFilter();
1076 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1077 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1079 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1083 * Creates and loads the policy data from xml.
1084 * @param userHandle the user for whom to load the policy data
1087 DevicePolicyData getUserData(int userHandle) {
1088 synchronized (this) {
1089 DevicePolicyData policy = mUserData.get(userHandle);
1090 if (policy == null) {
1091 policy = new DevicePolicyData(userHandle);
1092 mUserData.append(userHandle, policy);
1093 loadSettingsLocked(policy, userHandle);
1100 * Creates and loads the policy data from xml for data that is shared between
1101 * various profiles of a user. In contrast to {@link #getUserData(int)}
1102 * it allows access to data of users other than the calling user.
1104 * This function should only be used for shared data, e.g. everything regarding
1105 * passwords and should be removed once multiple screen locks are present.
1106 * @param userHandle the user for whom to load the policy data
1109 DevicePolicyData getUserDataUnchecked(int userHandle) {
1110 long ident = Binder.clearCallingIdentity();
1112 return getUserData(userHandle);
1114 Binder.restoreCallingIdentity(ident);
1118 void removeUserData(int userHandle) {
1119 synchronized (this) {
1120 if (userHandle == UserHandle.USER_OWNER) {
1121 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1124 if (mDeviceOwner != null) {
1125 mDeviceOwner.removeProfileOwner(userHandle);
1126 mDeviceOwner.writeOwnerFile();
1129 DevicePolicyData policy = mUserData.get(userHandle);
1130 if (policy != null) {
1131 mUserData.remove(userHandle);
1133 File policyFile = new File(Environment.getUserSystemDirectory(userHandle),
1134 DEVICE_POLICIES_XML);
1135 policyFile.delete();
1136 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1138 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1141 void loadDeviceOwner() {
1142 synchronized (this) {
1143 mDeviceOwner = DeviceOwner.load();
1144 updateDeviceOwnerLocked();
1149 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1150 * reminders. Clears alarm if no expirations are configured.
1152 protected void setExpirationAlarmCheckLocked(Context context, DevicePolicyData policy) {
1153 final long expiration = getPasswordExpirationLocked(null, policy.mUserHandle);
1154 final long now = System.currentTimeMillis();
1155 final long timeToExpire = expiration - now;
1156 final long alarmTime;
1157 if (expiration == 0) {
1158 // No expirations are currently configured: Cancel alarm.
1160 } else if (timeToExpire <= 0) {
1161 // The password has already expired: Repeat every 24 hours.
1162 alarmTime = now + MS_PER_DAY;
1164 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1165 // the expiration time.
1166 long alarmInterval = timeToExpire % MS_PER_DAY;
1167 if (alarmInterval == 0) {
1168 alarmInterval = MS_PER_DAY;
1170 alarmTime = now + alarmInterval;
1173 long token = Binder.clearCallingIdentity();
1175 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1176 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1177 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1178 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1179 new UserHandle(policy.mUserHandle));
1181 if (alarmTime != 0) {
1182 am.set(AlarmManager.RTC, alarmTime, pi);
1185 Binder.restoreCallingIdentity(token);
1189 private IWindowManager getWindowManager() {
1190 if (mIWindowManager == null) {
1191 IBinder b = ServiceManager.getService(Context.WINDOW_SERVICE);
1192 mIWindowManager = IWindowManager.Stub.asInterface(b);
1194 return mIWindowManager;
1197 private NotificationManager getNotificationManager() {
1198 if (mNotificationManager == null) {
1199 mNotificationManager =
1200 (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
1202 return mNotificationManager;
1205 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1206 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1208 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1209 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1215 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1216 throws SecurityException {
1217 final int callingUid = Binder.getCallingUid();
1219 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1220 if (result != null) {
1225 final int userId = UserHandle.getUserId(callingUid);
1226 final DevicePolicyData policy = getUserData(userId);
1227 ActiveAdmin admin = policy.mAdminMap.get(who);
1228 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1229 throw new SecurityException("Admin " + admin.info.getComponent()
1230 + " does not own the device");
1232 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1233 throw new SecurityException("Admin " + admin.info.getComponent()
1234 + " does not own the profile");
1236 throw new SecurityException("Admin " + admin.info.getComponent()
1237 + " did not specify uses-policy for: "
1238 + admin.info.getTagForPolicy(reqPolicy));
1240 throw new SecurityException("No active admin owned by uid "
1241 + Binder.getCallingUid() + " for policy #" + reqPolicy);
1245 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
1247 // Try to find an admin which can use reqPolicy
1248 final int userId = UserHandle.getUserId(uid);
1249 final DevicePolicyData policy = getUserData(userId);
1251 ActiveAdmin admin = policy.mAdminMap.get(who);
1252 if (admin == null) {
1253 throw new SecurityException("No active admin " + who);
1255 if (admin.getUid() != uid) {
1256 throw new SecurityException("Admin " + who + " is not owned by uid "
1257 + Binder.getCallingUid());
1259 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
1263 for (ActiveAdmin admin : policy.mAdminList) {
1264 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
1274 private boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
1276 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
1277 boolean ownsProfile = (getProfileOwner(userId) != null
1278 && getProfileOwner(userId).getPackageName()
1279 .equals(admin.info.getPackageName()));
1280 boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName())
1281 && !hasUserSetupCompleted(userId);
1283 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1284 if ((userId == UserHandle.USER_OWNER && (ownsDevice || ownsInitialization))
1285 || (ownsDevice && ownsProfile)) {
1288 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1289 if ((userId == UserHandle.USER_OWNER && ownsDevice) || ownsProfile
1290 || ownsInitialization) {
1294 if (admin.info.usesPolicy(reqPolicy)) {
1301 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
1302 sendAdminCommandLocked(admin, action, null);
1305 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
1306 sendAdminCommandLocked(admin, action, null, result);
1310 * Send an update to one specific admin, get notified when that admin returns a result.
1312 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
1313 BroadcastReceiver result) {
1314 Intent intent = new Intent(action);
1315 intent.setComponent(admin.info.getComponent());
1316 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
1317 intent.putExtra("expiration", admin.passwordExpirationDate);
1319 if (adminExtras != null) {
1320 intent.putExtras(adminExtras);
1322 if (result != null) {
1323 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
1324 null, result, mHandler, Activity.RESULT_OK, null, null);
1326 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
1331 * Send an update to all admins of a user that enforce a specified policy.
1333 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
1334 final DevicePolicyData policy = getUserData(userHandle);
1335 final int count = policy.mAdminList.size();
1337 for (int i = 0; i < count; i++) {
1338 final ActiveAdmin admin = policy.mAdminList.get(i);
1339 if (admin.info.usesPolicy(reqPolicy)) {
1340 sendAdminCommandLocked(admin, action);
1347 * Send an update intent to all admins of a user and its profiles. Only send to admins that
1348 * enforce a specified policy.
1350 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
1352 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1353 for (UserInfo ui : profiles) {
1355 sendAdminCommandLocked(action, reqPolicy, id);
1359 void removeActiveAdminLocked(final ComponentName adminReceiver, int userHandle) {
1360 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
1361 if (admin != null) {
1362 synchronized (this) {
1363 getUserData(userHandle).mRemovingAdmins.add(adminReceiver);
1365 sendAdminCommandLocked(admin,
1366 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
1367 new BroadcastReceiver() {
1369 public void onReceive(Context context, Intent intent) {
1370 synchronized (DevicePolicyManagerService.this) {
1371 int userHandle = admin.getUserHandle().getIdentifier();
1372 DevicePolicyData policy = getUserData(userHandle);
1373 boolean doProxyCleanup = admin.info.usesPolicy(
1374 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
1375 policy.mAdminList.remove(admin);
1376 policy.mAdminMap.remove(adminReceiver);
1377 validatePasswordOwnerLocked(policy);
1378 syncDeviceCapabilitiesLocked(policy);
1379 if (doProxyCleanup) {
1380 resetGlobalProxyLocked(getUserData(userHandle));
1382 saveSettingsLocked(userHandle);
1383 updateMaximumTimeToLockLocked(policy);
1384 policy.mRemovingAdmins.remove(adminReceiver);
1391 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle) {
1395 enforceCrossUserPermission(userHandle);
1396 Intent resolveIntent = new Intent();
1397 resolveIntent.setComponent(adminName);
1398 List<ResolveInfo> infos = mContext.getPackageManager().queryBroadcastReceivers(
1400 PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
1402 if (infos == null || infos.size() <= 0) {
1403 throw new IllegalArgumentException("Unknown admin: " + adminName);
1407 return new DeviceAdminInfo(mContext, infos.get(0));
1408 } catch (XmlPullParserException e) {
1409 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
1412 } catch (IOException e) {
1413 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
1419 private static JournaledFile makeJournaledFile(int userHandle) {
1420 final String base = userHandle == 0
1421 ? "/data/system/" + DEVICE_POLICIES_XML
1422 : new File(Environment.getUserSystemDirectory(userHandle), DEVICE_POLICIES_XML)
1424 return new JournaledFile(new File(base), new File(base + ".tmp"));
1427 private void saveSettingsLocked(int userHandle) {
1428 DevicePolicyData policy = getUserData(userHandle);
1429 JournaledFile journal = makeJournaledFile(userHandle);
1430 FileOutputStream stream = null;
1432 stream = new FileOutputStream(journal.chooseForWrite(), false);
1433 XmlSerializer out = new FastXmlSerializer();
1434 out.setOutput(stream, StandardCharsets.UTF_8.name());
1435 out.startDocument(null, true);
1437 out.startTag(null, "policies");
1438 if (policy.mRestrictionsProvider != null) {
1439 out.attribute(null, ATTR_PERMISSION_PROVIDER,
1440 policy.mRestrictionsProvider.flattenToString());
1442 if (policy.mUserSetupComplete) {
1443 out.attribute(null, ATTR_SETUP_COMPLETE,
1444 Boolean.toString(true));
1446 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
1447 out.attribute(null, ATTR_PERMISSION_POLICY,
1448 Integer.toString(policy.mPermissionPolicy));
1450 if (policy.mDelegatedCertInstallerPackage != null) {
1451 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
1452 policy.mDelegatedCertInstallerPackage);
1455 final int N = policy.mAdminList.size();
1456 for (int i=0; i<N; i++) {
1457 ActiveAdmin ap = policy.mAdminList.get(i);
1459 out.startTag(null, "admin");
1460 out.attribute(null, "name", ap.info.getComponent().flattenToString());
1462 out.endTag(null, "admin");
1466 if (policy.mPasswordOwner >= 0) {
1467 out.startTag(null, "password-owner");
1468 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
1469 out.endTag(null, "password-owner");
1472 if (policy.mFailedPasswordAttempts != 0) {
1473 out.startTag(null, "failed-password-attempts");
1474 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
1475 out.endTag(null, "failed-password-attempts");
1478 if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
1479 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
1480 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
1481 || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
1482 out.startTag(null, "active-password");
1483 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
1484 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
1485 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
1486 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
1487 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
1488 out.attribute(null, "numeric", Integer
1489 .toString(policy.mActivePasswordNumeric));
1490 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
1491 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
1492 out.endTag(null, "active-password");
1495 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
1496 String component = policy.mLockTaskPackages.get(i);
1497 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
1498 out.attribute(null, "name", component);
1499 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
1502 if (policy.mStatusBarDisabled) {
1503 out.startTag(null, TAG_STATUS_BAR);
1504 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
1505 out.endTag(null, TAG_STATUS_BAR);
1508 if (policy.doNotAskCredentialsOnBoot) {
1509 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
1510 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
1513 out.endTag(null, "policies");
1517 FileUtils.sync(stream);
1520 sendChangedNotification(userHandle);
1521 } catch (IOException e) {
1523 if (stream != null) {
1526 } catch (IOException ex) {
1533 private void sendChangedNotification(int userHandle) {
1534 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1535 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1536 long ident = Binder.clearCallingIdentity();
1538 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
1540 Binder.restoreCallingIdentity(ident);
1544 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
1545 JournaledFile journal = makeJournaledFile(userHandle);
1546 FileInputStream stream = null;
1547 File file = journal.chooseForRead();
1549 stream = new FileInputStream(file);
1550 XmlPullParser parser = Xml.newPullParser();
1551 parser.setInput(stream, StandardCharsets.UTF_8.name());
1554 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1555 && type != XmlPullParser.START_TAG) {
1557 String tag = parser.getName();
1558 if (!"policies".equals(tag)) {
1559 throw new XmlPullParserException(
1560 "Settings do not start with policies tag: found " + tag);
1563 // Extract the permission provider component name if available
1564 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
1565 if (permissionProvider != null) {
1566 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
1568 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
1569 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
1570 policy.mUserSetupComplete = true;
1572 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
1573 if (!TextUtils.isEmpty(permissionPolicy)) {
1574 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
1576 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
1577 ATTR_DELEGATED_CERT_INSTALLER);
1579 type = parser.next();
1580 int outerDepth = parser.getDepth();
1581 policy.mLockTaskPackages.clear();
1582 policy.mAdminList.clear();
1583 policy.mAdminMap.clear();
1584 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1585 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1586 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1589 tag = parser.getName();
1590 if ("admin".equals(tag)) {
1591 String name = parser.getAttributeValue(null, "name");
1593 DeviceAdminInfo dai = findAdmin(
1594 ComponentName.unflattenFromString(name), userHandle);
1595 if (DBG && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
1597 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
1598 + dai.getActivityInfo().applicationInfo.uid + " for user "
1602 ActiveAdmin ap = new ActiveAdmin(dai);
1603 ap.readFromXml(parser);
1604 policy.mAdminMap.put(ap.info.getComponent(), ap);
1606 } catch (RuntimeException e) {
1607 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
1609 } else if ("failed-password-attempts".equals(tag)) {
1610 policy.mFailedPasswordAttempts = Integer.parseInt(
1611 parser.getAttributeValue(null, "value"));
1612 } else if ("password-owner".equals(tag)) {
1613 policy.mPasswordOwner = Integer.parseInt(
1614 parser.getAttributeValue(null, "value"));
1615 } else if ("active-password".equals(tag)) {
1616 policy.mActivePasswordQuality = Integer.parseInt(
1617 parser.getAttributeValue(null, "quality"));
1618 policy.mActivePasswordLength = Integer.parseInt(
1619 parser.getAttributeValue(null, "length"));
1620 policy.mActivePasswordUpperCase = Integer.parseInt(
1621 parser.getAttributeValue(null, "uppercase"));
1622 policy.mActivePasswordLowerCase = Integer.parseInt(
1623 parser.getAttributeValue(null, "lowercase"));
1624 policy.mActivePasswordLetters = Integer.parseInt(
1625 parser.getAttributeValue(null, "letters"));
1626 policy.mActivePasswordNumeric = Integer.parseInt(
1627 parser.getAttributeValue(null, "numeric"));
1628 policy.mActivePasswordSymbols = Integer.parseInt(
1629 parser.getAttributeValue(null, "symbols"));
1630 policy.mActivePasswordNonLetter = Integer.parseInt(
1631 parser.getAttributeValue(null, "nonletter"));
1632 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
1633 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
1634 } else if (TAG_STATUS_BAR.equals(tag)) {
1635 policy.mStatusBarDisabled = Boolean.parseBoolean(
1636 parser.getAttributeValue(null, ATTR_DISABLED));
1637 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
1638 policy.doNotAskCredentialsOnBoot = true;
1640 Slog.w(LOG_TAG, "Unknown tag: " + tag);
1641 XmlUtils.skipCurrentTag(parser);
1644 } catch (NullPointerException e) {
1645 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1646 } catch (NumberFormatException e) {
1647 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1648 } catch (XmlPullParserException e) {
1649 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1650 } catch (FileNotFoundException e) {
1651 // Don't be noisy, this is normal if we haven't defined any policies.
1652 } catch (IOException e) {
1653 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1654 } catch (IndexOutOfBoundsException e) {
1655 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1658 if (stream != null) {
1661 } catch (IOException e) {
1665 // Generate a list of admins from the admin map
1666 policy.mAdminList.addAll(policy.mAdminMap.values());
1668 // Validate that what we stored for the password quality matches
1669 // sufficiently what is currently set. Note that this is only
1670 // a sanity check in case the two get out of sync; this should
1671 // never normally happen.
1672 final long identity = Binder.clearCallingIdentity();
1674 LockPatternUtils utils = new LockPatternUtils(mContext);
1675 if (utils.getActivePasswordQuality(userHandle) < policy.mActivePasswordQuality) {
1676 Slog.w(LOG_TAG, "Active password quality 0x"
1677 + Integer.toHexString(policy.mActivePasswordQuality)
1678 + " does not match actual quality 0x"
1679 + Integer.toHexString(utils.getActivePasswordQuality(userHandle)));
1680 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
1681 policy.mActivePasswordLength = 0;
1682 policy.mActivePasswordUpperCase = 0;
1683 policy.mActivePasswordLowerCase = 0;
1684 policy.mActivePasswordLetters = 0;
1685 policy.mActivePasswordNumeric = 0;
1686 policy.mActivePasswordSymbols = 0;
1687 policy.mActivePasswordNonLetter = 0;
1690 Binder.restoreCallingIdentity(identity);
1693 validatePasswordOwnerLocked(policy);
1694 syncDeviceCapabilitiesLocked(policy);
1695 updateMaximumTimeToLockLocked(policy);
1696 addDeviceInitializerToLockTaskPackagesLocked(userHandle);
1697 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
1698 if (policy.mStatusBarDisabled) {
1699 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
1703 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
1704 IActivityManager am = ActivityManagerNative.getDefault();
1705 long ident = Binder.clearCallingIdentity();
1707 am.updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
1708 } catch (RemoteException e) {
1709 // Not gonna happen.
1711 Binder.restoreCallingIdentity(ident);
1715 private void updateDeviceOwnerLocked() {
1716 IActivityManager am = ActivityManagerNative.getDefault();
1717 long ident = Binder.clearCallingIdentity();
1719 am.updateDeviceOwner(getDeviceOwner());
1720 } catch (RemoteException e) {
1721 // Not gonna happen.
1723 Binder.restoreCallingIdentity(ident);
1727 static void validateQualityConstant(int quality) {
1729 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
1730 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
1731 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
1732 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
1733 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
1734 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
1735 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
1736 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
1739 throw new IllegalArgumentException("Invalid quality constant: 0x"
1740 + Integer.toHexString(quality));
1743 void validatePasswordOwnerLocked(DevicePolicyData policy) {
1744 if (policy.mPasswordOwner >= 0) {
1745 boolean haveOwner = false;
1746 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1747 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
1753 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
1754 + " no longer active; disabling");
1755 policy.mPasswordOwner = -1;
1761 * Pushes down policy information to the system for any policies related to general device
1762 * capabilities that need to be enforced by lower level services (e.g. Camera services).
1764 void syncDeviceCapabilitiesLocked(DevicePolicyData policy) {
1765 // Ensure the status of the camera is synced down to the system. Interested native services
1766 // should monitor this value and act accordingly.
1767 String cameraPropertyForUser = SYSTEM_PROP_DISABLE_CAMERA_PREFIX + policy.mUserHandle;
1768 boolean systemState = SystemProperties.getBoolean(cameraPropertyForUser, false);
1769 boolean cameraDisabled = getCameraDisabled(null, policy.mUserHandle);
1770 if (cameraDisabled != systemState) {
1771 long token = Binder.clearCallingIdentity();
1773 String value = cameraDisabled ? "1" : "0";
1774 if (DBG) Slog.v(LOG_TAG, "Change in camera state ["
1775 + cameraPropertyForUser + "] = " + value);
1776 SystemProperties.set(cameraPropertyForUser, value);
1778 Binder.restoreCallingIdentity(token);
1783 public void systemReady() {
1787 getUserData(UserHandle.USER_OWNER);
1790 // Register an observer for watching for user setup complete.
1791 new SetupContentObserver(mHandler).register(mContext.getContentResolver());
1792 // Initialize the user setup state, to handle the upgrade case.
1793 updateUserSetupComplete();
1795 // Update the screen capture disabled cache in the window manager
1796 List<UserInfo> users = mUserManager.getUsers(true);
1797 final int N = users.size();
1798 for (int i = 0; i < N; i++) {
1799 int userHandle = users.get(i).id;
1800 updateScreenCaptureDisabledInWindowManager(userHandle,
1801 getScreenCaptureDisabled(null, userHandle));
1805 private void cleanUpOldUsers() {
1806 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
1808 Set<Integer> usersWithProfileOwners;
1809 Set<Integer> usersWithData;
1810 synchronized(this) {
1811 usersWithProfileOwners = mDeviceOwner != null
1812 ? mDeviceOwner.getProfileOwnerKeys() : new HashSet<Integer>();
1813 usersWithData = new HashSet<Integer>();
1814 for (int i = 0; i < mUserData.size(); i++) {
1815 usersWithData.add(mUserData.keyAt(i));
1818 List<UserInfo> allUsers = mUserManager.getUsers();
1820 Set<Integer> deletedUsers = new HashSet<Integer>();
1821 deletedUsers.addAll(usersWithProfileOwners);
1822 deletedUsers.addAll(usersWithData);
1823 for (UserInfo userInfo : allUsers) {
1824 deletedUsers.remove(userInfo.id);
1826 for (Integer userId : deletedUsers) {
1827 removeUserData(userId);
1831 private void handlePasswordExpirationNotification(int userHandle) {
1832 synchronized (this) {
1833 final long now = System.currentTimeMillis();
1835 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1836 for (UserInfo ui : profiles) {
1837 int profileUserHandle = ui.id;
1838 final DevicePolicyData policy = getUserData(profileUserHandle);
1839 final int count = policy.mAdminList.size();
1841 for (int i = 0; i < count; i++) {
1842 final ActiveAdmin admin = policy.mAdminList.get(i);
1843 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
1844 && admin.passwordExpirationTimeout > 0L
1845 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
1846 && admin.passwordExpirationDate > 0L) {
1847 sendAdminCommandLocked(admin,
1848 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
1853 setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
1857 private class MonitoringCertNotificationTask extends AsyncTask<Intent, Void, Void> {
1859 protected Void doInBackground(Intent... params) {
1860 int userHandle = params[0].getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
1862 if (userHandle == UserHandle.USER_ALL) {
1863 for (UserInfo userInfo : mUserManager.getUsers()) {
1864 manageNotification(userInfo.getUserHandle());
1867 manageNotification(new UserHandle(userHandle));
1872 private void manageNotification(UserHandle userHandle) {
1873 if (!mUserManager.isUserRunning(userHandle)) {
1877 // Call out to KeyChain to check for user-added CAs
1878 boolean hasCert = false;
1880 KeyChainConnection kcs = KeyChain.bindAsUser(mContext, userHandle);
1882 if (!kcs.getService().getUserCaAliases().getList().isEmpty()) {
1885 } catch (RemoteException e) {
1886 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
1890 } catch (InterruptedException e) {
1891 Thread.currentThread().interrupt();
1892 } catch (RuntimeException e) {
1893 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
1896 getNotificationManager().cancelAsUser(
1897 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
1901 // Build and show a warning notification
1904 final String ownerName = getDeviceOwnerName();
1905 if (isManagedProfile(userHandle.getIdentifier())) {
1906 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_administrator);
1907 smallIconId = R.drawable.stat_sys_certificate_info;
1908 } else if (ownerName != null) {
1909 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, ownerName);
1910 smallIconId = R.drawable.stat_sys_certificate_info;
1912 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
1913 smallIconId = android.R.drawable.stat_sys_warning;
1916 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
1917 dialogIntent.setFlags(
1918 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1919 dialogIntent.setPackage("com.android.settings");
1920 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
1921 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, userHandle);
1923 final Context userContext;
1925 userContext = mContext.createPackageContextAsUser("android", 0, userHandle);
1926 } catch (PackageManager.NameNotFoundException e) {
1927 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
1930 final Notification noti = new Notification.Builder(userContext)
1931 .setSmallIcon(smallIconId)
1932 .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning))
1933 .setContentText(contentText)
1934 .setContentIntent(notifyIntent)
1935 .setPriority(Notification.PRIORITY_HIGH)
1937 .setColor(mContext.getColor(
1938 com.android.internal.R.color.system_notification_accent_color))
1941 getNotificationManager().notifyAsUser(
1942 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
1947 * @param adminReceiver The admin to add
1948 * @param refreshing true = update an active admin, no error
1951 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
1955 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
1958 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
1959 Bundle onEnableData) {
1960 mContext.enforceCallingOrSelfPermission(
1961 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
1962 enforceCrossUserPermission(userHandle);
1964 DevicePolicyData policy = getUserData(userHandle);
1965 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle);
1967 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
1969 synchronized (this) {
1970 long ident = Binder.clearCallingIdentity();
1973 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
1974 throw new IllegalArgumentException("Admin is already added");
1976 ActiveAdmin newAdmin = new ActiveAdmin(info);
1977 policy.mAdminMap.put(adminReceiver, newAdmin);
1978 int replaceIndex = -1;
1979 final int N = policy.mAdminList.size();
1980 for (int i=0; i < N; i++) {
1981 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
1982 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
1987 if (replaceIndex == -1) {
1988 policy.mAdminList.add(newAdmin);
1989 enableIfNecessary(info.getPackageName(), userHandle);
1991 policy.mAdminList.set(replaceIndex, newAdmin);
1993 saveSettingsLocked(userHandle);
1994 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
1995 onEnableData, null);
1997 Binder.restoreCallingIdentity(ident);
2003 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2007 enforceCrossUserPermission(userHandle);
2008 synchronized (this) {
2009 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2014 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2018 enforceCrossUserPermission(userHandle);
2019 synchronized (this) {
2020 DevicePolicyData policyData = getUserData(userHandle);
2021 return policyData.mRemovingAdmins.contains(adminReceiver);
2026 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2030 enforceCrossUserPermission(userHandle);
2031 synchronized (this) {
2032 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2033 if (administrator == null) {
2034 throw new SecurityException("No active admin " + adminReceiver);
2036 return administrator.info.usesPolicy(policyId);
2041 @SuppressWarnings("unchecked")
2042 public List<ComponentName> getActiveAdmins(int userHandle) {
2044 return Collections.EMPTY_LIST;
2047 enforceCrossUserPermission(userHandle);
2048 synchronized (this) {
2049 DevicePolicyData policy = getUserData(userHandle);
2050 final int N = policy.mAdminList.size();
2054 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2055 for (int i=0; i<N; i++) {
2056 res.add(policy.mAdminList.get(i).info.getComponent());
2063 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2067 enforceCrossUserPermission(userHandle);
2068 synchronized (this) {
2069 DevicePolicyData policy = getUserData(userHandle);
2070 final int N = policy.mAdminList.size();
2071 for (int i=0; i<N; i++) {
2072 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2081 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
2085 enforceCrossUserPermission(userHandle);
2086 synchronized (this) {
2087 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2088 if (admin == null) {
2091 if (admin.getUid() != Binder.getCallingUid()) {
2092 // Active device owners must remain active admins.
2093 if (isDeviceOwner(adminReceiver.getPackageName())) {
2096 mContext.enforceCallingOrSelfPermission(
2097 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2099 long ident = Binder.clearCallingIdentity();
2101 removeActiveAdminLocked(adminReceiver, userHandle);
2103 Binder.restoreCallingIdentity(ident);
2109 public void setPasswordQuality(ComponentName who, int quality) {
2113 Preconditions.checkNotNull(who, "ComponentName is null");
2114 final int userHandle = UserHandle.getCallingUserId();
2115 validateQualityConstant(quality);
2117 synchronized (this) {
2118 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2119 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2120 if (ap.passwordQuality != quality) {
2121 ap.passwordQuality = quality;
2122 saveSettingsLocked(userHandle);
2128 public int getPasswordQuality(ComponentName who, int userHandle) {
2130 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2132 enforceCrossUserPermission(userHandle);
2133 synchronized (this) {
2134 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2137 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2138 return admin != null ? admin.passwordQuality : mode;
2141 // Return strictest policy for this user and profiles that are visible from this user.
2142 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2143 for (UserInfo userInfo : profiles) {
2144 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2145 final int N = policy.mAdminList.size();
2146 for (int i=0; i<N; i++) {
2147 ActiveAdmin admin = policy.mAdminList.get(i);
2148 if (mode < admin.passwordQuality) {
2149 mode = admin.passwordQuality;
2158 public void setPasswordMinimumLength(ComponentName who, int length) {
2162 Preconditions.checkNotNull(who, "ComponentName is null");
2163 final int userHandle = UserHandle.getCallingUserId();
2164 synchronized (this) {
2165 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2166 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2167 if (ap.minimumPasswordLength != length) {
2168 ap.minimumPasswordLength = length;
2169 saveSettingsLocked(userHandle);
2175 public int getPasswordMinimumLength(ComponentName who, int userHandle) {
2179 enforceCrossUserPermission(userHandle);
2180 synchronized (this) {
2184 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2185 return admin != null ? admin.minimumPasswordLength : length;
2188 // Return strictest policy for this user and profiles that are visible from this user.
2189 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2190 for (UserInfo userInfo : profiles) {
2191 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2192 final int N = policy.mAdminList.size();
2193 for (int i=0; i<N; i++) {
2194 ActiveAdmin admin = policy.mAdminList.get(i);
2195 if (length < admin.minimumPasswordLength) {
2196 length = admin.minimumPasswordLength;
2205 public void setPasswordHistoryLength(ComponentName who, int length) {
2209 Preconditions.checkNotNull(who, "ComponentName is null");
2210 final int userHandle = UserHandle.getCallingUserId();
2211 synchronized (this) {
2212 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2213 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2214 if (ap.passwordHistoryLength != length) {
2215 ap.passwordHistoryLength = length;
2216 saveSettingsLocked(userHandle);
2222 public int getPasswordHistoryLength(ComponentName who, int userHandle) {
2226 enforceCrossUserPermission(userHandle);
2227 synchronized (this) {
2231 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2232 return admin != null ? admin.passwordHistoryLength : length;
2235 // Return strictest policy for this user and profiles that are visible from this user.
2236 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2237 for (UserInfo userInfo : profiles) {
2238 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2239 final int N = policy.mAdminList.size();
2240 for (int i = 0; i < N; i++) {
2241 ActiveAdmin admin = policy.mAdminList.get(i);
2242 if (length < admin.passwordHistoryLength) {
2243 length = admin.passwordHistoryLength;
2252 public void setPasswordExpirationTimeout(ComponentName who, long timeout) {
2256 Preconditions.checkNotNull(who, "ComponentName is null");
2257 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
2258 final int userHandle = UserHandle.getCallingUserId();
2259 synchronized (this) {
2260 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2261 DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
2262 // Calling this API automatically bumps the expiration date
2263 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
2264 ap.passwordExpirationDate = expiration;
2265 ap.passwordExpirationTimeout = timeout;
2267 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
2268 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
2269 .format(new Date(expiration)));
2271 saveSettingsLocked(userHandle);
2272 // in case this is the first one
2273 setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
2278 * Return a single admin's expiration cycle time, or the min of all cycle times.
2279 * Returns 0 if not configured.
2282 public long getPasswordExpirationTimeout(ComponentName who, int userHandle) {
2286 enforceCrossUserPermission(userHandle);
2287 synchronized (this) {
2291 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2292 return admin != null ? admin.passwordExpirationTimeout : timeout;
2295 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2296 for (UserInfo userInfo : profiles) {
2297 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2298 final int N = policy.mAdminList.size();
2299 for (int i = 0; i < N; i++) {
2300 ActiveAdmin admin = policy.mAdminList.get(i);
2301 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
2302 && timeout > admin.passwordExpirationTimeout)) {
2303 timeout = admin.passwordExpirationTimeout;
2312 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
2313 final int userId = UserHandle.getCallingUserId();
2314 List<String> changedProviders = null;
2316 synchronized (this) {
2317 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2318 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2319 if (activeAdmin.crossProfileWidgetProviders == null) {
2320 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
2322 List<String> providers = activeAdmin.crossProfileWidgetProviders;
2323 if (!providers.contains(packageName)) {
2324 providers.add(packageName);
2325 changedProviders = new ArrayList<>(providers);
2326 saveSettingsLocked(userId);
2330 if (changedProviders != null) {
2331 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
2339 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
2340 final int userId = UserHandle.getCallingUserId();
2341 List<String> changedProviders = null;
2343 synchronized (this) {
2344 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2345 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2346 if (activeAdmin.crossProfileWidgetProviders == null) {
2349 List<String> providers = activeAdmin.crossProfileWidgetProviders;
2350 if (providers.remove(packageName)) {
2351 changedProviders = new ArrayList<>(providers);
2352 saveSettingsLocked(userId);
2356 if (changedProviders != null) {
2357 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
2365 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
2366 synchronized (this) {
2367 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2368 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2369 if (activeAdmin.crossProfileWidgetProviders == null
2370 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
2373 if (Binder.getCallingUid() == Process.myUid()) {
2374 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
2376 return activeAdmin.crossProfileWidgetProviders;
2382 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
2383 * Returns 0 if not configured.
2385 private long getPasswordExpirationLocked(ComponentName who, int userHandle) {
2389 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2390 return admin != null ? admin.passwordExpirationDate : timeout;
2393 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2394 for (UserInfo userInfo : profiles) {
2395 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2396 final int N = policy.mAdminList.size();
2397 for (int i = 0; i < N; i++) {
2398 ActiveAdmin admin = policy.mAdminList.get(i);
2399 if (timeout == 0L || (admin.passwordExpirationDate != 0
2400 && timeout > admin.passwordExpirationDate)) {
2401 timeout = admin.passwordExpirationDate;
2409 public long getPasswordExpiration(ComponentName who, int userHandle) {
2413 enforceCrossUserPermission(userHandle);
2414 synchronized (this) {
2415 return getPasswordExpirationLocked(who, userHandle);
2420 public void setPasswordMinimumUpperCase(ComponentName who, int length) {
2424 Preconditions.checkNotNull(who, "ComponentName is null");
2425 final int userHandle = UserHandle.getCallingUserId();
2426 synchronized (this) {
2427 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2428 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2429 if (ap.minimumPasswordUpperCase != length) {
2430 ap.minimumPasswordUpperCase = length;
2431 saveSettingsLocked(userHandle);
2437 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle) {
2441 enforceCrossUserPermission(userHandle);
2442 synchronized (this) {
2446 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2447 return admin != null ? admin.minimumPasswordUpperCase : length;
2450 // Return strictest policy for this user and profiles that are visible from this user.
2451 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2452 for (UserInfo userInfo : profiles) {
2453 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2454 final int N = policy.mAdminList.size();
2455 for (int i=0; i<N; i++) {
2456 ActiveAdmin admin = policy.mAdminList.get(i);
2457 if (length < admin.minimumPasswordUpperCase) {
2458 length = admin.minimumPasswordUpperCase;
2467 public void setPasswordMinimumLowerCase(ComponentName who, int length) {
2468 Preconditions.checkNotNull(who, "ComponentName is null");
2469 final int userHandle = UserHandle.getCallingUserId();
2470 synchronized (this) {
2471 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2472 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2473 if (ap.minimumPasswordLowerCase != length) {
2474 ap.minimumPasswordLowerCase = length;
2475 saveSettingsLocked(userHandle);
2481 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle) {
2485 enforceCrossUserPermission(userHandle);
2486 synchronized (this) {
2490 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2491 return admin != null ? admin.minimumPasswordLowerCase : length;
2494 // Return strictest policy for this user and profiles that are visible from this user.
2495 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2496 for (UserInfo userInfo : profiles) {
2497 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2498 final int N = policy.mAdminList.size();
2499 for (int i=0; i<N; i++) {
2500 ActiveAdmin admin = policy.mAdminList.get(i);
2501 if (length < admin.minimumPasswordLowerCase) {
2502 length = admin.minimumPasswordLowerCase;
2511 public void setPasswordMinimumLetters(ComponentName who, int length) {
2515 Preconditions.checkNotNull(who, "ComponentName is null");
2516 final int userHandle = UserHandle.getCallingUserId();
2517 synchronized (this) {
2518 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2519 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2520 if (ap.minimumPasswordLetters != length) {
2521 ap.minimumPasswordLetters = length;
2522 saveSettingsLocked(userHandle);
2528 public int getPasswordMinimumLetters(ComponentName who, int userHandle) {
2532 enforceCrossUserPermission(userHandle);
2533 synchronized (this) {
2537 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2538 return admin != null ? admin.minimumPasswordLetters : length;
2541 // Return strictest policy for this user and profiles that are visible from this user.
2542 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2543 for (UserInfo userInfo : profiles) {
2544 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2545 final int N = policy.mAdminList.size();
2546 for (int i=0; i<N; i++) {
2547 ActiveAdmin admin = policy.mAdminList.get(i);
2548 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2551 if (length < admin.minimumPasswordLetters) {
2552 length = admin.minimumPasswordLetters;
2561 public void setPasswordMinimumNumeric(ComponentName who, int length) {
2565 Preconditions.checkNotNull(who, "ComponentName is null");
2566 final int userHandle = UserHandle.getCallingUserId();
2567 synchronized (this) {
2568 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2569 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2570 if (ap.minimumPasswordNumeric != length) {
2571 ap.minimumPasswordNumeric = length;
2572 saveSettingsLocked(userHandle);
2578 public int getPasswordMinimumNumeric(ComponentName who, int userHandle) {
2582 enforceCrossUserPermission(userHandle);
2583 synchronized (this) {
2587 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2588 return admin != null ? admin.minimumPasswordNumeric : length;
2591 // Return strictest policy for this user and profiles that are visible from this user.
2592 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2593 for (UserInfo userInfo : profiles) {
2594 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2595 final int N = policy.mAdminList.size();
2596 for (int i = 0; i < N; i++) {
2597 ActiveAdmin admin = policy.mAdminList.get(i);
2598 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2601 if (length < admin.minimumPasswordNumeric) {
2602 length = admin.minimumPasswordNumeric;
2611 public void setPasswordMinimumSymbols(ComponentName who, int length) {
2615 Preconditions.checkNotNull(who, "ComponentName is null");
2616 final int userHandle = UserHandle.getCallingUserId();
2617 synchronized (this) {
2618 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2619 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2620 if (ap.minimumPasswordSymbols != length) {
2621 ap.minimumPasswordSymbols = length;
2622 saveSettingsLocked(userHandle);
2628 public int getPasswordMinimumSymbols(ComponentName who, int userHandle) {
2632 enforceCrossUserPermission(userHandle);
2633 synchronized (this) {
2637 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2638 return admin != null ? admin.minimumPasswordSymbols : length;
2641 // Return strictest policy for this user and profiles that are visible from this user.
2642 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2643 for (UserInfo userInfo : profiles) {
2644 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2645 final int N = policy.mAdminList.size();
2646 for (int i=0; i<N; i++) {
2647 ActiveAdmin admin = policy.mAdminList.get(i);
2648 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2651 if (length < admin.minimumPasswordSymbols) {
2652 length = admin.minimumPasswordSymbols;
2661 public void setPasswordMinimumNonLetter(ComponentName who, int length) {
2665 Preconditions.checkNotNull(who, "ComponentName is null");
2666 final int userHandle = UserHandle.getCallingUserId();
2667 synchronized (this) {
2668 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2669 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2670 if (ap.minimumPasswordNonLetter != length) {
2671 ap.minimumPasswordNonLetter = length;
2672 saveSettingsLocked(userHandle);
2678 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle) {
2682 enforceCrossUserPermission(userHandle);
2683 synchronized (this) {
2687 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2688 return admin != null ? admin.minimumPasswordNonLetter : length;
2691 // Return strictest policy for this user and profiles that are visible from this user.
2692 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2693 for (UserInfo userInfo : profiles) {
2694 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2695 final int N = policy.mAdminList.size();
2696 for (int i=0; i<N; i++) {
2697 ActiveAdmin admin = policy.mAdminList.get(i);
2698 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2701 if (length < admin.minimumPasswordNonLetter) {
2702 length = admin.minimumPasswordNonLetter;
2711 public boolean isActivePasswordSufficient(int userHandle) {
2715 enforceCrossUserPermission(userHandle);
2717 synchronized (this) {
2719 // The active password is stored in the user that runs the launcher
2720 // If the user this is called from is part of a profile group, that is the parent
2722 UserInfo parent = getProfileParent(userHandle);
2723 int id = (parent == null) ? userHandle : parent.id;
2724 DevicePolicyData policy = getUserDataUnchecked(id);
2726 // This API can only be called by an active device admin,
2727 // so try to retrieve it to check that the caller is one.
2728 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2729 if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle)
2730 || policy.mActivePasswordLength < getPasswordMinimumLength(null, userHandle)) {
2733 if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2736 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(null, userHandle)
2737 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(null, userHandle)
2738 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(null, userHandle)
2739 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(null, userHandle)
2740 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(null, userHandle)
2741 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(null, userHandle);
2746 public int getCurrentFailedPasswordAttempts(int userHandle) {
2747 synchronized (this) {
2748 // This API can only be called by an active device admin,
2749 // so try to retrieve it to check that the caller is one.
2750 getActiveAdminForCallerLocked(null,
2751 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2753 // The active password is stored in the parent.
2754 UserInfo parent = getProfileParent(userHandle);
2755 int id = (parent == null) ? userHandle : parent.id;
2756 DevicePolicyData policy = getUserDataUnchecked(id);
2758 return policy.mFailedPasswordAttempts;
2763 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num) {
2767 Preconditions.checkNotNull(who, "ComponentName is null");
2768 final int userHandle = UserHandle.getCallingUserId();
2769 synchronized (this) {
2770 // This API can only be called by an active device admin,
2771 // so try to retrieve it to check that the caller is one.
2772 getActiveAdminForCallerLocked(who,
2773 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
2774 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2775 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2776 if (ap.maximumFailedPasswordsForWipe != num) {
2777 ap.maximumFailedPasswordsForWipe = num;
2778 saveSettingsLocked(userHandle);
2784 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle) {
2788 enforceCrossUserPermission(userHandle);
2789 synchronized (this) {
2790 ActiveAdmin admin = (who != null) ? getActiveAdminUncheckedLocked(who, userHandle)
2791 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
2792 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
2797 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
2799 return UserHandle.USER_NULL;
2801 enforceCrossUserPermission(userHandle);
2802 synchronized (this) {
2803 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
2804 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
2809 * Returns the admin with the strictest policy on maximum failed passwords for this user and all
2810 * profiles that are visible from this user. If the policy for the primary and any other profile
2811 * are equal, it returns the admin for the primary profile.
2812 * Returns {@code null} if none of them have that policy set.
2814 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(int userHandle) {
2816 ActiveAdmin strictestAdmin = null;
2817 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
2818 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2819 for (ActiveAdmin admin : policy.mAdminList) {
2820 if (admin.maximumFailedPasswordsForWipe ==
2821 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
2822 continue; // No max number of failed passwords policy set for this profile.
2825 // We always favor the primary profile if several profiles have the same value set.
2827 count > admin.maximumFailedPasswordsForWipe ||
2828 (userInfo.isPrimary() && count >= admin.maximumFailedPasswordsForWipe)) {
2829 count = admin.maximumFailedPasswordsForWipe;
2830 strictestAdmin = admin;
2834 return strictestAdmin;
2838 public boolean resetPassword(String passwordOrNull, int flags) {
2842 final int userHandle = UserHandle.getCallingUserId();
2843 enforceNotManagedProfile(userHandle, "reset the password");
2845 String password = passwordOrNull != null ? passwordOrNull : "";
2848 synchronized (this) {
2849 // This api can only be called by an active device admin,
2850 // so try to retrieve it to check that the caller is one.
2851 getActiveAdminForCallerLocked(null,
2852 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
2853 quality = getPasswordQuality(null, userHandle);
2854 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
2855 int realQuality = LockPatternUtils.computePasswordQuality(password);
2856 if (realQuality < quality
2857 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2858 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
2859 + Integer.toHexString(realQuality)
2860 + " does not meet required quality 0x"
2861 + Integer.toHexString(quality));
2864 quality = Math.max(realQuality, quality);
2866 int length = getPasswordMinimumLength(null, userHandle);
2867 if (password.length() < length) {
2868 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
2869 + " does not meet required length " + length);
2872 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2879 for (int i = 0; i < password.length(); i++) {
2880 char c = password.charAt(i);
2881 if (c >= 'A' && c <= 'Z') {
2884 } else if (c >= 'a' && c <= 'z') {
2887 } else if (c >= '0' && c <= '9') {
2895 int neededLetters = getPasswordMinimumLetters(null, userHandle);
2896 if(letters < neededLetters) {
2897 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
2898 + " does not meet required number of letters " + neededLetters);
2901 int neededNumbers = getPasswordMinimumNumeric(null, userHandle);
2902 if (numbers < neededNumbers) {
2903 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
2904 + " does not meet required number of numerical digits "
2908 int neededLowerCase = getPasswordMinimumLowerCase(null, userHandle);
2909 if (lowercase < neededLowerCase) {
2910 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
2911 + " does not meet required number of lowercase letters "
2915 int neededUpperCase = getPasswordMinimumUpperCase(null, userHandle);
2916 if (uppercase < neededUpperCase) {
2917 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
2918 + " does not meet required number of uppercase letters "
2922 int neededSymbols = getPasswordMinimumSymbols(null, userHandle);
2923 if (symbols < neededSymbols) {
2924 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
2925 + " does not meet required number of special symbols " + neededSymbols);
2928 int neededNonLetter = getPasswordMinimumNonLetter(null, userHandle);
2929 if (nonletter < neededNonLetter) {
2930 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
2931 + " does not meet required number of non-letter characters "
2938 int callingUid = Binder.getCallingUid();
2939 DevicePolicyData policy = getUserData(userHandle);
2940 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
2941 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
2945 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwnerOrInitializer(callingUid);
2946 boolean doNotAskCredentialsOnBoot =
2947 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
2948 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
2949 setDoNotAskCredentialsOnBoot();
2952 // Don't do this with the lock held, because it is going to call
2953 // back in to the service.
2954 long ident = Binder.clearCallingIdentity();
2956 LockPatternUtils utils = new LockPatternUtils(mContext);
2957 if (!TextUtils.isEmpty(password)) {
2958 utils.saveLockPassword(password, null, quality, userHandle);
2960 utils.clearLock(userHandle);
2962 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
2964 utils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
2965 UserHandle.USER_ALL);
2967 synchronized (this) {
2968 int newOwner = requireEntry ? callingUid : -1;
2969 if (policy.mPasswordOwner != newOwner) {
2970 policy.mPasswordOwner = newOwner;
2971 saveSettingsLocked(userHandle);
2975 Binder.restoreCallingIdentity(ident);
2981 private void setDoNotAskCredentialsOnBoot() {
2982 synchronized (this) {
2983 DevicePolicyData policyData = getUserData(UserHandle.USER_OWNER);
2984 if (!policyData.doNotAskCredentialsOnBoot) {
2985 policyData.doNotAskCredentialsOnBoot = true;
2986 saveSettingsLocked(UserHandle.USER_OWNER);
2992 public boolean getDoNotAskCredentialsOnBoot() {
2993 mContext.enforceCallingOrSelfPermission(
2994 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
2995 synchronized (this) {
2996 DevicePolicyData policyData = getUserData(UserHandle.USER_OWNER);
2997 return policyData.doNotAskCredentialsOnBoot;
3002 public void setMaximumTimeToLock(ComponentName who, long timeMs) {
3006 Preconditions.checkNotNull(who, "ComponentName is null");
3007 final int userHandle = UserHandle.getCallingUserId();
3008 synchronized (this) {
3009 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3010 DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
3011 if (ap.maximumTimeToUnlock != timeMs) {
3012 ap.maximumTimeToUnlock = timeMs;
3013 saveSettingsLocked(userHandle);
3014 updateMaximumTimeToLockLocked(getUserData(userHandle));
3019 void updateMaximumTimeToLockLocked(DevicePolicyData policy) {
3020 long timeMs = getMaximumTimeToLock(null, policy.mUserHandle);
3021 if (policy.mLastMaximumTimeToLock == timeMs) {
3025 long ident = Binder.clearCallingIdentity();
3028 timeMs = Integer.MAX_VALUE;
3030 // Make sure KEEP_SCREEN_ON is disabled, since that
3031 // would allow bypassing of the maximum time to lock.
3032 Settings.Global.putInt(mContext.getContentResolver(),
3033 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
3036 policy.mLastMaximumTimeToLock = timeMs;
3037 mPowerManagerInternal.setMaximumScreenOffTimeoutFromDeviceAdmin((int)timeMs);
3039 Binder.restoreCallingIdentity(ident);
3044 public long getMaximumTimeToLock(ComponentName who, int userHandle) {
3048 enforceCrossUserPermission(userHandle);
3049 synchronized (this) {
3053 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3054 return admin != null ? admin.maximumTimeToUnlock : time;
3057 // Return strictest policy for this user and profiles that are visible from this user.
3058 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3059 for (UserInfo userInfo : profiles) {
3060 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
3061 final int N = policy.mAdminList.size();
3062 for (int i=0; i<N; i++) {
3063 ActiveAdmin admin = policy.mAdminList.get(i);
3065 time = admin.maximumTimeToUnlock;
3066 } else if (admin.maximumTimeToUnlock != 0
3067 && time > admin.maximumTimeToUnlock) {
3068 time = admin.maximumTimeToUnlock;
3077 public void lockNow() {
3081 synchronized (this) {
3082 // This API can only be called by an active device admin,
3083 // so try to retrieve it to check that the caller is one.
3084 getActiveAdminForCallerLocked(null,
3085 DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
3090 private void lockNowUnchecked() {
3091 long ident = Binder.clearCallingIdentity();
3093 // Power off the display
3094 mPowerManager.goToSleep(SystemClock.uptimeMillis(),
3095 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
3096 // Ensure the device is locked
3097 new LockPatternUtils(mContext).requireStrongAuth(
3098 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, UserHandle.USER_ALL);
3099 getWindowManager().lockNow(null);
3100 } catch (RemoteException e) {
3102 Binder.restoreCallingIdentity(ident);
3106 private boolean isExtStorageEncrypted() {
3107 String state = SystemProperties.get("vold.decrypt");
3108 return !"".equals(state);
3112 public void enforceCanManageCaCerts(ComponentName who) {
3114 if (!isCallerDelegatedCertInstaller()) {
3115 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
3118 synchronized (this) {
3119 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3124 private boolean isCallerDelegatedCertInstaller() {
3125 final int callingUid = Binder.getCallingUid();
3126 final int userHandle = UserHandle.getUserId(callingUid);
3127 synchronized (this) {
3128 final DevicePolicyData policy = getUserData(userHandle);
3129 if (policy.mDelegatedCertInstallerPackage == null) {
3134 int uid = mContext.getPackageManager().getPackageUid(
3135 policy.mDelegatedCertInstallerPackage, userHandle);
3136 return uid == callingUid;
3137 } catch (NameNotFoundException e) {
3144 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
3145 enforceCanManageCaCerts(admin);
3149 X509Certificate cert = parseCert(certBuffer);
3150 pemCert = Credentials.convertToPem(cert);
3151 } catch (CertificateException ce) {
3152 Log.e(LOG_TAG, "Problem converting cert", ce);
3154 } catch (IOException ioe) {
3155 Log.e(LOG_TAG, "Problem reading cert", ioe);
3159 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3160 final long id = Binder.clearCallingIdentity();
3162 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
3164 keyChainConnection.getService().installCaCertificate(pemCert);
3166 } catch (RemoteException e) {
3167 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
3169 keyChainConnection.close();
3171 } catch (InterruptedException e1) {
3172 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
3173 Thread.currentThread().interrupt();
3175 Binder.restoreCallingIdentity(id);
3180 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
3181 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
3182 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
3187 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
3188 enforceCanManageCaCerts(admin);
3190 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3191 final long id = Binder.clearCallingIdentity();
3193 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
3195 for (int i = 0 ; i < aliases.length; i++) {
3196 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
3198 } catch (RemoteException e) {
3199 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
3201 keyChainConnection.close();
3203 } catch (InterruptedException ie) {
3204 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
3205 Thread.currentThread().interrupt();
3207 Binder.restoreCallingIdentity(id);
3212 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, String alias) {
3214 if (!isCallerDelegatedCertInstaller()) {
3215 throw new SecurityException("who == null, but caller is not cert installer");
3218 synchronized (this) {
3219 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3222 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3223 final long id = Binder.clearCallingIdentity();
3225 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
3227 IKeyChainService keyChain = keyChainConnection.getService();
3228 return keyChain.installKeyPair(privKey, cert, alias);
3229 } catch (RemoteException e) {
3230 Log.e(LOG_TAG, "Installing certificate", e);
3232 keyChainConnection.close();
3234 } catch (InterruptedException e) {
3235 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
3236 Thread.currentThread().interrupt();
3238 Binder.restoreCallingIdentity(id);
3244 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
3245 final IBinder response) {
3246 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
3247 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
3251 final UserHandle caller = Binder.getCallingUserHandle();
3252 // If there is a profile owner, redirect to that; otherwise query the device owner.
3253 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
3254 if (aliasChooser == null && caller.isOwner()) {
3255 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdmin();
3256 if (deviceOwnerAdmin != null) {
3257 aliasChooser = deviceOwnerAdmin.info.getComponent();
3260 if (aliasChooser == null) {
3261 sendPrivateKeyAliasResponse(null, response);
3265 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
3266 intent.setComponent(aliasChooser);
3267 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
3268 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
3269 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
3270 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
3272 final long id = Binder.clearCallingIdentity();
3274 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
3276 public void onReceive(Context context, Intent intent) {
3277 final String chosenAlias = getResultData();
3278 sendPrivateKeyAliasResponse(chosenAlias, response);
3280 }, null, Activity.RESULT_OK, null, null);
3282 Binder.restoreCallingIdentity(id);
3286 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
3287 final IKeyChainAliasCallback keyChainAliasResponse =
3288 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
3289 new AsyncTask<Void, Void, Void>() {
3291 protected Void doInBackground(Void... unused) {
3293 keyChainAliasResponse.alias(alias);
3294 } catch (Exception e) {
3295 // Catch everything (not just RemoteException): caller could throw a
3296 // RuntimeException back across processes.
3297 Log.e(LOG_TAG, "error while responding to callback", e);
3305 public void setCertInstallerPackage(ComponentName who, String installerPackage)
3306 throws SecurityException {
3307 int userHandle = UserHandle.getCallingUserId();
3308 synchronized (this) {
3309 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3310 DevicePolicyData policy = getUserData(userHandle);
3311 policy.mDelegatedCertInstallerPackage = installerPackage;
3312 saveSettingsLocked(userHandle);
3317 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
3318 int userHandle = UserHandle.getCallingUserId();
3319 synchronized (this) {
3320 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3321 DevicePolicyData policy = getUserData(userHandle);
3322 return policy.mDelegatedCertInstallerPackage;
3326 private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
3327 if (wipeExtRequested) {
3328 StorageManager sm = (StorageManager) mContext.getSystemService(
3329 Context.STORAGE_SERVICE);
3330 sm.wipeAdoptableDisks();
3333 RecoverySystem.rebootWipeUserData(mContext, reason);
3334 } catch (IOException | SecurityException e) {
3335 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
3340 public void wipeData(int flags, final int userHandle) {
3344 enforceCrossUserPermission(userHandle);
3345 final String source;
3346 synchronized (this) {
3347 // This API can only be called by an active device admin,
3348 // so try to retrieve it to check that the caller is one.
3349 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
3350 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
3352 final ComponentName cname = admin.info.getComponent();
3353 if (cname != null) {
3354 source = cname.flattenToShortString();
3356 source = admin.info.getPackageName();
3359 long ident = Binder.clearCallingIdentity();
3361 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
3362 boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName())
3363 && !hasUserSetupCompleted(userHandle);
3364 if (userHandle != UserHandle.USER_OWNER
3365 || !(isDeviceOwner(admin.info.getPackageName())
3366 || ownsInitialization)) {
3367 throw new SecurityException(
3368 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
3370 PersistentDataBlockManager manager = (PersistentDataBlockManager)
3371 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
3372 if (manager != null) {
3377 Binder.restoreCallingIdentity(ident);
3380 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
3381 wipeDeviceNoLock(wipeExtRequested, userHandle,
3382 "DevicePolicyManager.wipeData() from " + source);
3385 private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
3386 long ident = Binder.clearCallingIdentity();
3388 if (userHandle == UserHandle.USER_OWNER) {
3389 wipeDataNoLock(wipeExtRequested, reason);
3391 mHandler.post(new Runnable() {
3395 IActivityManager am = ActivityManagerNative.getDefault();
3396 if (am.getCurrentUser().id == userHandle) {
3397 am.switchUser(UserHandle.USER_OWNER);
3400 boolean isManagedProfile = isManagedProfile(userHandle);
3401 if (!mUserManager.removeUser(userHandle)) {
3402 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
3403 } else if (isManagedProfile) {
3404 sendWipeProfileNotification();
3406 } catch (RemoteException re) {
3413 Binder.restoreCallingIdentity(ident);
3417 private void sendWipeProfileNotification() {
3418 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
3419 Notification notification = new Notification.Builder(mContext)
3420 .setSmallIcon(android.R.drawable.stat_sys_warning)
3421 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
3422 .setContentText(contentText)
3423 .setColor(mContext.getColor(R.color.system_notification_accent_color))
3424 .setStyle(new Notification.BigTextStyle().bigText(contentText))
3426 getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
3429 private void clearWipeProfileNotification() {
3430 getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
3434 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
3438 enforceCrossUserPermission(userHandle);
3439 mContext.enforceCallingOrSelfPermission(
3440 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3442 synchronized (this) {
3443 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
3444 if (admin == null) {
3446 result.sendResult(null);
3447 } catch (RemoteException e) {
3451 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
3452 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3453 intent.setComponent(admin.info.getComponent());
3454 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
3455 null, new BroadcastReceiver() {
3457 public void onReceive(Context context, Intent intent) {
3459 result.sendResult(getResultExtras(false));
3460 } catch (RemoteException e) {
3463 }, null, Activity.RESULT_OK, null, null);
3468 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
3469 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
3473 enforceCrossUserPermission(userHandle);
3474 enforceNotManagedProfile(userHandle, "set the active password");
3476 mContext.enforceCallingOrSelfPermission(
3477 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3478 DevicePolicyData p = getUserData(userHandle);
3480 validateQualityConstant(quality);
3482 synchronized (this) {
3483 if (p.mActivePasswordQuality != quality || p.mActivePasswordLength != length
3484 || p.mFailedPasswordAttempts != 0 || p.mActivePasswordLetters != letters
3485 || p.mActivePasswordUpperCase != uppercase
3486 || p.mActivePasswordLowerCase != lowercase
3487 || p.mActivePasswordNumeric != numbers
3488 || p.mActivePasswordSymbols != symbols
3489 || p.mActivePasswordNonLetter != nonletter) {
3490 long ident = Binder.clearCallingIdentity();
3492 p.mActivePasswordQuality = quality;
3493 p.mActivePasswordLength = length;
3494 p.mActivePasswordLetters = letters;
3495 p.mActivePasswordLowerCase = lowercase;
3496 p.mActivePasswordUpperCase = uppercase;
3497 p.mActivePasswordNumeric = numbers;
3498 p.mActivePasswordSymbols = symbols;
3499 p.mActivePasswordNonLetter = nonletter;
3500 p.mFailedPasswordAttempts = 0;
3501 saveSettingsLocked(userHandle);
3502 updatePasswordExpirationsLocked(userHandle);
3503 setExpirationAlarmCheckLocked(mContext, p);
3504 sendAdminCommandToSelfAndProfilesLocked(
3505 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
3506 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
3508 Binder.restoreCallingIdentity(ident);
3515 * Called any time the device password is updated. Resets all password expiration clocks.
3517 private void updatePasswordExpirationsLocked(int userHandle) {
3518 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3519 for (UserInfo userInfo : profiles) {
3520 int profileId = userInfo.id;
3521 DevicePolicyData policy = getUserDataUnchecked(profileId);
3522 final int N = policy.mAdminList.size();
3524 for (int i=0; i<N; i++) {
3525 ActiveAdmin admin = policy.mAdminList.get(i);
3526 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
3527 long timeout = admin.passwordExpirationTimeout;
3528 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3529 admin.passwordExpirationDate = expiration;
3533 saveSettingsLocked(profileId);
3538 public void reportFailedPasswordAttempt(int userHandle) {
3539 enforceCrossUserPermission(userHandle);
3540 enforceNotManagedProfile(userHandle, "report failed password attempt");
3541 mContext.enforceCallingOrSelfPermission(
3542 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3544 long ident = Binder.clearCallingIdentity();
3546 boolean wipeData = false;
3548 synchronized (this) {
3549 DevicePolicyData policy = getUserData(userHandle);
3550 policy.mFailedPasswordAttempts++;
3551 saveSettingsLocked(userHandle);
3553 ActiveAdmin strictestAdmin =
3554 getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
3555 int max = strictestAdmin != null
3556 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
3557 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
3558 // Wipe the user/profile associated with the policy that was violated. This
3559 // is not necessarily calling user: if the policy that fired was from a
3560 // managed profile rather than the main user profile, we wipe former only.
3562 identifier = strictestAdmin.getUserHandle().getIdentifier();
3564 sendAdminCommandToSelfAndProfilesLocked(
3565 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
3566 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3570 // Call without holding lock.
3571 wipeDeviceNoLock(false, identifier,
3572 "reportFailedPasswordAttempt()");
3575 Binder.restoreCallingIdentity(ident);
3580 public void reportSuccessfulPasswordAttempt(int userHandle) {
3581 enforceCrossUserPermission(userHandle);
3582 mContext.enforceCallingOrSelfPermission(
3583 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3585 synchronized (this) {
3586 DevicePolicyData policy = getUserData(userHandle);
3587 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
3588 long ident = Binder.clearCallingIdentity();
3590 policy.mFailedPasswordAttempts = 0;
3591 policy.mPasswordOwner = -1;
3592 saveSettingsLocked(userHandle);
3594 sendAdminCommandToSelfAndProfilesLocked(
3595 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
3596 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3599 Binder.restoreCallingIdentity(ident);
3606 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
3607 String exclusionList) {
3611 synchronized(this) {
3612 Preconditions.checkNotNull(who, "ComponentName is null");
3614 // Only check if owner has set global proxy. We don't allow other users to set it.
3615 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3616 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3617 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
3619 // Scan through active admins and find if anyone has already
3620 // set the global proxy.
3621 Set<ComponentName> compSet = policy.mAdminMap.keySet();
3622 for (ComponentName component : compSet) {
3623 ActiveAdmin ap = policy.mAdminMap.get(component);
3624 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
3625 // Another admin already sets the global proxy
3626 // Return it to the caller.
3631 // If the user is not the owner, don't set the global proxy. Fail silently.
3632 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3633 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
3634 + UserHandle.getCallingUserId() + " is not permitted.");
3637 if (proxySpec == null) {
3638 admin.specifiesGlobalProxy = false;
3639 admin.globalProxySpec = null;
3640 admin.globalProxyExclusionList = null;
3643 admin.specifiesGlobalProxy = true;
3644 admin.globalProxySpec = proxySpec;
3645 admin.globalProxyExclusionList = exclusionList;
3648 // Reset the global proxy accordingly
3649 // Do this using system permissions, as apps cannot write to secure settings
3650 long origId = Binder.clearCallingIdentity();
3652 resetGlobalProxyLocked(policy);
3654 Binder.restoreCallingIdentity(origId);
3661 public ComponentName getGlobalProxyAdmin(int userHandle) {
3665 enforceCrossUserPermission(userHandle);
3666 synchronized(this) {
3667 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3668 // Scan through active admins and find if anyone has already
3669 // set the global proxy.
3670 final int N = policy.mAdminList.size();
3671 for (int i = 0; i < N; i++) {
3672 ActiveAdmin ap = policy.mAdminList.get(i);
3673 if (ap.specifiesGlobalProxy) {
3674 // Device admin sets the global proxy
3675 // Return it to the caller.
3676 return ap.info.getComponent();
3680 // No device admin sets the global proxy.
3685 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
3686 synchronized (this) {
3687 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3689 long token = Binder.clearCallingIdentity();
3691 ConnectivityManager connectivityManager = (ConnectivityManager)
3692 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
3693 connectivityManager.setGlobalProxy(proxyInfo);
3695 Binder.restoreCallingIdentity(token);
3699 private void resetGlobalProxyLocked(DevicePolicyData policy) {
3700 final int N = policy.mAdminList.size();
3701 for (int i = 0; i < N; i++) {
3702 ActiveAdmin ap = policy.mAdminList.get(i);
3703 if (ap.specifiesGlobalProxy) {
3704 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
3708 // No device admins defining global proxies - reset global proxy settings to none
3709 saveGlobalProxyLocked(null, null);
3712 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
3713 if (exclusionList == null) {
3716 if (proxySpec == null) {
3719 // Remove white spaces
3720 proxySpec = proxySpec.trim();
3721 String data[] = proxySpec.split(":");
3722 int proxyPort = 8080;
3723 if (data.length > 1) {
3725 proxyPort = Integer.parseInt(data[1]);
3726 } catch (NumberFormatException e) {}
3728 exclusionList = exclusionList.trim();
3729 ContentResolver res = mContext.getContentResolver();
3731 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
3732 if (!proxyProperties.isValid()) {
3733 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
3736 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
3737 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
3738 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3743 * Set the storage encryption request for a single admin. Returns the new total request
3744 * status (for all admins).
3747 public int setStorageEncryption(ComponentName who, boolean encrypt) {
3749 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3751 Preconditions.checkNotNull(who, "ComponentName is null");
3752 final int userHandle = UserHandle.getCallingUserId();
3753 synchronized (this) {
3754 // Check for permissions
3755 // Only owner can set storage encryption
3756 if (userHandle != UserHandle.USER_OWNER
3757 || UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3758 Slog.w(LOG_TAG, "Only owner is allowed to set storage encryption. User "
3759 + UserHandle.getCallingUserId() + " is not permitted.");
3763 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3764 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
3766 // Quick exit: If the filesystem does not support encryption, we can exit early.
3767 if (!isEncryptionSupported()) {
3768 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3771 // (1) Record the value for the admin so it's sticky
3772 if (ap.encryptionRequested != encrypt) {
3773 ap.encryptionRequested = encrypt;
3774 saveSettingsLocked(userHandle);
3777 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3778 // (2) Compute "max" for all admins
3779 boolean newRequested = false;
3780 final int N = policy.mAdminList.size();
3781 for (int i = 0; i < N; i++) {
3782 newRequested |= policy.mAdminList.get(i).encryptionRequested;
3785 // Notify OS of new request
3786 setEncryptionRequested(newRequested);
3788 // Return the new global request status
3790 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3791 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3796 * Get the current storage encryption request status for a given admin, or aggregate of all
3800 public boolean getStorageEncryption(ComponentName who, int userHandle) {
3804 enforceCrossUserPermission(userHandle);
3805 synchronized (this) {
3806 // Check for permissions if a particular caller is specified
3808 // When checking for a single caller, status is based on caller's request
3809 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
3810 return ap != null ? ap.encryptionRequested : false;
3813 // If no particular caller is specified, return the aggregate set of requests.
3814 // This is short circuited by returning true on the first hit.
3815 DevicePolicyData policy = getUserData(userHandle);
3816 final int N = policy.mAdminList.size();
3817 for (int i = 0; i < N; i++) {
3818 if (policy.mAdminList.get(i).encryptionRequested) {
3827 * Get the current encryption status of the device.
3830 public int getStorageEncryptionStatus(int userHandle) {
3832 // Ok to return current status.
3834 enforceCrossUserPermission(userHandle);
3835 return getEncryptionStatus();
3839 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
3841 private boolean isEncryptionSupported() {
3842 // Note, this can be implemented as
3843 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3844 // But is provided as a separate internal method if there's a faster way to do a
3845 // simple check for supported-or-not.
3846 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3850 * Hook to low-levels: Reporting the current status of encryption.
3851 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
3852 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
3853 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, or
3854 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
3856 private int getEncryptionStatus() {
3857 String status = SystemProperties.get("ro.crypto.state", "unsupported");
3858 if ("encrypted".equalsIgnoreCase(status)) {
3859 final long token = Binder.clearCallingIdentity();
3861 return LockPatternUtils.isDeviceEncrypted()
3862 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3863 : DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
3865 Binder.restoreCallingIdentity(token);
3867 } else if ("unencrypted".equalsIgnoreCase(status)) {
3868 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3870 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3875 * Hook to low-levels: If needed, record the new admin setting for encryption.
3877 private void setEncryptionRequested(boolean encrypt) {
3882 * Set whether the screen capture is disabled for the user managed by the specified admin.
3885 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
3889 Preconditions.checkNotNull(who, "ComponentName is null");
3890 final int userHandle = UserHandle.getCallingUserId();
3891 synchronized (this) {
3892 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3893 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3894 if (ap.disableScreenCapture != disabled) {
3895 ap.disableScreenCapture = disabled;
3896 saveSettingsLocked(userHandle);
3897 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
3903 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
3904 * active admin (if given admin is null).
3907 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
3911 synchronized (this) {
3913 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3914 return (admin != null) ? admin.disableScreenCapture : false;
3917 DevicePolicyData policy = getUserData(userHandle);
3918 final int N = policy.mAdminList.size();
3919 for (int i = 0; i < N; i++) {
3920 ActiveAdmin admin = policy.mAdminList.get(i);
3921 if (admin.disableScreenCapture) {
3929 private void updateScreenCaptureDisabledInWindowManager(int userHandle, boolean disabled) {
3930 long ident = Binder.clearCallingIdentity();
3932 getWindowManager().setScreenCaptureDisabled(userHandle, disabled);
3933 } catch (RemoteException e) {
3934 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
3936 Binder.restoreCallingIdentity(ident);
3941 * Set whether auto time is required by the specified admin (must be device owner).
3944 public void setAutoTimeRequired(ComponentName who, boolean required) {
3948 Preconditions.checkNotNull(who, "ComponentName is null");
3949 final int userHandle = UserHandle.getCallingUserId();
3950 synchronized (this) {
3951 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3952 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3953 if (admin.requireAutoTime != required) {
3954 admin.requireAutoTime = required;
3955 saveSettingsLocked(userHandle);
3959 // Turn AUTO_TIME on in settings if it is required
3961 long ident = Binder.clearCallingIdentity();
3963 Settings.Global.putInt(mContext.getContentResolver(),
3964 Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
3966 Binder.restoreCallingIdentity(ident);
3972 * Returns whether or not auto time is required by the device owner.
3975 public boolean getAutoTimeRequired() {
3979 synchronized (this) {
3980 ActiveAdmin deviceOwner = getDeviceOwnerAdmin();
3981 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
3986 * The system property used to share the state of the camera. The native camera service
3987 * is expected to read this property and act accordingly. The userId should be appended
3990 public static final String SYSTEM_PROP_DISABLE_CAMERA_PREFIX = "sys.secpolicy.camera.off_";
3993 * Disables all device cameras according to the specified admin.
3996 public void setCameraDisabled(ComponentName who, boolean disabled) {
4000 Preconditions.checkNotNull(who, "ComponentName is null");
4001 final int userHandle = UserHandle.getCallingUserId();
4002 synchronized (this) {
4003 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4004 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
4005 if (ap.disableCamera != disabled) {
4006 ap.disableCamera = disabled;
4007 saveSettingsLocked(userHandle);
4009 syncDeviceCapabilitiesLocked(getUserData(userHandle));
4014 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
4018 public boolean getCameraDisabled(ComponentName who, int userHandle) {
4022 synchronized (this) {
4024 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4025 return (admin != null) ? admin.disableCamera : false;
4028 DevicePolicyData policy = getUserData(userHandle);
4029 // Determine whether or not the device camera is disabled for any active admins.
4030 final int N = policy.mAdminList.size();
4031 for (int i = 0; i < N; i++) {
4032 ActiveAdmin admin = policy.mAdminList.get(i);
4033 if (admin.disableCamera) {
4042 * Selectively disable keyguard features.
4045 public void setKeyguardDisabledFeatures(ComponentName who, int which) {
4049 Preconditions.checkNotNull(who, "ComponentName is null");
4050 final int userHandle = UserHandle.getCallingUserId();
4051 if (isManagedProfile(userHandle)) {
4052 which = which & PROFILE_KEYGUARD_FEATURES;
4054 synchronized (this) {
4055 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4056 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
4057 if (ap.disabledKeyguardFeatures != which) {
4058 ap.disabledKeyguardFeatures = which;
4059 saveSettingsLocked(userHandle);
4061 syncDeviceCapabilitiesLocked(getUserData(userHandle));
4066 * Gets the disabled state for features in keyguard for the given admin,
4067 * or the aggregate of all active admins if who is null.
4070 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle) {
4074 enforceCrossUserPermission(userHandle);
4075 long ident = Binder.clearCallingIdentity();
4077 synchronized (this) {
4079 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4080 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
4083 UserInfo user = mUserManager.getUserInfo(userHandle);
4084 final List<UserInfo> profiles;
4085 if (user.isManagedProfile()) {
4086 // If we are being asked about a managed profile just return
4087 // keyguard features disabled by admins in the profile.
4088 profiles = new ArrayList<UserInfo>(1);
4091 // Otherwise return those set by admins in the user
4092 // and its profiles.
4093 profiles = mUserManager.getProfiles(userHandle);
4096 // Determine which keyguard features are disabled by any active admin.
4098 for (UserInfo userInfo : profiles) {
4099 DevicePolicyData policy = getUserData(userInfo.id);
4100 final int N = policy.mAdminList.size();
4101 for (int i = 0; i < N; i++) {
4102 ActiveAdmin admin = policy.mAdminList.get(i);
4103 if (userInfo.id == userHandle || !userInfo.isManagedProfile()) {
4104 // If we are being asked explictly about this user
4105 // return all disabled features even if its a managed profile.
4106 which |= admin.disabledKeyguardFeatures;
4108 // Otherwise a managed profile is only allowed to disable
4109 // some features on the parent user.
4110 which |= (admin.disabledKeyguardFeatures
4111 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
4118 Binder.restoreCallingIdentity(ident);
4123 public boolean setDeviceOwner(String packageName, String ownerName) {
4127 if (packageName == null
4128 || !DeviceOwner.isInstalled(packageName, mContext.getPackageManager())) {
4129 throw new IllegalArgumentException("Invalid package name " + packageName
4130 + " for device owner");
4132 synchronized (this) {
4133 enforceCanSetDeviceOwner();
4135 // Shutting down backup manager service permanently.
4136 long ident = Binder.clearCallingIdentity();
4138 IBackupManager ibm = IBackupManager.Stub.asInterface(
4139 ServiceManager.getService(Context.BACKUP_SERVICE));
4140 ibm.setBackupServiceActive(UserHandle.USER_OWNER, false);
4141 } catch (RemoteException e) {
4142 throw new IllegalStateException("Failed deactivating backup service.", e);
4144 Binder.restoreCallingIdentity(ident);
4147 if (mDeviceOwner == null) {
4148 // Device owner is not set and does not exist, set it.
4149 mDeviceOwner = DeviceOwner.createWithDeviceOwner(packageName, ownerName);
4151 // Device owner state already exists, update it.
4152 mDeviceOwner.setDeviceOwner(packageName, ownerName);
4154 mDeviceOwner.writeOwnerFile();
4155 updateDeviceOwnerLocked();
4156 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
4158 ident = Binder.clearCallingIdentity();
4160 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
4162 Binder.restoreCallingIdentity(ident);
4169 public boolean isDeviceOwner(String packageName) {
4173 synchronized (this) {
4174 return mDeviceOwner != null
4175 && mDeviceOwner.hasDeviceOwner()
4176 && mDeviceOwner.getDeviceOwnerPackageName().equals(packageName);
4181 public String getDeviceOwner() {
4185 synchronized (this) {
4186 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
4187 return mDeviceOwner.getDeviceOwnerPackageName();
4194 public String getDeviceOwnerName() {
4198 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
4199 synchronized (this) {
4200 if (mDeviceOwner == null || !mDeviceOwner.hasDeviceOwner()) {
4203 String deviceOwnerPackage = mDeviceOwner.getDeviceOwnerPackageName();
4204 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_OWNER);
4208 // Returns the active device owner or null if there is no device owner.
4209 private ActiveAdmin getDeviceOwnerAdmin() {
4210 String deviceOwnerPackageName = getDeviceOwner();
4211 if (deviceOwnerPackageName == null) {
4215 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
4216 final int n = policy.mAdminList.size();
4217 for (int i = 0; i < n; i++) {
4218 ActiveAdmin admin = policy.mAdminList.get(i);
4219 if (deviceOwnerPackageName.equals(admin.info.getPackageName())) {
4227 public void clearDeviceOwner(String packageName) {
4228 Preconditions.checkNotNull(packageName, "packageName is null");
4230 int uid = mContext.getPackageManager().getPackageUid(packageName, 0);
4231 if (uid != Binder.getCallingUid()) {
4232 throw new SecurityException("Invalid packageName");
4234 } catch (NameNotFoundException e) {
4235 throw new SecurityException(e);
4237 if (!isDeviceOwner(packageName)) {
4238 throw new SecurityException("clearDeviceOwner can only be called by the device owner");
4240 synchronized (this) {
4241 clearUserPoliciesLocked(new UserHandle(UserHandle.USER_OWNER));
4242 if (mDeviceOwner != null) {
4243 mDeviceOwner.clearDeviceOwner();
4244 mDeviceOwner.writeOwnerFile();
4245 updateDeviceOwnerLocked();
4251 public boolean setDeviceInitializer(ComponentName who, ComponentName initializer) {
4255 if (initializer == null || !DeviceOwner.isInstalled(
4256 initializer.getPackageName(), mContext.getPackageManager())) {
4257 throw new IllegalArgumentException("Invalid component name " + initializer
4258 + " for device initializer");
4260 boolean isInitializerSystemApp;
4262 isInitializerSystemApp = isSystemApp(AppGlobals.getPackageManager(),
4263 initializer.getPackageName(), Binder.getCallingUserHandle().getIdentifier());
4264 } catch (RemoteException | IllegalArgumentException e) {
4265 isInitializerSystemApp = false;
4266 Slog.e(LOG_TAG, "Fail to check if device initialzer is system app.", e);
4268 if (!isInitializerSystemApp) {
4269 throw new IllegalArgumentException("Only system app can be set as device initializer.");
4271 synchronized (this) {
4272 enforceCanSetDeviceInitializer(who);
4274 if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4275 throw new IllegalStateException(
4276 "Trying to set device initializer but device initializer is already set.");
4279 if (mDeviceOwner == null) {
4280 // Device owner state does not exist, create it.
4281 mDeviceOwner = DeviceOwner.createWithDeviceInitializer(initializer);
4283 // Device owner already exists, update it.
4284 mDeviceOwner.setDeviceInitializer(initializer);
4287 addDeviceInitializerToLockTaskPackagesLocked(UserHandle.USER_OWNER);
4288 mDeviceOwner.writeOwnerFile();
4293 private void enforceCanSetDeviceInitializer(ComponentName who) {
4295 mContext.enforceCallingOrSelfPermission(
4296 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
4297 if (hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4298 throw new IllegalStateException(
4299 "Trying to set device initializer but device is already provisioned.");
4302 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4307 public boolean isDeviceInitializer(String packageName) {
4311 synchronized (this) {
4312 return mDeviceOwner != null
4313 && mDeviceOwner.hasDeviceInitializer()
4314 && mDeviceOwner.getDeviceInitializerPackageName().equals(packageName);
4319 public String getDeviceInitializer() {
4323 synchronized (this) {
4324 if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4325 return mDeviceOwner.getDeviceInitializerPackageName();
4332 public ComponentName getDeviceInitializerComponent() {
4336 synchronized (this) {
4337 if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4338 return mDeviceOwner.getDeviceInitializerComponent();
4345 public void clearDeviceInitializer(ComponentName who) {
4349 Preconditions.checkNotNull(who, "ComponentName is null");
4351 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, UserHandle.getCallingUserId());
4353 if (admin.getUid() != Binder.getCallingUid()) {
4354 throw new SecurityException("Admin " + who + " is not owned by uid "
4355 + Binder.getCallingUid());
4358 if (!isDeviceInitializer(admin.info.getPackageName())
4359 && !isDeviceOwner(admin.info.getPackageName())) {
4360 throw new SecurityException(
4361 "clearDeviceInitializer can only be called by the device initializer/owner");
4363 synchronized (this) {
4364 long ident = Binder.clearCallingIdentity();
4366 if (mDeviceOwner != null) {
4367 mDeviceOwner.clearDeviceInitializer();
4368 mDeviceOwner.writeOwnerFile();
4371 Binder.restoreCallingIdentity(ident);
4377 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
4382 || !DeviceOwner.isInstalledForUser(who.getPackageName(), userHandle)) {
4383 throw new IllegalArgumentException("Component " + who
4384 + " not installed for userId:" + userHandle);
4386 synchronized (this) {
4387 enforceCanSetProfileOwner(userHandle);
4388 if (mDeviceOwner == null) {
4389 // Device owner state does not exist, create it.
4390 mDeviceOwner = DeviceOwner.createWithProfileOwner(who, ownerName,
4393 // Device owner state already exists, update it.
4394 mDeviceOwner.setProfileOwner(who, ownerName, userHandle);
4396 mDeviceOwner.writeOwnerFile();
4402 public void clearProfileOwner(ComponentName who) {
4406 UserHandle callingUser = Binder.getCallingUserHandle();
4407 // Check if this is the profile owner who is calling
4408 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4409 synchronized (this) {
4410 clearUserPoliciesLocked(callingUser);
4411 if (mDeviceOwner != null) {
4412 mDeviceOwner.removeProfileOwner(callingUser.getIdentifier());
4413 mDeviceOwner.writeOwnerFile();
4418 private void clearUserPoliciesLocked(UserHandle userHandle) {
4419 int userId = userHandle.getIdentifier();
4420 // Reset some of the user-specific policies
4421 DevicePolicyData policy = getUserData(userId);
4422 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
4423 policy.mDelegatedCertInstallerPackage = null;
4424 policy.mStatusBarDisabled = false;
4425 saveSettingsLocked(userId);
4427 final long ident = Binder.clearCallingIdentity();
4429 clearUserRestrictions(userHandle);
4430 AppGlobals.getPackageManager().updatePermissionFlagsForAllApps(
4431 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
4432 0 /* flagValues */, userHandle.getIdentifier());
4433 } catch (RemoteException re) {
4435 Binder.restoreCallingIdentity(ident);
4440 private void clearUserRestrictions(UserHandle userHandle) {
4441 Bundle userRestrictions = mUserManager.getUserRestrictions();
4442 mUserManager.setUserRestrictions(new Bundle(), userHandle);
4443 IAudioService iAudioService = IAudioService.Stub.asInterface(
4444 ServiceManager.getService(Context.AUDIO_SERVICE));
4445 if (userRestrictions.getBoolean(UserManager.DISALLOW_ADJUST_VOLUME)) {
4447 iAudioService.setMasterMute(true, 0, mContext.getPackageName(),
4448 userHandle.getIdentifier());
4449 } catch (RemoteException e) {
4450 // Not much we can do here.
4453 if (userRestrictions.getBoolean(UserManager.DISALLOW_UNMUTE_MICROPHONE)) {
4455 iAudioService.setMicrophoneMute(true, mContext.getPackageName(),
4456 userHandle.getIdentifier());
4457 } catch (RemoteException e) {
4458 // Not much we can do here.
4464 public boolean hasUserSetupCompleted() {
4465 return hasUserSetupCompleted(UserHandle.getCallingUserId());
4468 private boolean hasUserSetupCompleted(int userHandle) {
4472 DevicePolicyData policy = getUserData(userHandle);
4473 // If policy is null, return true, else check if the setup has completed.
4474 return policy == null || policy.mUserSetupComplete;
4478 public boolean setUserEnabled(ComponentName who) {
4482 synchronized (this) {
4484 throw new NullPointerException("ComponentName is null");
4486 int userId = UserHandle.getCallingUserId();
4488 ActiveAdmin activeAdmin =
4489 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4490 if (!isDeviceInitializer(activeAdmin.info.getPackageName())) {
4491 throw new SecurityException(
4492 "This method can only be called by device initializers");
4495 long id = Binder.clearCallingIdentity();
4497 if (!isDeviceOwner(activeAdmin.info.getPackageName())) {
4498 IPackageManager ipm = AppGlobals.getPackageManager();
4499 ipm.setComponentEnabledSetting(who,
4500 PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
4501 PackageManager.DONT_KILL_APP, userId);
4503 removeActiveAdmin(who, userId);
4506 if (userId == UserHandle.USER_OWNER) {
4507 Settings.Global.putInt(mContext.getContentResolver(),
4508 Settings.Global.DEVICE_PROVISIONED, 1);
4510 Settings.Secure.putIntForUser(mContext.getContentResolver(),
4511 Settings.Secure.USER_SETUP_COMPLETE, 1, userId);
4512 } catch (RemoteException e) {
4513 Log.i(LOG_TAG, "Can't talk to package manager", e);
4516 restoreCallingIdentity(id);
4523 public void setProfileEnabled(ComponentName who) {
4527 Preconditions.checkNotNull(who, "ComponentName is null");
4528 final int userHandle = UserHandle.getCallingUserId();
4529 synchronized (this) {
4530 // Check if this is the profile owner who is calling
4531 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4532 int userId = UserHandle.getCallingUserId();
4534 long id = Binder.clearCallingIdentity();
4536 mUserManager.setUserEnabled(userId);
4537 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
4538 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle));
4539 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
4540 Intent.FLAG_RECEIVER_FOREGROUND);
4541 // TODO This should send to parent of profile (which is always owner at the moment).
4542 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
4544 restoreCallingIdentity(id);
4550 public void setProfileName(ComponentName who, String profileName) {
4551 Preconditions.checkNotNull(who, "ComponentName is null");
4552 int userId = UserHandle.getCallingUserId();
4553 // Check if this is the profile owner (includes device owner).
4554 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4556 long id = Binder.clearCallingIdentity();
4558 mUserManager.setUserName(userId, profileName);
4560 restoreCallingIdentity(id);
4565 public ComponentName getProfileOwner(int userHandle) {
4570 synchronized (this) {
4571 if (mDeviceOwner != null) {
4572 return mDeviceOwner.getProfileOwnerComponent(userHandle);
4578 // Returns the active profile owner for this user or null if the current user has no
4580 private ActiveAdmin getProfileOwnerAdmin(int userHandle) {
4581 ComponentName profileOwner =
4582 mDeviceOwner != null ? mDeviceOwner.getProfileOwnerComponent(userHandle) : null;
4583 if (profileOwner == null) {
4586 DevicePolicyData policy = getUserData(userHandle);
4587 final int n = policy.mAdminList.size();
4588 for (int i = 0; i < n; i++) {
4589 ActiveAdmin admin = policy.mAdminList.get(i);
4590 if (profileOwner.equals(admin.info.getComponent())) {
4598 public String getProfileOwnerName(int userHandle) {
4602 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
4603 ComponentName profileOwner = getProfileOwner(userHandle);
4604 if (profileOwner == null) {
4607 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
4611 * Canonical name for a given package.
4613 private String getApplicationLabel(String packageName, int userHandle) {
4614 long token = Binder.clearCallingIdentity();
4616 final Context userContext;
4618 UserHandle handle = new UserHandle(userHandle);
4619 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
4620 } catch (PackageManager.NameNotFoundException nnfe) {
4621 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
4624 ApplicationInfo appInfo = userContext.getApplicationInfo();
4625 CharSequence result = null;
4626 if (appInfo != null) {
4627 PackageManager pm = userContext.getPackageManager();
4628 result = pm.getApplicationLabel(appInfo);
4630 return result != null ? result.toString() : null;
4632 Binder.restoreCallingIdentity(token);
4637 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
4639 * The profile owner can only be set before the user setup phase has completed,
4642 * - adb if there are not accounts.
4644 private void enforceCanSetProfileOwner(int userHandle) {
4645 UserInfo info = mUserManager.getUserInfo(userHandle);
4647 // User doesn't exist.
4648 throw new IllegalArgumentException(
4649 "Attempted to set profile owner for invalid userId: " + userHandle);
4651 if (info.isGuest()) {
4652 throw new IllegalStateException("Cannot set a profile owner on a guest");
4654 if (getProfileOwner(userHandle) != null) {
4655 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
4656 + "is already set.");
4658 int callingUid = Binder.getCallingUid();
4659 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
4660 if (hasUserSetupCompleted(userHandle) &&
4661 AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) {
4662 throw new IllegalStateException("Not allowed to set the profile owner because "
4663 + "there are already some accounts on the profile");
4667 mContext.enforceCallingOrSelfPermission(
4668 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
4669 if (hasUserSetupCompleted(userHandle)
4670 && UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
4671 throw new IllegalStateException("Cannot set the profile owner on a user which is "
4672 + "already set-up");
4677 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
4679 * The device owner can only be set before the setup phase of the primary user has completed,
4680 * except for adb if no accounts or additional users are present on the device.
4682 private void enforceCanSetDeviceOwner() {
4683 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
4684 throw new IllegalStateException("Trying to set the device owner, but device owner "
4685 + "is already set.");
4687 int callingUid = Binder.getCallingUid();
4688 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
4689 if (!hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4692 if (mUserManager.getUserCount() > 1) {
4693 throw new IllegalStateException("Not allowed to set the device owner because there "
4694 + "are already several users on the device");
4696 if (AccountManager.get(mContext).getAccounts().length > 0) {
4697 throw new IllegalStateException("Not allowed to set the device owner because there "
4698 + "are already some accounts on the device");
4702 mContext.enforceCallingOrSelfPermission(
4703 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
4704 if (hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4705 throw new IllegalStateException("Cannot set the device owner if the device is "
4706 + "already set-up");
4710 private void enforceCrossUserPermission(int userHandle) {
4711 if (userHandle < 0) {
4712 throw new IllegalArgumentException("Invalid userId " + userHandle);
4714 final int callingUid = Binder.getCallingUid();
4715 if (userHandle == UserHandle.getUserId(callingUid)) return;
4716 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4717 mContext.enforceCallingOrSelfPermission(
4718 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have"
4719 + " INTERACT_ACROSS_USERS_FULL permission");
4723 private void enforceSystemProcess(String message) {
4724 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4725 throw new SecurityException(message);
4729 private void enforceNotManagedProfile(int userHandle, String message) {
4730 if(isManagedProfile(userHandle)) {
4731 throw new SecurityException("You can not " + message + " for a managed profile. ");
4735 private UserInfo getProfileParent(int userHandle) {
4736 long ident = Binder.clearCallingIdentity();
4738 return mUserManager.getProfileParent(userHandle);
4740 Binder.restoreCallingIdentity(ident);
4744 private boolean isManagedProfile(int userHandle) {
4745 long ident = Binder.clearCallingIdentity();
4747 return mUserManager.getUserInfo(userHandle).isManagedProfile();
4749 Binder.restoreCallingIdentity(ident);
4753 private void enableIfNecessary(String packageName, int userId) {
4755 IPackageManager ipm = AppGlobals.getPackageManager();
4756 ApplicationInfo ai = ipm.getApplicationInfo(packageName,
4757 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
4759 if (ai.enabledSetting
4760 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
4761 ipm.setApplicationEnabledSetting(packageName,
4762 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
4763 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
4765 } catch (RemoteException e) {
4770 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4771 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4772 != PackageManager.PERMISSION_GRANTED) {
4774 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
4775 + Binder.getCallingPid()
4776 + ", uid=" + Binder.getCallingUid());
4780 final Printer p = new PrintWriterPrinter(pw);
4782 synchronized (this) {
4783 p.println("Current Device Policy Manager state:");
4784 if (mDeviceOwner != null) {
4785 mDeviceOwner.dump(" ", pw);
4787 int userCount = mUserData.size();
4788 for (int u = 0; u < userCount; u++) {
4789 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
4790 p.println(" Enabled Device Admins (User " + policy.mUserHandle + "):");
4791 final int N = policy.mAdminList.size();
4792 for (int i=0; i<N; i++) {
4793 ActiveAdmin ap = policy.mAdminList.get(i);
4795 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
4800 if (!policy.mRemovingAdmins.isEmpty()) {
4801 p.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
4802 + policy.mRemovingAdmins);
4806 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
4812 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
4813 ComponentName activity) {
4814 Preconditions.checkNotNull(who, "ComponentName is null");
4815 final int userHandle = UserHandle.getCallingUserId();
4816 synchronized (this) {
4817 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4819 IPackageManager pm = AppGlobals.getPackageManager();
4820 long id = Binder.clearCallingIdentity();
4822 pm.addPersistentPreferredActivity(filter, activity, userHandle);
4823 } catch (RemoteException re) {
4826 restoreCallingIdentity(id);
4832 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
4833 Preconditions.checkNotNull(who, "ComponentName is null");
4834 final int userHandle = UserHandle.getCallingUserId();
4835 synchronized (this) {
4836 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4838 IPackageManager pm = AppGlobals.getPackageManager();
4839 long id = Binder.clearCallingIdentity();
4841 pm.clearPackagePersistentPreferredActivities(packageName, userHandle);
4842 } catch (RemoteException re) {
4845 restoreCallingIdentity(id);
4851 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
4852 Preconditions.checkNotNull(who, "ComponentName is null");
4853 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4854 synchronized (this) {
4855 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4857 long id = Binder.clearCallingIdentity();
4859 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
4861 restoreCallingIdentity(id);
4867 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
4868 PersistableBundle args) {
4872 Preconditions.checkNotNull(admin, "admin is null");
4873 Preconditions.checkNotNull(agent, "agent is null");
4874 final int userHandle = UserHandle.getCallingUserId();
4875 enforceNotManagedProfile(userHandle, "set trust agent configuration");
4876 synchronized (this) {
4877 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
4878 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
4879 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
4880 saveSettingsLocked(userHandle);
4881 syncDeviceCapabilitiesLocked(getUserData(userHandle));
4886 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
4887 ComponentName agent, int userHandle) {
4891 Preconditions.checkNotNull(agent, "agent null");
4892 enforceCrossUserPermission(userHandle);
4894 synchronized (this) {
4895 final String componentName = agent.flattenToString();
4896 if (admin != null) {
4897 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle);
4898 if (ap == null) return null;
4899 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
4900 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
4901 List<PersistableBundle> result = new ArrayList<PersistableBundle>();
4902 result.add(trustAgentInfo.options);
4906 // Return strictest policy for this user and profiles that are visible from this user.
4907 final List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
4908 List<PersistableBundle> result = null;
4910 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
4911 // of the options. If any admin doesn't have options, discard options for the rest
4913 boolean allAdminsHaveOptions = true;
4914 for (UserInfo userInfo : profiles) {
4915 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4916 final int N = policy.mAdminList.size();
4917 for (int i=0; i < N; i++) {
4918 final ActiveAdmin active = policy.mAdminList.get(i);
4919 final boolean disablesTrust = (active.disabledKeyguardFeatures
4920 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
4921 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
4922 if (info != null && info.options != null && !info.options.isEmpty()) {
4923 if (disablesTrust) {
4924 if (result == null) {
4925 result = new ArrayList<PersistableBundle>();
4927 result.add(info.options);
4929 Log.w(LOG_TAG, "Ignoring admin " + active.info
4930 + " because it has trust options but doesn't declare "
4931 + "KEYGUARD_DISABLE_TRUST_AGENTS");
4933 } else if (disablesTrust) {
4934 allAdminsHaveOptions = false;
4939 return allAdminsHaveOptions ? result : null;
4944 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
4945 Preconditions.checkNotNull(who, "ComponentName is null");
4946 synchronized (this) {
4947 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4949 int userHandle = UserHandle.getCallingUserId();
4950 DevicePolicyData userData = getUserData(userHandle);
4951 userData.mRestrictionsProvider = permissionProvider;
4952 saveSettingsLocked(userHandle);
4957 public ComponentName getRestrictionsProvider(int userHandle) {
4958 synchronized (this) {
4959 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4960 throw new SecurityException("Only the system can query the permission provider");
4962 DevicePolicyData userData = getUserData(userHandle);
4963 return userData != null ? userData.mRestrictionsProvider : null;
4968 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
4969 Preconditions.checkNotNull(who, "ComponentName is null");
4970 int callingUserId = UserHandle.getCallingUserId();
4971 synchronized (this) {
4972 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4974 IPackageManager pm = AppGlobals.getPackageManager();
4975 long id = Binder.clearCallingIdentity();
4977 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
4978 pm.addCrossProfileIntentFilter(filter, who.getPackageName(), callingUserId,
4979 UserHandle.USER_OWNER, 0);
4981 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
4982 pm.addCrossProfileIntentFilter(filter, who.getPackageName(),
4983 UserHandle.USER_OWNER, callingUserId, 0);
4985 } catch (RemoteException re) {
4988 restoreCallingIdentity(id);
4994 public void clearCrossProfileIntentFilters(ComponentName who) {
4995 Preconditions.checkNotNull(who, "ComponentName is null");
4996 int callingUserId = UserHandle.getCallingUserId();
4997 synchronized (this) {
4998 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4999 IPackageManager pm = AppGlobals.getPackageManager();
5000 long id = Binder.clearCallingIdentity();
5002 // Removing those that go from the managed profile to the primary user.
5003 pm.clearCrossProfileIntentFilters(callingUserId, who.getPackageName());
5004 // And those that go from the primary user to the managed profile.
5005 // If we want to support multiple managed profiles, we will have to only remove
5006 // those that have callingUserId as their target.
5007 pm.clearCrossProfileIntentFilters(UserHandle.USER_OWNER, who.getPackageName());
5008 } catch (RemoteException re) {
5011 restoreCallingIdentity(id);
5017 * @return true if all packages in enabledPackages are either in the list
5018 * permittedList or are a system app.
5020 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
5021 List<String> permittedList) {
5022 int userIdToCheck = UserHandle.getCallingUserId();
5023 long id = Binder.clearCallingIdentity();
5025 // If we have an enabled packages list for a managed profile the packages
5026 // we should check are installed for the parent user.
5027 UserInfo user = mUserManager.getUserInfo(userIdToCheck);
5028 if (user.isManagedProfile()) {
5029 userIdToCheck = user.profileGroupId;
5032 IPackageManager pm = AppGlobals.getPackageManager();
5033 for (String enabledPackage : enabledPackages) {
5034 boolean systemService = false;
5036 ApplicationInfo applicationInfo = pm.getApplicationInfo(enabledPackage,
5037 PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
5038 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5039 } catch (RemoteException e) {
5040 Log.i(LOG_TAG, "Can't talk to package managed", e);
5042 if (!systemService && !permittedList.contains(enabledPackage)) {
5047 restoreCallingIdentity(id);
5052 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
5053 // Not using AccessibilityManager.getInstance because that guesses
5054 // at the user you require based on callingUid and caches for a given
5056 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
5057 IAccessibilityManager service = iBinder == null
5058 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
5059 return new AccessibilityManager(mContext, service, userId);
5063 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
5067 Preconditions.checkNotNull(who, "ComponentName is null");
5069 if (packageList != null) {
5070 int userId = UserHandle.getCallingUserId();
5071 List<AccessibilityServiceInfo> enabledServices = null;
5072 long id = Binder.clearCallingIdentity();
5074 UserInfo user = mUserManager.getUserInfo(userId);
5075 if (user.isManagedProfile()) {
5076 userId = user.profileGroupId;
5078 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
5079 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
5080 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
5082 restoreCallingIdentity(id);
5085 if (enabledServices != null) {
5086 List<String> enabledPackages = new ArrayList<String>();
5087 for (AccessibilityServiceInfo service : enabledServices) {
5088 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
5090 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
5091 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
5092 + "because it contains already enabled accesibility services.");
5098 synchronized (this) {
5099 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5100 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5101 admin.permittedAccessiblityServices = packageList;
5102 saveSettingsLocked(UserHandle.getCallingUserId());
5108 public List getPermittedAccessibilityServices(ComponentName who) {
5112 Preconditions.checkNotNull(who, "ComponentName is null");
5114 synchronized (this) {
5115 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5116 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5117 return admin.permittedAccessiblityServices;
5122 public List getPermittedAccessibilityServicesForUser(int userId) {
5126 synchronized (this) {
5127 List<String> result = null;
5128 // If we have multiple profiles we return the intersection of the
5129 // permitted lists. This can happen in cases where we have a device
5130 // and profile owner.
5131 List<UserInfo> profiles = mUserManager.getProfiles(userId);
5132 final int PROFILES_SIZE = profiles.size();
5133 for (int i = 0; i < PROFILES_SIZE; ++i) {
5134 // Just loop though all admins, only device or profiles
5135 // owners can have permitted lists set.
5136 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
5137 final int N = policy.mAdminList.size();
5138 for (int j = 0; j < N; j++) {
5139 ActiveAdmin admin = policy.mAdminList.get(j);
5140 List<String> fromAdmin = admin.permittedAccessiblityServices;
5141 if (fromAdmin != null) {
5142 if (result == null) {
5143 result = new ArrayList<String>(fromAdmin);
5145 result.retainAll(fromAdmin);
5151 // If we have a permitted list add all system accessibility services.
5152 if (result != null) {
5153 long id = Binder.clearCallingIdentity();
5155 UserInfo user = mUserManager.getUserInfo(userId);
5156 if (user.isManagedProfile()) {
5157 userId = user.profileGroupId;
5159 AccessibilityManager accessibilityManager =
5160 getAccessibilityManagerForUser(userId);
5161 List<AccessibilityServiceInfo> installedServices =
5162 accessibilityManager.getInstalledAccessibilityServiceList();
5164 IPackageManager pm = AppGlobals.getPackageManager();
5165 if (installedServices != null) {
5166 for (AccessibilityServiceInfo service : installedServices) {
5167 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
5168 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
5169 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5170 result.add(serviceInfo.packageName);
5175 restoreCallingIdentity(id);
5183 private boolean checkCallerIsCurrentUserOrProfile() {
5184 int callingUserId = UserHandle.getCallingUserId();
5185 long token = Binder.clearCallingIdentity();
5187 UserInfo currentUser;
5188 UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
5190 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
5191 } catch (RemoteException e) {
5192 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
5196 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
5197 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
5198 + "of a user that isn't the foreground user.");
5201 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
5202 Slog.e(LOG_TAG, "Cannot set permitted input methods "
5203 + "of a user that isn't the foreground user.");
5207 Binder.restoreCallingIdentity(token);
5213 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
5217 Preconditions.checkNotNull(who, "ComponentName is null");
5219 // TODO When InputMethodManager supports per user calls remove
5220 // this restriction.
5221 if (!checkCallerIsCurrentUserOrProfile()) {
5225 if (packageList != null) {
5226 // InputMethodManager fetches input methods for current user.
5227 // So this can only be set when calling user is the current user
5228 // or parent is current user in case of managed profiles.
5229 InputMethodManager inputMethodManager = (InputMethodManager) mContext
5230 .getSystemService(Context.INPUT_METHOD_SERVICE);
5231 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
5233 if (enabledImes != null) {
5234 List<String> enabledPackages = new ArrayList<String>();
5235 for (InputMethodInfo ime : enabledImes) {
5236 enabledPackages.add(ime.getPackageName());
5238 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
5239 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
5240 + "because it contains already enabled input method.");
5246 synchronized (this) {
5247 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5248 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5249 admin.permittedInputMethods = packageList;
5250 saveSettingsLocked(UserHandle.getCallingUserId());
5256 public List getPermittedInputMethods(ComponentName who) {
5260 Preconditions.checkNotNull(who, "ComponentName is null");
5262 synchronized (this) {
5263 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5264 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5265 return admin.permittedInputMethods;
5270 public List getPermittedInputMethodsForCurrentUser() {
5271 UserInfo currentUser;
5273 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
5274 } catch (RemoteException e) {
5275 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
5276 // Activity managed is dead, just allow all IMEs
5280 int userId = currentUser.id;
5281 synchronized (this) {
5282 List<String> result = null;
5283 // If we have multiple profiles we return the intersection of the
5284 // permitted lists. This can happen in cases where we have a device
5285 // and profile owner.
5286 List<UserInfo> profiles = mUserManager.getProfiles(userId);
5287 final int PROFILES_SIZE = profiles.size();
5288 for (int i = 0; i < PROFILES_SIZE; ++i) {
5289 // Just loop though all admins, only device or profiles
5290 // owners can have permitted lists set.
5291 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
5292 final int N = policy.mAdminList.size();
5293 for (int j = 0; j < N; j++) {
5294 ActiveAdmin admin = policy.mAdminList.get(j);
5295 List<String> fromAdmin = admin.permittedInputMethods;
5296 if (fromAdmin != null) {
5297 if (result == null) {
5298 result = new ArrayList<String>(fromAdmin);
5300 result.retainAll(fromAdmin);
5306 // If we have a permitted list add all system input methods.
5307 if (result != null) {
5308 InputMethodManager inputMethodManager = (InputMethodManager) mContext
5309 .getSystemService(Context.INPUT_METHOD_SERVICE);
5310 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
5311 long id = Binder.clearCallingIdentity();
5313 IPackageManager pm = AppGlobals.getPackageManager();
5315 for (InputMethodInfo ime : imes) {
5316 ServiceInfo serviceInfo = ime.getServiceInfo();
5317 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
5318 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5319 result.add(serviceInfo.packageName);
5324 restoreCallingIdentity(id);
5332 public UserHandle createUser(ComponentName who, String name) {
5333 Preconditions.checkNotNull(who, "ComponentName is null");
5334 synchronized (this) {
5335 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5337 long id = Binder.clearCallingIdentity();
5339 UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */);
5340 if (userInfo != null) {
5341 return userInfo.getUserHandle();
5345 restoreCallingIdentity(id);
5351 public UserHandle createAndInitializeUser(ComponentName who, String name,
5352 String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) {
5353 UserHandle user = createUser(who, name);
5357 long id = Binder.clearCallingIdentity();
5359 String profileOwnerPkg = profileOwnerComponent.getPackageName();
5360 final IPackageManager ipm = AppGlobals.getPackageManager();
5361 IActivityManager activityManager = ActivityManagerNative.getDefault();
5363 final int userHandle = user.getIdentifier();
5365 // Install the profile owner if not present.
5366 if (!ipm.isPackageAvailable(profileOwnerPkg, userHandle)) {
5367 ipm.installExistingPackageAsUser(profileOwnerPkg, userHandle);
5370 // Start user in background.
5371 activityManager.startUserInBackground(userHandle);
5372 } catch (RemoteException e) {
5373 Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e);
5376 setActiveAdmin(profileOwnerComponent, true, userHandle, adminExtras);
5377 setProfileOwner(profileOwnerComponent, ownerName, userHandle);
5380 restoreCallingIdentity(id);
5385 public boolean removeUser(ComponentName who, UserHandle userHandle) {
5386 Preconditions.checkNotNull(who, "ComponentName is null");
5387 synchronized (this) {
5388 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5390 long id = Binder.clearCallingIdentity();
5392 return mUserManager.removeUser(userHandle.getIdentifier());
5394 restoreCallingIdentity(id);
5400 public boolean switchUser(ComponentName who, UserHandle userHandle) {
5401 Preconditions.checkNotNull(who, "ComponentName is null");
5402 synchronized (this) {
5403 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5405 long id = Binder.clearCallingIdentity();
5407 int userId = UserHandle.USER_OWNER;
5408 if (userHandle != null) {
5409 userId = userHandle.getIdentifier();
5411 return ActivityManagerNative.getDefault().switchUser(userId);
5412 } catch (RemoteException e) {
5413 Log.e(LOG_TAG, "Couldn't switch user", e);
5416 restoreCallingIdentity(id);
5422 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
5423 Preconditions.checkNotNull(who, "ComponentName is null");
5424 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
5426 synchronized (this) {
5427 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5429 long id = Binder.clearCallingIdentity();
5431 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
5432 // if no restrictions were saved, mUserManager.getApplicationRestrictions
5433 // returns null, but DPM method should return an empty Bundle as per JavaDoc
5434 return bundle != null ? bundle : Bundle.EMPTY;
5436 restoreCallingIdentity(id);
5442 public void setUserRestriction(ComponentName who, String key, boolean enabled) {
5443 Preconditions.checkNotNull(who, "ComponentName is null");
5444 final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
5445 final int userHandle = user.getIdentifier();
5446 synchronized (this) {
5447 ActiveAdmin activeAdmin =
5448 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5449 boolean isDeviceOwner = isDeviceOwner(activeAdmin.info.getPackageName());
5450 if (!isDeviceOwner && userHandle != UserHandle.USER_OWNER
5451 && DEVICE_OWNER_USER_RESTRICTIONS.contains(key)) {
5452 throw new SecurityException("Profile owners cannot set user restriction " + key);
5454 if (IMMUTABLE_USER_RESTRICTIONS.contains(key)) {
5455 throw new SecurityException("User restriction " + key + " cannot be changed");
5457 boolean alreadyRestricted = mUserManager.hasUserRestriction(key, user);
5459 IAudioService iAudioService = null;
5460 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)
5461 || UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5462 iAudioService = IAudioService.Stub.asInterface(
5463 ServiceManager.getService(Context.AUDIO_SERVICE));
5466 long id = Binder.clearCallingIdentity();
5468 if (enabled && !alreadyRestricted) {
5469 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
5470 iAudioService.setMicrophoneMute(true, mContext.getPackageName(),
5472 } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5473 iAudioService.setMasterMute(true, 0, mContext.getPackageName(),
5476 if (UserManager.DISALLOW_CONFIG_WIFI.equals(key)) {
5477 Settings.Secure.putIntForUser(mContext.getContentResolver(),
5478 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0,
5480 } else if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
5481 Settings.Secure.putIntForUser(mContext.getContentResolver(),
5482 Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF,
5484 Settings.Secure.putStringForUser(mContext.getContentResolver(),
5485 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, "",
5487 } else if (UserManager.DISALLOW_DEBUGGING_FEATURES.equals(key)) {
5488 // Only disable adb if changing for primary user, since it is global
5489 if (userHandle == UserHandle.USER_OWNER) {
5490 Settings.Global.putStringForUser(mContext.getContentResolver(),
5491 Settings.Global.ADB_ENABLED, "0", userHandle);
5493 } else if (UserManager.ENSURE_VERIFY_APPS.equals(key)) {
5494 Settings.Global.putStringForUser(mContext.getContentResolver(),
5495 Settings.Global.PACKAGE_VERIFIER_ENABLE, "1",
5497 Settings.Global.putStringForUser(mContext.getContentResolver(),
5498 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1",
5500 } else if (UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES.equals(key)) {
5501 Settings.Secure.putIntForUser(mContext.getContentResolver(),
5502 Settings.Secure.INSTALL_NON_MARKET_APPS, 0,
5506 mUserManager.setUserRestriction(key, enabled, user);
5507 if (enabled != alreadyRestricted) {
5508 if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
5509 // Send out notifications however as some clients may want to reread the
5510 // value which actually changed due to a restriction having been applied.
5511 final String property = Settings.Secure.SYS_PROP_SETTING_VERSION;
5512 long version = SystemProperties.getLong(property, 0) + 1;
5513 SystemProperties.set(property, Long.toString(version));
5515 final String name = Settings.Secure.LOCATION_PROVIDERS_ALLOWED;
5516 Uri url = Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
5517 mContext.getContentResolver().notifyChange(url, null, true, userHandle);
5520 if (!enabled && alreadyRestricted) {
5521 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
5522 iAudioService.setMicrophoneMute(false, mContext.getPackageName(),
5524 } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5525 iAudioService.setMasterMute(false, 0, mContext.getPackageName(),
5529 } catch (RemoteException re) {
5530 Slog.e(LOG_TAG, "Failed to talk to AudioService.", re);
5532 restoreCallingIdentity(id);
5534 sendChangedNotification(userHandle);
5539 public boolean setApplicationHidden(ComponentName who, String packageName,
5541 Preconditions.checkNotNull(who, "ComponentName is null");
5542 int callingUserId = UserHandle.getCallingUserId();
5543 synchronized (this) {
5544 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5546 long id = Binder.clearCallingIdentity();
5548 IPackageManager pm = AppGlobals.getPackageManager();
5549 return pm.setApplicationHiddenSettingAsUser(packageName, hidden, callingUserId);
5550 } catch (RemoteException re) {
5552 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
5554 restoreCallingIdentity(id);
5561 public boolean isApplicationHidden(ComponentName who, String packageName) {
5562 Preconditions.checkNotNull(who, "ComponentName is null");
5563 int callingUserId = UserHandle.getCallingUserId();
5564 synchronized (this) {
5565 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5567 long id = Binder.clearCallingIdentity();
5569 IPackageManager pm = AppGlobals.getPackageManager();
5570 return pm.getApplicationHiddenSettingAsUser(packageName, callingUserId);
5571 } catch (RemoteException re) {
5573 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
5575 restoreCallingIdentity(id);
5582 public void enableSystemApp(ComponentName who, String packageName) {
5583 Preconditions.checkNotNull(who, "ComponentName is null");
5584 synchronized (this) {
5585 // This API can only be called by an active device admin,
5586 // so try to retrieve it to check that the caller is one.
5587 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5589 int userId = UserHandle.getCallingUserId();
5590 long id = Binder.clearCallingIdentity();
5594 Slog.v(LOG_TAG, "installing " + packageName + " for "
5598 UserManager um = UserManager.get(mContext);
5599 UserInfo primaryUser = um.getProfileParent(userId);
5601 // Call did not come from a managed profile
5602 if (primaryUser == null) {
5603 primaryUser = um.getUserInfo(userId);
5606 IPackageManager pm = AppGlobals.getPackageManager();
5607 if (!isSystemApp(pm, packageName, primaryUser.id)) {
5608 throw new IllegalArgumentException("Only system apps can be enabled this way.");
5612 pm.installExistingPackageAsUser(packageName, userId);
5614 } catch (RemoteException re) {
5616 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
5618 restoreCallingIdentity(id);
5624 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
5625 Preconditions.checkNotNull(who, "ComponentName is null");
5626 synchronized (this) {
5627 // This API can only be called by an active device admin,
5628 // so try to retrieve it to check that the caller is one.
5629 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5631 int userId = UserHandle.getCallingUserId();
5632 long id = Binder.clearCallingIdentity();
5635 UserManager um = UserManager.get(mContext);
5636 UserInfo primaryUser = um.getProfileParent(userId);
5638 // Call did not come from a managed profile.
5639 if (primaryUser == null) {
5640 primaryUser = um.getUserInfo(userId);
5643 IPackageManager pm = AppGlobals.getPackageManager();
5644 List<ResolveInfo> activitiesToEnable = pm.queryIntentActivities(intent,
5645 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5649 if (DBG) Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
5650 int numberOfAppsInstalled = 0;
5651 if (activitiesToEnable != null) {
5652 for (ResolveInfo info : activitiesToEnable) {
5653 if (info.activityInfo != null) {
5654 String packageName = info.activityInfo.packageName;
5655 if (isSystemApp(pm, packageName, primaryUser.id)) {
5656 numberOfAppsInstalled++;
5657 pm.installExistingPackageAsUser(packageName, userId);
5659 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
5665 return numberOfAppsInstalled;
5666 } catch (RemoteException e) {
5668 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
5671 restoreCallingIdentity(id);
5676 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
5677 throws RemoteException {
5678 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
5680 if (appInfo == null) {
5681 throw new IllegalArgumentException("The application " + packageName +
5682 " is not present on this device");
5684 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5688 public void setAccountManagementDisabled(ComponentName who, String accountType,
5693 Preconditions.checkNotNull(who, "ComponentName is null");
5694 synchronized (this) {
5695 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5696 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5698 ap.accountTypesWithManagementDisabled.add(accountType);
5700 ap.accountTypesWithManagementDisabled.remove(accountType);
5702 saveSettingsLocked(UserHandle.getCallingUserId());
5707 public String[] getAccountTypesWithManagementDisabled() {
5708 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
5712 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
5713 enforceCrossUserPermission(userId);
5717 synchronized (this) {
5718 DevicePolicyData policy = getUserData(userId);
5719 final int N = policy.mAdminList.size();
5720 HashSet<String> resultSet = new HashSet<String>();
5721 for (int i = 0; i < N; i++) {
5722 ActiveAdmin admin = policy.mAdminList.get(i);
5723 resultSet.addAll(admin.accountTypesWithManagementDisabled);
5725 return resultSet.toArray(new String[resultSet.size()]);
5730 public void setUninstallBlocked(ComponentName who, String packageName,
5731 boolean uninstallBlocked) {
5732 Preconditions.checkNotNull(who, "ComponentName is null");
5733 final int userId = UserHandle.getCallingUserId();
5734 synchronized (this) {
5735 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5737 long id = Binder.clearCallingIdentity();
5739 IPackageManager pm = AppGlobals.getPackageManager();
5740 pm.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
5741 } catch (RemoteException re) {
5742 // Shouldn't happen.
5743 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
5745 restoreCallingIdentity(id);
5751 public boolean isUninstallBlocked(ComponentName who, String packageName) {
5752 // This function should return true if and only if the package is blocked by
5753 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
5754 // when the package is a system app, or when it is an active device admin.
5755 final int userId = UserHandle.getCallingUserId();
5757 synchronized (this) {
5759 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5762 long id = Binder.clearCallingIdentity();
5764 IPackageManager pm = AppGlobals.getPackageManager();
5765 return pm.getBlockUninstallForUser(packageName, userId);
5766 } catch (RemoteException re) {
5767 // Shouldn't happen.
5768 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
5770 restoreCallingIdentity(id);
5777 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
5781 Preconditions.checkNotNull(who, "ComponentName is null");
5782 synchronized (this) {
5783 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5784 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5785 if (admin.disableCallerId != disabled) {
5786 admin.disableCallerId = disabled;
5787 saveSettingsLocked(UserHandle.getCallingUserId());
5793 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
5797 Preconditions.checkNotNull(who, "ComponentName is null");
5798 synchronized (this) {
5799 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5800 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5801 return admin.disableCallerId;
5806 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
5807 // TODO: Should there be a check to make sure this relationship is within a profile group?
5808 //enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5809 synchronized (this) {
5810 ActiveAdmin admin = getProfileOwnerAdmin(userId);
5811 return (admin != null) ? admin.disableCallerId : false;
5816 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5817 Intent originalIntent) {
5818 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(
5819 actualLookupKey, actualContactId, originalIntent);
5820 final int callingUserId = UserHandle.getCallingUserId();
5822 final long ident = Binder.clearCallingIdentity();
5824 synchronized (this) {
5825 final int managedUserId = getManagedUserId(callingUserId);
5826 if (managedUserId < 0) {
5829 if (getCrossProfileCallerIdDisabledForUser(managedUserId)) {
5832 "Cross-profile contacts access disabled for user " + managedUserId);
5836 ContactsInternal.startQuickContactWithErrorToastForUser(
5837 mContext, intent, new UserHandle(managedUserId));
5840 Binder.restoreCallingIdentity(ident);
5845 * @return the user ID of the managed user that is linked to the current user, if any.
5848 public int getManagedUserId(int callingUserId) {
5850 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
5853 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
5854 if (ui.id == callingUserId || !ui.isManagedProfile()) {
5855 continue; // Caller user self, or not a managed profile. Skip.
5858 Log.v(LOG_TAG, "Managed user=" + ui.id);
5863 Log.v(LOG_TAG, "Managed user not found.");
5869 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
5873 Preconditions.checkNotNull(who, "ComponentName is null");
5874 synchronized (this) {
5875 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5876 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5877 if (admin.disableBluetoothContactSharing != disabled) {
5878 admin.disableBluetoothContactSharing = disabled;
5879 saveSettingsLocked(UserHandle.getCallingUserId());
5885 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
5889 Preconditions.checkNotNull(who, "ComponentName is null");
5890 synchronized (this) {
5891 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5892 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5893 return admin.disableBluetoothContactSharing;
5898 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
5899 // TODO: Should there be a check to make sure this relationship is
5900 // within a profile group?
5901 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5902 synchronized (this) {
5903 ActiveAdmin admin = getProfileOwnerAdmin(userId);
5904 return (admin != null) ? admin.disableBluetoothContactSharing : false;
5909 * Sets which packages may enter lock task mode.
5911 * This function can only be called by the device owner.
5912 * @param packages The list of packages allowed to enter lock task mode.
5915 public void setLockTaskPackages(ComponentName who, String[] packages)
5916 throws SecurityException {
5917 Preconditions.checkNotNull(who, "ComponentName is null");
5918 synchronized (this) {
5919 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5921 int userHandle = Binder.getCallingUserHandle().getIdentifier();
5922 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
5926 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
5927 DevicePolicyData policy = getUserData(userHandle);
5928 policy.mLockTaskPackages = packages;
5930 // Store the settings persistently.
5931 saveSettingsLocked(userHandle);
5932 updateLockTaskPackagesLocked(packages, userHandle);
5936 * This function returns the list of components allowed to start the task lock mode.
5939 public String[] getLockTaskPackages(ComponentName who) {
5940 Preconditions.checkNotNull(who, "ComponentName is null");
5941 synchronized (this) {
5942 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5943 int userHandle = Binder.getCallingUserHandle().getIdentifier();
5944 final List<String> packages = getLockTaskPackagesLocked(userHandle);
5945 return packages.toArray(new String[packages.size()]);
5949 private List<String> getLockTaskPackagesLocked(int userHandle) {
5950 final DevicePolicyData policy = getUserData(userHandle);
5951 return policy.mLockTaskPackages;
5955 * This function lets the caller know whether the given package is allowed to start the
5957 * @param pkg The package to check
5960 public boolean isLockTaskPermitted(String pkg) {
5961 // Get current user's devicepolicy
5962 int uid = Binder.getCallingUid();
5963 int userHandle = UserHandle.getUserId(uid);
5964 DevicePolicyData policy = getUserData(userHandle);
5965 synchronized (this) {
5966 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
5967 String lockTaskPackage = policy.mLockTaskPackages.get(i);
5969 // If the given package equals one of the packages stored our list,
5970 // we allow this package to start lock task mode.
5971 if (lockTaskPackage.equals(pkg)) {
5980 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
5981 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
5982 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
5984 synchronized (this) {
5985 final DevicePolicyData policy = getUserData(userHandle);
5986 Bundle adminExtras = new Bundle();
5987 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
5988 for (ActiveAdmin admin : policy.mAdminList) {
5989 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
5990 boolean ownsProfile = (getProfileOwner(userHandle) != null
5991 && getProfileOwner(userHandle).equals(admin.info.getPackageName()));
5992 if (ownsDevice || ownsProfile) {
5994 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
5997 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
6005 public void setGlobalSetting(ComponentName who, String setting, String value) {
6006 final ContentResolver contentResolver = mContext.getContentResolver();
6007 Preconditions.checkNotNull(who, "ComponentName is null");
6009 synchronized (this) {
6010 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6012 // Some settings are no supported any more. However we do not want to throw a
6013 // SecurityException to avoid breaking apps.
6014 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
6015 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
6019 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
6020 throw new SecurityException(String.format(
6021 "Permission denial: device owners cannot update %1$s", setting));
6024 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
6025 // ignore if it contradicts an existing policy
6026 long timeMs = getMaximumTimeToLock(who, UserHandle.getCallingUserId());
6027 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
6032 long id = Binder.clearCallingIdentity();
6034 Settings.Global.putString(contentResolver, setting, value);
6036 restoreCallingIdentity(id);
6042 public void setSecureSetting(ComponentName who, String setting, String value) {
6043 Preconditions.checkNotNull(who, "ComponentName is null");
6044 int callingUserId = UserHandle.getCallingUserId();
6045 final ContentResolver contentResolver = mContext.getContentResolver();
6047 synchronized (this) {
6048 ActiveAdmin activeAdmin =
6049 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6051 if (isDeviceOwner(activeAdmin.info.getPackageName())) {
6052 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
6053 throw new SecurityException(String.format(
6054 "Permission denial: Device owners cannot update %1$s", setting));
6056 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
6057 throw new SecurityException(String.format(
6058 "Permission denial: Profile owners cannot update %1$s", setting));
6061 long id = Binder.clearCallingIdentity();
6063 Settings.Secure.putStringForUser(contentResolver, setting, value, callingUserId);
6065 restoreCallingIdentity(id);
6071 public void setMasterVolumeMuted(ComponentName who, boolean on) {
6072 Preconditions.checkNotNull(who, "ComponentName is null");
6073 synchronized (this) {
6074 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6075 int userId = UserHandle.getCallingUserId();
6076 long identity = Binder.clearCallingIdentity();
6078 IAudioService iAudioService = IAudioService.Stub.asInterface(
6079 ServiceManager.getService(Context.AUDIO_SERVICE));
6080 iAudioService.setMasterMute(on, 0, mContext.getPackageName(), userId);
6081 } catch (RemoteException re) {
6082 Slog.e(LOG_TAG, "Failed to setMasterMute", re);
6084 Binder.restoreCallingIdentity(identity);
6090 public boolean isMasterVolumeMuted(ComponentName who) {
6091 Preconditions.checkNotNull(who, "ComponentName is null");
6092 synchronized (this) {
6093 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6095 AudioManager audioManager =
6096 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
6097 return audioManager.isMasterMute();
6102 public void setUserIcon(ComponentName who, Bitmap icon) {
6103 synchronized (this) {
6104 Preconditions.checkNotNull(who, "ComponentName is null");
6105 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6107 int userId = UserHandle.getCallingUserId();
6108 long id = Binder.clearCallingIdentity();
6110 mUserManager.setUserIcon(userId, icon);
6112 restoreCallingIdentity(id);
6118 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
6119 Preconditions.checkNotNull(who, "ComponentName is null");
6120 synchronized (this) {
6121 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6123 final int userId = UserHandle.getCallingUserId();
6124 LockPatternUtils utils = new LockPatternUtils(mContext);
6126 long ident = Binder.clearCallingIdentity();
6128 // disallow disabling the keyguard if a password is currently set
6129 if (disabled && utils.isSecure(userId)) {
6132 utils.setLockScreenDisabled(disabled, userId);
6134 Binder.restoreCallingIdentity(ident);
6140 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
6141 int userId = UserHandle.getCallingUserId();
6142 synchronized (this) {
6143 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6144 DevicePolicyData policy = getUserData(userId);
6145 if (policy.mStatusBarDisabled != disabled) {
6146 if (!setStatusBarDisabledInternal(disabled, userId)) {
6149 policy.mStatusBarDisabled = disabled;
6150 saveSettingsLocked(userId);
6156 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
6157 long ident = Binder.clearCallingIdentity();
6159 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
6160 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
6161 if (statusBarService != null) {
6162 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
6163 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
6164 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
6165 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
6168 } catch (RemoteException e) {
6169 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
6171 Binder.restoreCallingIdentity(ident);
6177 * We need to update the internal state of whether a user has completed setup once. After
6178 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
6179 * as we don't trust any apps that might try to reset it.
6181 * Unfortunately, we don't know which user's setup state was changed, so we write all of
6184 void updateUserSetupComplete() {
6185 List<UserInfo> users = mUserManager.getUsers(true);
6186 ContentResolver resolver = mContext.getContentResolver();
6187 final int N = users.size();
6188 for (int i = 0; i < N; i++) {
6189 int userHandle = users.get(i).id;
6190 if (Settings.Secure.getIntForUser(resolver, Settings.Secure.USER_SETUP_COMPLETE, 0,
6192 DevicePolicyData policy = getUserData(userHandle);
6193 if (!policy.mUserSetupComplete) {
6194 policy.mUserSetupComplete = true;
6195 synchronized (this) {
6196 // The DeviceInitializer was whitelisted but now should be removed.
6197 removeDeviceInitializerFromLockTaskPackages(userHandle);
6198 saveSettingsLocked(userHandle);
6205 private void addDeviceInitializerToLockTaskPackagesLocked(int userHandle) {
6206 if (hasUserSetupCompleted(userHandle)) {
6210 final String deviceInitializerPackage = getDeviceInitializer();
6211 if (deviceInitializerPackage == null) {
6215 final List<String> packages = getLockTaskPackagesLocked(userHandle);
6216 if (!packages.contains(deviceInitializerPackage)) {
6217 packages.add(deviceInitializerPackage);
6218 setLockTaskPackagesLocked(userHandle, packages);
6222 private void removeDeviceInitializerFromLockTaskPackages(int userHandle) {
6223 final String deviceInitializerPackage = getDeviceInitializer();
6224 if (deviceInitializerPackage == null) {
6228 List<String> packages = getLockTaskPackagesLocked(userHandle);
6229 if (packages.remove(deviceInitializerPackage)) {
6230 setLockTaskPackagesLocked(userHandle, packages);
6234 private class SetupContentObserver extends ContentObserver {
6236 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
6237 Settings.Secure.USER_SETUP_COMPLETE);
6239 public SetupContentObserver(Handler handler) {
6243 void register(ContentResolver resolver) {
6244 resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
6248 public void onChange(boolean selfChange, Uri uri) {
6249 if (mUserSetupComplete.equals(uri)) {
6250 updateUserSetupComplete();
6255 private final class LocalService extends DevicePolicyManagerInternal {
6256 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
6259 public List<String> getCrossProfileWidgetProviders(int profileId) {
6260 synchronized (DevicePolicyManagerService.this) {
6261 if (mDeviceOwner == null) {
6262 return Collections.emptyList();
6264 ComponentName ownerComponent = mDeviceOwner.getProfileOwnerComponent(profileId);
6265 if (ownerComponent == null) {
6266 return Collections.emptyList();
6269 DevicePolicyData policy = getUserDataUnchecked(profileId);
6270 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
6272 if (admin == null || admin.crossProfileWidgetProviders == null
6273 || admin.crossProfileWidgetProviders.isEmpty()) {
6274 return Collections.emptyList();
6277 return admin.crossProfileWidgetProviders;
6282 public void addOnCrossProfileWidgetProvidersChangeListener(
6283 OnCrossProfileWidgetProvidersChangeListener listener) {
6284 synchronized (DevicePolicyManagerService.this) {
6285 if (mWidgetProviderListeners == null) {
6286 mWidgetProviderListeners = new ArrayList<>();
6288 if (!mWidgetProviderListeners.contains(listener)) {
6289 mWidgetProviderListeners.add(listener);
6295 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
6296 final int userId = UserHandle.getUserId(uid);
6297 synchronized(DevicePolicyManagerService.this) {
6298 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
6302 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
6303 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
6304 synchronized (DevicePolicyManagerService.this) {
6305 listeners = new ArrayList<>(mWidgetProviderListeners);
6307 final int listenerCount = listeners.size();
6308 for (int i = 0; i < listenerCount; i++) {
6309 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
6310 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
6316 * Returns true if specified admin is allowed to limit passwords and has a
6317 * {@code passwordQuality} of at least {@code minPasswordQuality}
6319 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
6320 if (admin.passwordQuality < minPasswordQuality) {
6323 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
6327 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
6328 if (policy != null && !policy.isValid()) {
6329 throw new IllegalArgumentException("Invalid system update policy.");
6331 synchronized (this) {
6332 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6333 if (policy == null) {
6334 mDeviceOwner.clearSystemUpdatePolicy();
6336 mDeviceOwner.setSystemUpdatePolicy(policy);
6338 mDeviceOwner.writeOwnerFile();
6340 mContext.sendBroadcastAsUser(
6341 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
6346 public SystemUpdatePolicy getSystemUpdatePolicy() {
6347 synchronized (this) {
6348 SystemUpdatePolicy policy = mDeviceOwner.getSystemUpdatePolicy();
6349 if (policy != null && !policy.isValid()) {
6350 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
6358 * Checks if the caller of the method is the device owner app or device initialization app.
6360 * @param callerUid UID of the caller.
6361 * @return true if the caller is the device owner app or device initializer.
6363 private boolean isCallerDeviceOwnerOrInitializer(int callerUid) {
6364 String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
6365 for (String pkg : pkgs) {
6366 if (isDeviceOwner(pkg) || isDeviceInitializer(pkg)) {
6374 public void notifyPendingSystemUpdate(long updateReceivedTime) {
6375 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
6376 "Only the system update service can broadcast update information");
6378 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
6379 Slog.w(LOG_TAG, "Only the system update service in the primary user" +
6380 "can broadcast update information.");
6383 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
6384 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
6385 updateReceivedTime);
6387 synchronized (this) {
6388 String deviceOwnerPackage = getDeviceOwner();
6389 if (deviceOwnerPackage == null) {
6393 ActivityInfo[] receivers = null;
6395 receivers = mContext.getPackageManager().getPackageInfo(
6396 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
6397 } catch (NameNotFoundException e) {
6398 Log.e(LOG_TAG, "Cannot find device owner package", e);
6400 if (receivers != null) {
6401 long ident = Binder.clearCallingIdentity();
6403 for (int i = 0; i < receivers.length; i++) {
6404 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
6405 intent.setComponent(new ComponentName(deviceOwnerPackage,
6406 receivers[i].name));
6407 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
6411 Binder.restoreCallingIdentity(ident);
6418 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
6419 int userId = UserHandle.getCallingUserId();
6420 synchronized (this) {
6421 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6422 DevicePolicyData userPolicy = getUserData(userId);
6423 if (userPolicy.mPermissionPolicy != policy) {
6424 userPolicy.mPermissionPolicy = policy;
6425 saveSettingsLocked(userId);
6431 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
6432 int userId = UserHandle.getCallingUserId();
6433 synchronized (this) {
6434 DevicePolicyData userPolicy = getUserData(userId);
6435 return userPolicy.mPermissionPolicy;
6440 public boolean setPermissionGrantState(ComponentName admin, String packageName,
6441 String permission, int grantState) throws RemoteException {
6442 UserHandle user = Binder.getCallingUserHandle();
6443 synchronized (this) {
6444 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6445 long ident = Binder.clearCallingIdentity();
6447 final ApplicationInfo ai = AppGlobals.getPackageManager()
6448 .getApplicationInfo(packageName, 0, user.getIdentifier());
6449 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
6450 if (targetSdkVersion < android.os.Build.VERSION_CODES.M) {
6453 if (!isRuntimePermission(permission)) {
6454 EventLog.writeEvent(0x534e4554, "62623498", user.getIdentifier(), "");
6457 final PackageManager packageManager = mContext.getPackageManager();
6458 switch (grantState) {
6459 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
6460 packageManager.grantRuntimePermission(packageName, permission, user);
6461 packageManager.updatePermissionFlags(permission, packageName,
6462 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6463 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
6466 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
6467 packageManager.revokeRuntimePermission(packageName,
6469 packageManager.updatePermissionFlags(permission, packageName,
6470 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6471 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
6474 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
6475 packageManager.updatePermissionFlags(permission, packageName,
6476 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
6480 } catch (SecurityException se) {
6482 } catch (NameNotFoundException e) {
6485 Binder.restoreCallingIdentity(ident);
6490 public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
6491 final PackageManager packageManager = mContext.getPackageManager();
6492 PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
6493 return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
6494 == PermissionInfo.PROTECTION_DANGEROUS;
6498 public int getPermissionGrantState(ComponentName admin, String packageName,
6499 String permission) throws RemoteException {
6500 PackageManager packageManager = mContext.getPackageManager();
6502 UserHandle user = Binder.getCallingUserHandle();
6503 synchronized (this) {
6504 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6505 long ident = Binder.clearCallingIdentity();
6507 int granted = AppGlobals.getPackageManager().checkPermission(permission,
6508 packageName, user.getIdentifier());
6509 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
6510 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
6511 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
6512 // Not controlled by policy
6513 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
6515 // Policy controlled so return result based on permission grant state
6516 return granted == PackageManager.PERMISSION_GRANTED
6517 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
6518 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
6521 Binder.restoreCallingIdentity(ident);