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 org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
25 import static org.xmlpull.v1.XmlPullParser.END_TAG;
26 import static org.xmlpull.v1.XmlPullParser.TEXT;
28 import android.Manifest.permission;
29 import android.accessibilityservice.AccessibilityServiceInfo;
30 import android.accounts.AccountManager;
31 import android.app.Activity;
32 import android.app.ActivityManagerNative;
33 import android.app.AlarmManager;
34 import android.app.AppGlobals;
35 import android.app.IActivityManager;
36 import android.app.Notification;
37 import android.app.NotificationManager;
38 import android.app.PendingIntent;
39 import android.app.StatusBarManager;
40 import android.app.admin.DeviceAdminInfo;
41 import android.app.admin.DeviceAdminReceiver;
42 import android.app.admin.DevicePolicyManager;
43 import android.app.admin.DevicePolicyManagerInternal;
44 import android.app.admin.IDevicePolicyManager;
45 import android.app.admin.SystemUpdatePolicy;
46 import android.app.backup.IBackupManager;
47 import android.content.BroadcastReceiver;
48 import android.content.ComponentName;
49 import android.content.ContentResolver;
50 import android.content.Context;
51 import android.content.Intent;
52 import android.content.IntentFilter;
53 import android.content.pm.ActivityInfo;
54 import android.content.pm.ApplicationInfo;
55 import android.content.pm.IPackageManager;
56 import android.content.pm.PackageManager;
57 import android.content.pm.PackageManager.NameNotFoundException;
58 import android.content.pm.PermissionInfo;
59 import android.content.pm.ResolveInfo;
60 import android.content.pm.ServiceInfo;
61 import android.content.pm.UserInfo;
62 import android.database.ContentObserver;
63 import android.graphics.Bitmap;
64 import android.media.AudioManager;
65 import android.media.IAudioService;
66 import android.net.ConnectivityManager;
67 import android.net.ProxyInfo;
68 import android.net.Uri;
69 import android.os.AsyncTask;
70 import android.os.Binder;
71 import android.os.Bundle;
72 import android.os.Environment;
73 import android.os.FileUtils;
74 import android.os.Handler;
75 import android.os.IBinder;
76 import android.os.PersistableBundle;
77 import android.os.PowerManager;
78 import android.os.PowerManagerInternal;
79 import android.os.Process;
80 import android.os.RecoverySystem;
81 import android.os.RemoteCallback;
82 import android.os.RemoteException;
83 import android.os.ServiceManager;
84 import android.os.SystemClock;
85 import android.os.SystemProperties;
86 import android.os.UserHandle;
87 import android.os.UserManager;
88 import android.os.storage.StorageManager;
89 import android.provider.ContactsContract.QuickContact;
90 import android.provider.ContactsInternal;
91 import android.provider.Settings;
92 import android.security.Credentials;
93 import android.security.IKeyChainAliasCallback;
94 import android.security.IKeyChainService;
95 import android.security.KeyChain;
96 import android.security.KeyChain.KeyChainConnection;
97 import android.service.persistentdata.PersistentDataBlockManager;
98 import android.text.TextUtils;
99 import android.util.EventLog;
100 import android.util.Log;
101 import android.util.PrintWriterPrinter;
102 import android.util.Printer;
103 import android.util.Slog;
104 import android.util.SparseArray;
105 import android.util.Xml;
106 import android.view.IWindowManager;
107 import android.view.accessibility.AccessibilityManager;
108 import android.view.accessibility.IAccessibilityManager;
109 import android.view.inputmethod.InputMethodInfo;
110 import android.view.inputmethod.InputMethodManager;
112 import com.android.internal.R;
113 import com.android.internal.statusbar.IStatusBarService;
114 import com.android.internal.util.FastXmlSerializer;
115 import com.android.internal.util.JournaledFile;
116 import com.android.internal.util.Preconditions;
117 import com.android.internal.util.XmlUtils;
118 import com.android.internal.widget.LockPatternUtils;
119 import com.android.server.LocalServices;
120 import com.android.server.SystemService;
121 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
123 import org.xmlpull.v1.XmlPullParser;
124 import org.xmlpull.v1.XmlPullParserException;
125 import org.xmlpull.v1.XmlSerializer;
127 import java.io.ByteArrayInputStream;
129 import java.io.FileDescriptor;
130 import java.io.FileInputStream;
131 import java.io.FileNotFoundException;
132 import java.io.FileOutputStream;
133 import java.io.IOException;
134 import java.io.PrintWriter;
135 import java.nio.charset.StandardCharsets;
136 import java.security.cert.CertificateException;
137 import java.security.cert.CertificateFactory;
138 import java.security.cert.X509Certificate;
139 import java.text.DateFormat;
140 import java.util.ArrayList;
141 import java.util.Arrays;
142 import java.util.Collections;
143 import java.util.Date;
144 import java.util.HashMap;
145 import java.util.HashSet;
146 import java.util.List;
147 import java.util.Map.Entry;
148 import java.util.Set;
151 * Implementation of the device policy APIs.
153 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
155 private static final String LOG_TAG = "DevicePolicyManagerService";
157 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
159 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
161 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
163 private static final String TAG_STATUS_BAR = "statusbar";
165 private static final String ATTR_DISABLED = "disabled";
167 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
168 "do-not-ask-credentials-on-boot";
170 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
172 private static final long MS_PER_DAY = 86400 * 1000;
174 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
176 protected static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
177 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
179 private static final int MONITORING_CERT_NOTIFICATION_ID = R.string.ssl_ca_cert_warning;
180 private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
182 private static final boolean DBG = false;
184 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
185 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
186 private static final String ATTR_PERMISSION_POLICY = "permission-policy";
188 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
190 private static final int STATUS_BAR_DISABLE_MASK =
191 StatusBarManager.DISABLE_EXPAND |
192 StatusBarManager.DISABLE_NOTIFICATION_ICONS |
193 StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
194 StatusBarManager.DISABLE_SEARCH;
196 private static final int STATUS_BAR_DISABLE2_MASK =
197 StatusBarManager.DISABLE2_QUICK_SETTINGS;
199 private static final Set<String> DEVICE_OWNER_USER_RESTRICTIONS;
201 DEVICE_OWNER_USER_RESTRICTIONS = new HashSet();
202 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_USB_FILE_TRANSFER);
203 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_TETHERING);
204 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_NETWORK_RESET);
205 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_FACTORY_RESET);
206 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADD_USER);
207 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
208 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
209 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
210 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_UNMUTE_MICROPHONE);
211 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADJUST_VOLUME);
212 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SMS);
213 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_FUN);
214 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SAFE_BOOT);
215 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CREATE_WINDOWS);
218 // The following user restrictions cannot be changed by any active admin, including device
219 // owner and profile owner.
220 private static final Set<String> IMMUTABLE_USER_RESTRICTIONS;
222 IMMUTABLE_USER_RESTRICTIONS = new HashSet();
223 IMMUTABLE_USER_RESTRICTIONS.add(UserManager.DISALLOW_WALLPAPER);
226 private static final Set<String> SECURE_SETTINGS_WHITELIST;
227 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
228 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
229 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
231 SECURE_SETTINGS_WHITELIST = new HashSet();
232 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
233 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
234 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
236 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new HashSet();
237 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
238 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
240 GLOBAL_SETTINGS_WHITELIST = new HashSet();
241 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
242 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
243 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
244 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
245 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
246 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
247 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
248 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
250 GLOBAL_SETTINGS_DEPRECATED = new HashSet();
251 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
252 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
253 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
254 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
255 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
258 // Keyguard features that when set of a profile will affect the profiles
260 private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
261 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
262 | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
264 // Keyguard features that are allowed to be set on a managed profile
265 private static final int PROFILE_KEYGUARD_FEATURES =
266 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
267 | DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
269 final Context mContext;
270 final UserManager mUserManager;
271 final PowerManager.WakeLock mWakeLock;
273 final LocalService mLocalService;
275 final PowerManager mPowerManager;
276 final PowerManagerInternal mPowerManagerInternal;
278 IWindowManager mIWindowManager;
279 NotificationManager mNotificationManager;
281 // Stores and loads state on device and profile owners.
282 private DeviceOwner mDeviceOwner;
284 private final Binder mToken = new Binder();
287 * Whether or not device admin feature is supported. If it isn't return defaults for all
290 private boolean mHasFeature;
292 public static final class Lifecycle extends SystemService {
293 private DevicePolicyManagerService mService;
295 public Lifecycle(Context context) {
297 mService = new DevicePolicyManagerService(context);
301 public void onStart() {
302 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
306 public void onBootPhase(int phase) {
307 if (phase == PHASE_LOCK_SETTINGS_READY) {
308 mService.systemReady();
313 public static class DevicePolicyData {
314 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
315 int mActivePasswordLength = 0;
316 int mActivePasswordUpperCase = 0;
317 int mActivePasswordLowerCase = 0;
318 int mActivePasswordLetters = 0;
319 int mActivePasswordNumeric = 0;
320 int mActivePasswordSymbols = 0;
321 int mActivePasswordNonLetter = 0;
322 int mFailedPasswordAttempts = 0;
325 int mPasswordOwner = -1;
326 long mLastMaximumTimeToLock = -1;
327 boolean mUserSetupComplete = false;
328 int mPermissionPolicy;
330 final HashMap<ComponentName, ActiveAdmin> mAdminMap = new HashMap<>();
331 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
332 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
334 // This is the list of component allowed to start lock task mode.
335 List<String> mLockTaskPackages = new ArrayList<>();
337 boolean mStatusBarDisabled = false;
339 ComponentName mRestrictionsProvider;
341 String mDelegatedCertInstallerPackage;
343 boolean doNotAskCredentialsOnBoot = false;
345 public DevicePolicyData(int userHandle) {
346 mUserHandle = userHandle;
350 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
352 Handler mHandler = new Handler();
354 BroadcastReceiver mReceiver = new BroadcastReceiver() {
356 public void onReceive(Context context, Intent intent) {
357 final String action = intent.getAction();
358 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
360 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
361 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
362 if (DBG) Slog.v(LOG_TAG, "Sending password expiration notifications for action "
363 + action + " for user " + userHandle);
364 mHandler.post(new Runnable() {
367 handlePasswordExpirationNotification(userHandle);
371 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
372 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
373 new MonitoringCertNotificationTask().execute(intent);
375 if (Intent.ACTION_USER_REMOVED.equals(action)) {
376 removeUserData(userHandle);
377 } else if (Intent.ACTION_USER_STARTED.equals(action)
378 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
380 if (Intent.ACTION_USER_STARTED.equals(action)) {
381 // Reset the policy data
382 synchronized (DevicePolicyManagerService.this) {
383 mUserData.remove(userHandle);
386 handlePackagesChanged(null /* check all admins */, userHandle);
387 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
388 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
389 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
390 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
391 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
392 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
393 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
394 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
395 clearWipeProfileNotification();
400 static class ActiveAdmin {
401 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
402 private static final String TAG_DISABLE_CAMERA = "disable-camera";
403 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
404 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
405 = "disable-bt-contacts-sharing";
406 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
407 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
408 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
409 private static final String TAG_ACCOUNT_TYPE = "account-type";
410 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
411 = "permitted-accessiblity-services";
412 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
413 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
414 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
415 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
416 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
417 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
418 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
419 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
420 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
421 private static final String TAG_PERMITTED_IMES = "permitted-imes";
422 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
423 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
424 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
425 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
426 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
427 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
428 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
429 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
430 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
431 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
432 private static final String ATTR_VALUE = "value";
433 private static final String TAG_PASSWORD_QUALITY = "password-quality";
434 private static final String TAG_POLICIES = "policies";
435 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
436 "cross-profile-widget-providers";
437 private static final String TAG_PROVIDER = "provider";
438 private static final String TAG_PACKAGE_LIST_ITEM = "item";
440 final DeviceAdminInfo info;
442 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
444 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
445 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
447 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
448 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
450 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
451 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
453 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
454 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
456 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
457 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
459 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
460 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
462 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
463 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
465 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
466 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
468 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
469 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
471 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
472 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
474 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
475 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
477 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
478 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
480 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
482 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
484 boolean encryptionRequested = false;
485 boolean disableCamera = false;
486 boolean disableCallerId = false;
487 boolean disableBluetoothContactSharing = true;
488 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
489 boolean requireAutoTime = false; // Can only be set by a device owner.
491 static class TrustAgentInfo {
492 public PersistableBundle options;
493 TrustAgentInfo(PersistableBundle bundle) {
498 Set<String> accountTypesWithManagementDisabled = new HashSet<String>();
500 // The list of permitted accessibility services package namesas set by a profile
501 // or device owner. Null means all accessibility services are allowed, empty means
502 // none except system services are allowed.
503 List<String> permittedAccessiblityServices;
505 // The list of permitted input methods package names as set by a profile or device owner.
506 // Null means all input methods are allowed, empty means none except system imes are
508 List<String> permittedInputMethods;
510 // TODO: review implementation decisions with frameworks team
511 boolean specifiesGlobalProxy = false;
512 String globalProxySpec = null;
513 String globalProxyExclusionList = null;
515 HashMap<String, TrustAgentInfo> trustAgentInfos = new HashMap<String, TrustAgentInfo>();
517 List<String> crossProfileWidgetProviders;
519 ActiveAdmin(DeviceAdminInfo _info) {
523 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
525 public UserHandle getUserHandle() {
526 return new UserHandle(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
529 void writeToXml(XmlSerializer out)
530 throws IllegalArgumentException, IllegalStateException, IOException {
531 out.startTag(null, TAG_POLICIES);
532 info.writePoliciesToXml(out);
533 out.endTag(null, TAG_POLICIES);
534 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
535 out.startTag(null, TAG_PASSWORD_QUALITY);
536 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
537 out.endTag(null, TAG_PASSWORD_QUALITY);
538 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
539 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
540 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
541 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
543 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
544 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
545 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
546 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
548 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
549 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
550 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
551 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
553 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
554 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
555 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
556 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
558 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
559 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
560 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
561 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
563 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
564 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
565 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
566 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
568 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
569 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
570 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
571 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
573 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
574 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
575 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
576 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
579 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
580 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
581 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
582 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
584 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
585 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
586 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
587 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
589 if (specifiesGlobalProxy) {
590 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
591 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
592 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
593 if (globalProxySpec != null) {
594 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
595 out.attribute(null, ATTR_VALUE, globalProxySpec);
596 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
598 if (globalProxyExclusionList != null) {
599 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
600 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
601 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
604 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
605 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
606 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
607 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
609 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
610 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
611 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
612 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
614 if (encryptionRequested) {
615 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
616 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
617 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
620 out.startTag(null, TAG_DISABLE_CAMERA);
621 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
622 out.endTag(null, TAG_DISABLE_CAMERA);
624 if (disableCallerId) {
625 out.startTag(null, TAG_DISABLE_CALLER_ID);
626 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
627 out.endTag(null, TAG_DISABLE_CALLER_ID);
629 if (disableBluetoothContactSharing) {
630 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
631 out.attribute(null, ATTR_VALUE,
632 Boolean.toString(disableBluetoothContactSharing));
633 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
635 if (disableScreenCapture) {
636 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
637 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
638 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
640 if (requireAutoTime) {
641 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
642 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
643 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
645 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
646 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
647 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
648 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
650 if (!accountTypesWithManagementDisabled.isEmpty()) {
651 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
652 for (String ac : accountTypesWithManagementDisabled) {
653 out.startTag(null, TAG_ACCOUNT_TYPE);
654 out.attribute(null, ATTR_VALUE, ac);
655 out.endTag(null, TAG_ACCOUNT_TYPE);
657 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
659 if (!trustAgentInfos.isEmpty()) {
660 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
661 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
662 for (Entry<String, TrustAgentInfo> entry : set) {
663 TrustAgentInfo trustAgentInfo = entry.getValue();
664 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
665 out.attribute(null, ATTR_VALUE, entry.getKey());
666 if (trustAgentInfo.options != null) {
667 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
669 trustAgentInfo.options.saveToXml(out);
670 } catch (XmlPullParserException e) {
671 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
673 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
675 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
677 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
679 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
680 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
681 final int providerCount = crossProfileWidgetProviders.size();
682 for (int i = 0; i < providerCount; i++) {
683 String provider = crossProfileWidgetProviders.get(i);
684 out.startTag(null, TAG_PROVIDER);
685 out.attribute(null, ATTR_VALUE, provider);
686 out.endTag(null, TAG_PROVIDER);
688 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
690 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
691 permittedAccessiblityServices);
692 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
695 void writePackageListToXml(XmlSerializer out, String outerTag,
696 List<String> packageList)
697 throws IllegalArgumentException, IllegalStateException, IOException {
698 if (packageList == null) {
702 out.startTag(null, outerTag);
703 for (String packageName : packageList) {
704 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
705 out.attribute(null, ATTR_VALUE, packageName);
706 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
708 out.endTag(null, outerTag);
711 void readFromXml(XmlPullParser parser)
712 throws XmlPullParserException, IOException {
713 int outerDepth = parser.getDepth();
715 while ((type=parser.next()) != END_DOCUMENT
716 && (type != END_TAG || parser.getDepth() > outerDepth)) {
717 if (type == END_TAG || type == TEXT) {
720 String tag = parser.getName();
721 if (TAG_POLICIES.equals(tag)) {
722 info.readPoliciesFromXml(parser);
723 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
724 passwordQuality = Integer.parseInt(
725 parser.getAttributeValue(null, ATTR_VALUE));
726 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
727 minimumPasswordLength = Integer.parseInt(
728 parser.getAttributeValue(null, ATTR_VALUE));
729 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
730 passwordHistoryLength = Integer.parseInt(
731 parser.getAttributeValue(null, ATTR_VALUE));
732 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
733 minimumPasswordUpperCase = Integer.parseInt(
734 parser.getAttributeValue(null, ATTR_VALUE));
735 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
736 minimumPasswordLowerCase = Integer.parseInt(
737 parser.getAttributeValue(null, ATTR_VALUE));
738 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
739 minimumPasswordLetters = Integer.parseInt(
740 parser.getAttributeValue(null, ATTR_VALUE));
741 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
742 minimumPasswordNumeric = Integer.parseInt(
743 parser.getAttributeValue(null, ATTR_VALUE));
744 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
745 minimumPasswordSymbols = Integer.parseInt(
746 parser.getAttributeValue(null, ATTR_VALUE));
747 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
748 minimumPasswordNonLetter = Integer.parseInt(
749 parser.getAttributeValue(null, ATTR_VALUE));
750 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
751 maximumTimeToUnlock = Long.parseLong(
752 parser.getAttributeValue(null, ATTR_VALUE));
753 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
754 maximumFailedPasswordsForWipe = Integer.parseInt(
755 parser.getAttributeValue(null, ATTR_VALUE));
756 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
757 specifiesGlobalProxy = Boolean.parseBoolean(
758 parser.getAttributeValue(null, ATTR_VALUE));
759 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
761 parser.getAttributeValue(null, ATTR_VALUE);
762 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
763 globalProxyExclusionList =
764 parser.getAttributeValue(null, ATTR_VALUE);
765 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
766 passwordExpirationTimeout = Long.parseLong(
767 parser.getAttributeValue(null, ATTR_VALUE));
768 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
769 passwordExpirationDate = Long.parseLong(
770 parser.getAttributeValue(null, ATTR_VALUE));
771 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
772 encryptionRequested = Boolean.parseBoolean(
773 parser.getAttributeValue(null, ATTR_VALUE));
774 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
775 disableCamera = Boolean.parseBoolean(
776 parser.getAttributeValue(null, ATTR_VALUE));
777 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
778 disableCallerId = Boolean.parseBoolean(
779 parser.getAttributeValue(null, ATTR_VALUE));
780 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
781 disableBluetoothContactSharing = Boolean.parseBoolean(parser
782 .getAttributeValue(null, ATTR_VALUE));
783 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
784 disableScreenCapture = Boolean.parseBoolean(
785 parser.getAttributeValue(null, ATTR_VALUE));
786 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
787 requireAutoTime= Boolean.parseBoolean(
788 parser.getAttributeValue(null, ATTR_VALUE));
789 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
790 disabledKeyguardFeatures = Integer.parseInt(
791 parser.getAttributeValue(null, ATTR_VALUE));
792 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
793 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
794 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
795 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
796 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
797 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
798 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
799 permittedAccessiblityServices = readPackageList(parser, tag);
800 } else if (TAG_PERMITTED_IMES.equals(tag)) {
801 permittedInputMethods = readPackageList(parser, tag);
803 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
804 XmlUtils.skipCurrentTag(parser);
809 private List<String> readPackageList(XmlPullParser parser,
810 String tag) throws XmlPullParserException, IOException {
811 List<String> result = new ArrayList<String>();
812 int outerDepth = parser.getDepth();
814 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
815 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
816 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
819 String outerTag = parser.getName();
820 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
821 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
822 if (packageName != null) {
823 result.add(packageName);
825 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
828 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
834 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
835 throws XmlPullParserException, IOException {
836 int outerDepthDAM = parser.getDepth();
838 Set<String> result = new HashSet<String>();
839 while ((typeDAM=parser.next()) != END_DOCUMENT
840 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
841 if (typeDAM == END_TAG || typeDAM == TEXT) {
844 String tagDAM = parser.getName();
845 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
846 result.add(parser.getAttributeValue(null, ATTR_VALUE));
848 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
854 private HashMap<String, TrustAgentInfo> getAllTrustAgentInfos(
855 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
856 int outerDepthDAM = parser.getDepth();
858 HashMap<String, TrustAgentInfo> result = new HashMap<String, TrustAgentInfo>();
859 while ((typeDAM=parser.next()) != END_DOCUMENT
860 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
861 if (typeDAM == END_TAG || typeDAM == TEXT) {
864 String tagDAM = parser.getName();
865 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
866 final String component = parser.getAttributeValue(null, ATTR_VALUE);
867 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
868 result.put(component, trustAgentInfo);
870 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
876 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
877 throws XmlPullParserException, IOException {
878 int outerDepthDAM = parser.getDepth();
880 TrustAgentInfo result = new TrustAgentInfo(null);
881 while ((typeDAM=parser.next()) != END_DOCUMENT
882 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
883 if (typeDAM == END_TAG || typeDAM == TEXT) {
886 String tagDAM = parser.getName();
887 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
888 PersistableBundle bundle = new PersistableBundle();
889 bundle.restoreFromXml(parser);
890 result.options = bundle;
892 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
898 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
899 throws XmlPullParserException, IOException {
900 int outerDepthDAM = parser.getDepth();
902 ArrayList<String> result = null;
903 while ((typeDAM=parser.next()) != END_DOCUMENT
904 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
905 if (typeDAM == END_TAG || typeDAM == TEXT) {
908 String tagDAM = parser.getName();
909 if (TAG_PROVIDER.equals(tagDAM)) {
910 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
911 if (result == null) {
912 result = new ArrayList<>();
914 result.add(provider);
916 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
922 void dump(String prefix, PrintWriter pw) {
923 pw.print(prefix); pw.print("uid="); pw.println(getUid());
924 pw.print(prefix); pw.println("policies:");
925 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
927 for (int i=0; i<pols.size(); i++) {
928 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
931 pw.print(prefix); pw.print("passwordQuality=0x");
932 pw.println(Integer.toHexString(passwordQuality));
933 pw.print(prefix); pw.print("minimumPasswordLength=");
934 pw.println(minimumPasswordLength);
935 pw.print(prefix); pw.print("passwordHistoryLength=");
936 pw.println(passwordHistoryLength);
937 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
938 pw.println(minimumPasswordUpperCase);
939 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
940 pw.println(minimumPasswordLowerCase);
941 pw.print(prefix); pw.print("minimumPasswordLetters=");
942 pw.println(minimumPasswordLetters);
943 pw.print(prefix); pw.print("minimumPasswordNumeric=");
944 pw.println(minimumPasswordNumeric);
945 pw.print(prefix); pw.print("minimumPasswordSymbols=");
946 pw.println(minimumPasswordSymbols);
947 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
948 pw.println(minimumPasswordNonLetter);
949 pw.print(prefix); pw.print("maximumTimeToUnlock=");
950 pw.println(maximumTimeToUnlock);
951 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
952 pw.println(maximumFailedPasswordsForWipe);
953 pw.print(prefix); pw.print("specifiesGlobalProxy=");
954 pw.println(specifiesGlobalProxy);
955 pw.print(prefix); pw.print("passwordExpirationTimeout=");
956 pw.println(passwordExpirationTimeout);
957 pw.print(prefix); pw.print("passwordExpirationDate=");
958 pw.println(passwordExpirationDate);
959 if (globalProxySpec != null) {
960 pw.print(prefix); pw.print("globalProxySpec=");
961 pw.println(globalProxySpec);
963 if (globalProxyExclusionList != null) {
964 pw.print(prefix); pw.print("globalProxyEclusionList=");
965 pw.println(globalProxyExclusionList);
967 pw.print(prefix); pw.print("encryptionRequested=");
968 pw.println(encryptionRequested);
969 pw.print(prefix); pw.print("disableCamera=");
970 pw.println(disableCamera);
971 pw.print(prefix); pw.print("disableCallerId=");
972 pw.println(disableCallerId);
973 pw.print(prefix); pw.print("disableBluetoothContactSharing=");
974 pw.println(disableBluetoothContactSharing);
975 pw.print(prefix); pw.print("disableScreenCapture=");
976 pw.println(disableScreenCapture);
977 pw.print(prefix); pw.print("requireAutoTime=");
978 pw.println(requireAutoTime);
979 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
980 pw.println(disabledKeyguardFeatures);
981 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
982 pw.println(crossProfileWidgetProviders);
983 if (!(permittedAccessiblityServices == null)) {
984 pw.print(prefix); pw.print("permittedAccessibilityServices=");
985 pw.println(permittedAccessiblityServices.toString());
987 if (!(permittedInputMethods == null)) {
988 pw.print(prefix); pw.print("permittedInputMethods=");
989 pw.println(permittedInputMethods.toString());
994 private void handlePackagesChanged(String packageName, int userHandle) {
995 boolean removed = false;
996 if (DBG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
997 DevicePolicyData policy = getUserData(userHandle);
998 IPackageManager pm = AppGlobals.getPackageManager();
999 synchronized (this) {
1000 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1001 ActiveAdmin aa = policy.mAdminList.get(i);
1003 // If we're checking all packages or if the specific one we're checking matches,
1004 // then check if the package and receiver still exist.
1005 final String adminPackage = aa.info.getPackageName();
1006 if (packageName == null || packageName.equals(adminPackage)) {
1007 if (pm.getPackageInfo(adminPackage, 0, userHandle) == null
1008 || pm.getReceiverInfo(aa.info.getComponent(), 0, userHandle)
1011 policy.mAdminList.remove(i);
1012 policy.mAdminMap.remove(aa.info.getComponent());
1015 } catch (RemoteException re) {
1020 validatePasswordOwnerLocked(policy);
1021 syncDeviceCapabilitiesLocked(policy);
1022 saveSettingsLocked(policy.mUserHandle);
1025 if (policy.mDelegatedCertInstallerPackage != null &&
1026 (packageName == null
1027 || packageName.equals(policy.mDelegatedCertInstallerPackage))) {
1029 // Check if delegated cert installer package is removed.
1030 if (pm.getPackageInfo(
1031 policy.mDelegatedCertInstallerPackage, 0, userHandle) == null) {
1032 policy.mDelegatedCertInstallerPackage = null;
1033 saveSettingsLocked(policy.mUserHandle);
1035 } catch (RemoteException e) {
1043 * Instantiates the service.
1045 public DevicePolicyManagerService(Context context) {
1047 mUserManager = UserManager.get(mContext);
1048 mHasFeature = context.getPackageManager().hasSystemFeature(
1049 PackageManager.FEATURE_DEVICE_ADMIN);
1050 mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1051 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
1052 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DPM");
1053 mLocalService = new LocalService();
1055 // Skip the rest of the initialization
1058 IntentFilter filter = new IntentFilter();
1059 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1060 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1061 filter.addAction(Intent.ACTION_USER_REMOVED);
1062 filter.addAction(Intent.ACTION_USER_STARTED);
1063 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1064 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1065 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1066 filter = new IntentFilter();
1067 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1068 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1069 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1070 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1071 filter.addDataScheme("package");
1072 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1073 filter = new IntentFilter();
1074 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1075 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1077 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1081 * Creates and loads the policy data from xml.
1082 * @param userHandle the user for whom to load the policy data
1085 DevicePolicyData getUserData(int userHandle) {
1086 synchronized (this) {
1087 DevicePolicyData policy = mUserData.get(userHandle);
1088 if (policy == null) {
1089 policy = new DevicePolicyData(userHandle);
1090 mUserData.append(userHandle, policy);
1091 loadSettingsLocked(policy, userHandle);
1098 * Creates and loads the policy data from xml for data that is shared between
1099 * various profiles of a user. In contrast to {@link #getUserData(int)}
1100 * it allows access to data of users other than the calling user.
1102 * This function should only be used for shared data, e.g. everything regarding
1103 * passwords and should be removed once multiple screen locks are present.
1104 * @param userHandle the user for whom to load the policy data
1107 DevicePolicyData getUserDataUnchecked(int userHandle) {
1108 long ident = Binder.clearCallingIdentity();
1110 return getUserData(userHandle);
1112 Binder.restoreCallingIdentity(ident);
1116 void removeUserData(int userHandle) {
1117 synchronized (this) {
1118 if (userHandle == UserHandle.USER_OWNER) {
1119 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1122 if (mDeviceOwner != null) {
1123 mDeviceOwner.removeProfileOwner(userHandle);
1124 mDeviceOwner.writeOwnerFile();
1127 DevicePolicyData policy = mUserData.get(userHandle);
1128 if (policy != null) {
1129 mUserData.remove(userHandle);
1131 File policyFile = new File(Environment.getUserSystemDirectory(userHandle),
1132 DEVICE_POLICIES_XML);
1133 policyFile.delete();
1134 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1136 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1139 void loadDeviceOwner() {
1140 synchronized (this) {
1141 mDeviceOwner = DeviceOwner.load();
1142 updateDeviceOwnerLocked();
1147 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1148 * reminders. Clears alarm if no expirations are configured.
1150 protected void setExpirationAlarmCheckLocked(Context context, DevicePolicyData policy) {
1151 final long expiration = getPasswordExpirationLocked(null, policy.mUserHandle);
1152 final long now = System.currentTimeMillis();
1153 final long timeToExpire = expiration - now;
1154 final long alarmTime;
1155 if (expiration == 0) {
1156 // No expirations are currently configured: Cancel alarm.
1158 } else if (timeToExpire <= 0) {
1159 // The password has already expired: Repeat every 24 hours.
1160 alarmTime = now + MS_PER_DAY;
1162 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1163 // the expiration time.
1164 long alarmInterval = timeToExpire % MS_PER_DAY;
1165 if (alarmInterval == 0) {
1166 alarmInterval = MS_PER_DAY;
1168 alarmTime = now + alarmInterval;
1171 long token = Binder.clearCallingIdentity();
1173 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1174 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1175 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1176 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1177 new UserHandle(policy.mUserHandle));
1179 if (alarmTime != 0) {
1180 am.set(AlarmManager.RTC, alarmTime, pi);
1183 Binder.restoreCallingIdentity(token);
1187 private IWindowManager getWindowManager() {
1188 if (mIWindowManager == null) {
1189 IBinder b = ServiceManager.getService(Context.WINDOW_SERVICE);
1190 mIWindowManager = IWindowManager.Stub.asInterface(b);
1192 return mIWindowManager;
1195 private NotificationManager getNotificationManager() {
1196 if (mNotificationManager == null) {
1197 mNotificationManager =
1198 (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
1200 return mNotificationManager;
1203 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1204 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1206 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1207 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1213 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1214 throws SecurityException {
1215 final int callingUid = Binder.getCallingUid();
1217 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1218 if (result != null) {
1223 final int userId = UserHandle.getUserId(callingUid);
1224 final DevicePolicyData policy = getUserData(userId);
1225 ActiveAdmin admin = policy.mAdminMap.get(who);
1226 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1227 throw new SecurityException("Admin " + admin.info.getComponent()
1228 + " does not own the device");
1230 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1231 throw new SecurityException("Admin " + admin.info.getComponent()
1232 + " does not own the profile");
1234 throw new SecurityException("Admin " + admin.info.getComponent()
1235 + " did not specify uses-policy for: "
1236 + admin.info.getTagForPolicy(reqPolicy));
1238 throw new SecurityException("No active admin owned by uid "
1239 + Binder.getCallingUid() + " for policy #" + reqPolicy);
1243 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
1245 // Try to find an admin which can use reqPolicy
1246 final int userId = UserHandle.getUserId(uid);
1247 final DevicePolicyData policy = getUserData(userId);
1249 ActiveAdmin admin = policy.mAdminMap.get(who);
1250 if (admin == null) {
1251 throw new SecurityException("No active admin " + who);
1253 if (admin.getUid() != uid) {
1254 throw new SecurityException("Admin " + who + " is not owned by uid "
1255 + Binder.getCallingUid());
1257 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
1261 for (ActiveAdmin admin : policy.mAdminList) {
1262 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
1272 private boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
1274 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
1275 boolean ownsProfile = (getProfileOwner(userId) != null
1276 && getProfileOwner(userId).getPackageName()
1277 .equals(admin.info.getPackageName()));
1278 boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName())
1279 && !hasUserSetupCompleted(userId);
1281 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1282 if ((userId == UserHandle.USER_OWNER && (ownsDevice || ownsInitialization))
1283 || (ownsDevice && ownsProfile)) {
1286 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1287 if ((userId == UserHandle.USER_OWNER && ownsDevice) || ownsProfile
1288 || ownsInitialization) {
1292 if (admin.info.usesPolicy(reqPolicy)) {
1299 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
1300 sendAdminCommandLocked(admin, action, null);
1303 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
1304 sendAdminCommandLocked(admin, action, null, result);
1308 * Send an update to one specific admin, get notified when that admin returns a result.
1310 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
1311 BroadcastReceiver result) {
1312 Intent intent = new Intent(action);
1313 intent.setComponent(admin.info.getComponent());
1314 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
1315 intent.putExtra("expiration", admin.passwordExpirationDate);
1317 if (adminExtras != null) {
1318 intent.putExtras(adminExtras);
1320 if (result != null) {
1321 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
1322 null, result, mHandler, Activity.RESULT_OK, null, null);
1324 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
1329 * Send an update to all admins of a user that enforce a specified policy.
1331 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
1332 final DevicePolicyData policy = getUserData(userHandle);
1333 final int count = policy.mAdminList.size();
1335 for (int i = 0; i < count; i++) {
1336 final ActiveAdmin admin = policy.mAdminList.get(i);
1337 if (admin.info.usesPolicy(reqPolicy)) {
1338 sendAdminCommandLocked(admin, action);
1345 * Send an update intent to all admins of a user and its profiles. Only send to admins that
1346 * enforce a specified policy.
1348 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
1350 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1351 for (UserInfo ui : profiles) {
1353 sendAdminCommandLocked(action, reqPolicy, id);
1357 void removeActiveAdminLocked(final ComponentName adminReceiver, int userHandle) {
1358 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
1359 if (admin != null) {
1360 synchronized (this) {
1361 getUserData(userHandle).mRemovingAdmins.add(adminReceiver);
1363 sendAdminCommandLocked(admin,
1364 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
1365 new BroadcastReceiver() {
1367 public void onReceive(Context context, Intent intent) {
1368 synchronized (DevicePolicyManagerService.this) {
1369 int userHandle = admin.getUserHandle().getIdentifier();
1370 DevicePolicyData policy = getUserData(userHandle);
1371 boolean doProxyCleanup = admin.info.usesPolicy(
1372 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
1373 policy.mAdminList.remove(admin);
1374 policy.mAdminMap.remove(adminReceiver);
1375 validatePasswordOwnerLocked(policy);
1376 syncDeviceCapabilitiesLocked(policy);
1377 if (doProxyCleanup) {
1378 resetGlobalProxyLocked(getUserData(userHandle));
1380 saveSettingsLocked(userHandle);
1381 updateMaximumTimeToLockLocked(policy);
1382 policy.mRemovingAdmins.remove(adminReceiver);
1389 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle) {
1393 enforceCrossUserPermission(userHandle);
1394 Intent resolveIntent = new Intent();
1395 resolveIntent.setComponent(adminName);
1396 List<ResolveInfo> infos = mContext.getPackageManager().queryBroadcastReceivers(
1398 PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
1400 if (infos == null || infos.size() <= 0) {
1401 throw new IllegalArgumentException("Unknown admin: " + adminName);
1405 return new DeviceAdminInfo(mContext, infos.get(0));
1406 } catch (XmlPullParserException e) {
1407 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
1410 } catch (IOException e) {
1411 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
1417 private static JournaledFile makeJournaledFile(int userHandle) {
1418 final String base = userHandle == 0
1419 ? "/data/system/" + DEVICE_POLICIES_XML
1420 : new File(Environment.getUserSystemDirectory(userHandle), DEVICE_POLICIES_XML)
1422 return new JournaledFile(new File(base), new File(base + ".tmp"));
1425 private void saveSettingsLocked(int userHandle) {
1426 DevicePolicyData policy = getUserData(userHandle);
1427 JournaledFile journal = makeJournaledFile(userHandle);
1428 FileOutputStream stream = null;
1430 stream = new FileOutputStream(journal.chooseForWrite(), false);
1431 XmlSerializer out = new FastXmlSerializer();
1432 out.setOutput(stream, StandardCharsets.UTF_8.name());
1433 out.startDocument(null, true);
1435 out.startTag(null, "policies");
1436 if (policy.mRestrictionsProvider != null) {
1437 out.attribute(null, ATTR_PERMISSION_PROVIDER,
1438 policy.mRestrictionsProvider.flattenToString());
1440 if (policy.mUserSetupComplete) {
1441 out.attribute(null, ATTR_SETUP_COMPLETE,
1442 Boolean.toString(true));
1444 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
1445 out.attribute(null, ATTR_PERMISSION_POLICY,
1446 Integer.toString(policy.mPermissionPolicy));
1448 if (policy.mDelegatedCertInstallerPackage != null) {
1449 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
1450 policy.mDelegatedCertInstallerPackage);
1453 final int N = policy.mAdminList.size();
1454 for (int i=0; i<N; i++) {
1455 ActiveAdmin ap = policy.mAdminList.get(i);
1457 out.startTag(null, "admin");
1458 out.attribute(null, "name", ap.info.getComponent().flattenToString());
1460 out.endTag(null, "admin");
1464 if (policy.mPasswordOwner >= 0) {
1465 out.startTag(null, "password-owner");
1466 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
1467 out.endTag(null, "password-owner");
1470 if (policy.mFailedPasswordAttempts != 0) {
1471 out.startTag(null, "failed-password-attempts");
1472 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
1473 out.endTag(null, "failed-password-attempts");
1476 if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
1477 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
1478 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
1479 || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
1480 out.startTag(null, "active-password");
1481 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
1482 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
1483 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
1484 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
1485 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
1486 out.attribute(null, "numeric", Integer
1487 .toString(policy.mActivePasswordNumeric));
1488 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
1489 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
1490 out.endTag(null, "active-password");
1493 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
1494 String component = policy.mLockTaskPackages.get(i);
1495 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
1496 out.attribute(null, "name", component);
1497 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
1500 if (policy.mStatusBarDisabled) {
1501 out.startTag(null, TAG_STATUS_BAR);
1502 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
1503 out.endTag(null, TAG_STATUS_BAR);
1506 if (policy.doNotAskCredentialsOnBoot) {
1507 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
1508 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
1511 out.endTag(null, "policies");
1515 FileUtils.sync(stream);
1518 sendChangedNotification(userHandle);
1519 } catch (IOException e) {
1521 if (stream != null) {
1524 } catch (IOException ex) {
1531 private void sendChangedNotification(int userHandle) {
1532 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1533 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1534 long ident = Binder.clearCallingIdentity();
1536 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
1538 Binder.restoreCallingIdentity(ident);
1542 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
1543 JournaledFile journal = makeJournaledFile(userHandle);
1544 FileInputStream stream = null;
1545 File file = journal.chooseForRead();
1547 stream = new FileInputStream(file);
1548 XmlPullParser parser = Xml.newPullParser();
1549 parser.setInput(stream, StandardCharsets.UTF_8.name());
1552 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1553 && type != XmlPullParser.START_TAG) {
1555 String tag = parser.getName();
1556 if (!"policies".equals(tag)) {
1557 throw new XmlPullParserException(
1558 "Settings do not start with policies tag: found " + tag);
1561 // Extract the permission provider component name if available
1562 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
1563 if (permissionProvider != null) {
1564 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
1566 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
1567 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
1568 policy.mUserSetupComplete = true;
1570 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
1571 if (!TextUtils.isEmpty(permissionPolicy)) {
1572 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
1574 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
1575 ATTR_DELEGATED_CERT_INSTALLER);
1577 type = parser.next();
1578 int outerDepth = parser.getDepth();
1579 policy.mLockTaskPackages.clear();
1580 policy.mAdminList.clear();
1581 policy.mAdminMap.clear();
1582 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1583 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1584 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1587 tag = parser.getName();
1588 if ("admin".equals(tag)) {
1589 String name = parser.getAttributeValue(null, "name");
1591 DeviceAdminInfo dai = findAdmin(
1592 ComponentName.unflattenFromString(name), userHandle);
1593 if (DBG && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
1595 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
1596 + dai.getActivityInfo().applicationInfo.uid + " for user "
1600 ActiveAdmin ap = new ActiveAdmin(dai);
1601 ap.readFromXml(parser);
1602 policy.mAdminMap.put(ap.info.getComponent(), ap);
1604 } catch (RuntimeException e) {
1605 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
1607 } else if ("failed-password-attempts".equals(tag)) {
1608 policy.mFailedPasswordAttempts = Integer.parseInt(
1609 parser.getAttributeValue(null, "value"));
1610 } else if ("password-owner".equals(tag)) {
1611 policy.mPasswordOwner = Integer.parseInt(
1612 parser.getAttributeValue(null, "value"));
1613 } else if ("active-password".equals(tag)) {
1614 policy.mActivePasswordQuality = Integer.parseInt(
1615 parser.getAttributeValue(null, "quality"));
1616 policy.mActivePasswordLength = Integer.parseInt(
1617 parser.getAttributeValue(null, "length"));
1618 policy.mActivePasswordUpperCase = Integer.parseInt(
1619 parser.getAttributeValue(null, "uppercase"));
1620 policy.mActivePasswordLowerCase = Integer.parseInt(
1621 parser.getAttributeValue(null, "lowercase"));
1622 policy.mActivePasswordLetters = Integer.parseInt(
1623 parser.getAttributeValue(null, "letters"));
1624 policy.mActivePasswordNumeric = Integer.parseInt(
1625 parser.getAttributeValue(null, "numeric"));
1626 policy.mActivePasswordSymbols = Integer.parseInt(
1627 parser.getAttributeValue(null, "symbols"));
1628 policy.mActivePasswordNonLetter = Integer.parseInt(
1629 parser.getAttributeValue(null, "nonletter"));
1630 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
1631 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
1632 } else if (TAG_STATUS_BAR.equals(tag)) {
1633 policy.mStatusBarDisabled = Boolean.parseBoolean(
1634 parser.getAttributeValue(null, ATTR_DISABLED));
1635 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
1636 policy.doNotAskCredentialsOnBoot = true;
1638 Slog.w(LOG_TAG, "Unknown tag: " + tag);
1639 XmlUtils.skipCurrentTag(parser);
1642 } catch (NullPointerException e) {
1643 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1644 } catch (NumberFormatException e) {
1645 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1646 } catch (XmlPullParserException e) {
1647 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1648 } catch (FileNotFoundException e) {
1649 // Don't be noisy, this is normal if we haven't defined any policies.
1650 } catch (IOException e) {
1651 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1652 } catch (IndexOutOfBoundsException e) {
1653 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1656 if (stream != null) {
1659 } catch (IOException e) {
1663 // Generate a list of admins from the admin map
1664 policy.mAdminList.addAll(policy.mAdminMap.values());
1666 // Validate that what we stored for the password quality matches
1667 // sufficiently what is currently set. Note that this is only
1668 // a sanity check in case the two get out of sync; this should
1669 // never normally happen.
1670 final long identity = Binder.clearCallingIdentity();
1672 LockPatternUtils utils = new LockPatternUtils(mContext);
1673 if (utils.getActivePasswordQuality(userHandle) < policy.mActivePasswordQuality) {
1674 Slog.w(LOG_TAG, "Active password quality 0x"
1675 + Integer.toHexString(policy.mActivePasswordQuality)
1676 + " does not match actual quality 0x"
1677 + Integer.toHexString(utils.getActivePasswordQuality(userHandle)));
1678 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
1679 policy.mActivePasswordLength = 0;
1680 policy.mActivePasswordUpperCase = 0;
1681 policy.mActivePasswordLowerCase = 0;
1682 policy.mActivePasswordLetters = 0;
1683 policy.mActivePasswordNumeric = 0;
1684 policy.mActivePasswordSymbols = 0;
1685 policy.mActivePasswordNonLetter = 0;
1688 Binder.restoreCallingIdentity(identity);
1691 validatePasswordOwnerLocked(policy);
1692 syncDeviceCapabilitiesLocked(policy);
1693 updateMaximumTimeToLockLocked(policy);
1694 addDeviceInitializerToLockTaskPackagesLocked(userHandle);
1695 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
1696 if (policy.mStatusBarDisabled) {
1697 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
1701 private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
1702 IActivityManager am = ActivityManagerNative.getDefault();
1703 long ident = Binder.clearCallingIdentity();
1705 am.updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
1706 } catch (RemoteException e) {
1707 // Not gonna happen.
1709 Binder.restoreCallingIdentity(ident);
1713 private void updateDeviceOwnerLocked() {
1714 IActivityManager am = ActivityManagerNative.getDefault();
1715 long ident = Binder.clearCallingIdentity();
1717 am.updateDeviceOwner(getDeviceOwner());
1718 } catch (RemoteException e) {
1719 // Not gonna happen.
1721 Binder.restoreCallingIdentity(ident);
1725 static void validateQualityConstant(int quality) {
1727 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
1728 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
1729 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
1730 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
1731 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
1732 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
1733 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
1734 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
1737 throw new IllegalArgumentException("Invalid quality constant: 0x"
1738 + Integer.toHexString(quality));
1741 void validatePasswordOwnerLocked(DevicePolicyData policy) {
1742 if (policy.mPasswordOwner >= 0) {
1743 boolean haveOwner = false;
1744 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1745 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
1751 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
1752 + " no longer active; disabling");
1753 policy.mPasswordOwner = -1;
1759 * Pushes down policy information to the system for any policies related to general device
1760 * capabilities that need to be enforced by lower level services (e.g. Camera services).
1762 void syncDeviceCapabilitiesLocked(DevicePolicyData policy) {
1763 // Ensure the status of the camera is synced down to the system. Interested native services
1764 // should monitor this value and act accordingly.
1765 String cameraPropertyForUser = SYSTEM_PROP_DISABLE_CAMERA_PREFIX + policy.mUserHandle;
1766 boolean systemState = SystemProperties.getBoolean(cameraPropertyForUser, false);
1767 boolean cameraDisabled = getCameraDisabled(null, policy.mUserHandle);
1768 if (cameraDisabled != systemState) {
1769 long token = Binder.clearCallingIdentity();
1771 String value = cameraDisabled ? "1" : "0";
1772 if (DBG) Slog.v(LOG_TAG, "Change in camera state ["
1773 + cameraPropertyForUser + "] = " + value);
1774 SystemProperties.set(cameraPropertyForUser, value);
1776 Binder.restoreCallingIdentity(token);
1781 public void systemReady() {
1785 getUserData(UserHandle.USER_OWNER);
1788 // Register an observer for watching for user setup complete.
1789 new SetupContentObserver(mHandler).register(mContext.getContentResolver());
1790 // Initialize the user setup state, to handle the upgrade case.
1791 updateUserSetupComplete();
1793 // Update the screen capture disabled cache in the window manager
1794 List<UserInfo> users = mUserManager.getUsers(true);
1795 final int N = users.size();
1796 for (int i = 0; i < N; i++) {
1797 int userHandle = users.get(i).id;
1798 updateScreenCaptureDisabledInWindowManager(userHandle,
1799 getScreenCaptureDisabled(null, userHandle));
1803 private void cleanUpOldUsers() {
1804 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
1806 Set<Integer> usersWithProfileOwners;
1807 Set<Integer> usersWithData;
1808 synchronized(this) {
1809 usersWithProfileOwners = mDeviceOwner != null
1810 ? mDeviceOwner.getProfileOwnerKeys() : new HashSet<Integer>();
1811 usersWithData = new HashSet<Integer>();
1812 for (int i = 0; i < mUserData.size(); i++) {
1813 usersWithData.add(mUserData.keyAt(i));
1816 List<UserInfo> allUsers = mUserManager.getUsers();
1818 Set<Integer> deletedUsers = new HashSet<Integer>();
1819 deletedUsers.addAll(usersWithProfileOwners);
1820 deletedUsers.addAll(usersWithData);
1821 for (UserInfo userInfo : allUsers) {
1822 deletedUsers.remove(userInfo.id);
1824 for (Integer userId : deletedUsers) {
1825 removeUserData(userId);
1829 private void handlePasswordExpirationNotification(int userHandle) {
1830 synchronized (this) {
1831 final long now = System.currentTimeMillis();
1833 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1834 for (UserInfo ui : profiles) {
1835 int profileUserHandle = ui.id;
1836 final DevicePolicyData policy = getUserData(profileUserHandle);
1837 final int count = policy.mAdminList.size();
1839 for (int i = 0; i < count; i++) {
1840 final ActiveAdmin admin = policy.mAdminList.get(i);
1841 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
1842 && admin.passwordExpirationTimeout > 0L
1843 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
1844 && admin.passwordExpirationDate > 0L) {
1845 sendAdminCommandLocked(admin,
1846 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
1851 setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
1855 private class MonitoringCertNotificationTask extends AsyncTask<Intent, Void, Void> {
1857 protected Void doInBackground(Intent... params) {
1858 int userHandle = params[0].getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
1860 if (userHandle == UserHandle.USER_ALL) {
1861 for (UserInfo userInfo : mUserManager.getUsers()) {
1862 manageNotification(userInfo.getUserHandle());
1865 manageNotification(new UserHandle(userHandle));
1870 private void manageNotification(UserHandle userHandle) {
1871 if (!mUserManager.isUserRunning(userHandle)) {
1875 // Call out to KeyChain to check for user-added CAs
1876 boolean hasCert = false;
1878 KeyChainConnection kcs = KeyChain.bindAsUser(mContext, userHandle);
1880 if (!kcs.getService().getUserCaAliases().getList().isEmpty()) {
1883 } catch (RemoteException e) {
1884 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
1888 } catch (InterruptedException e) {
1889 Thread.currentThread().interrupt();
1890 } catch (RuntimeException e) {
1891 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
1894 getNotificationManager().cancelAsUser(
1895 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
1899 // Build and show a warning notification
1902 final String ownerName = getDeviceOwnerName();
1903 if (isManagedProfile(userHandle.getIdentifier())) {
1904 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_administrator);
1905 smallIconId = R.drawable.stat_sys_certificate_info;
1906 } else if (ownerName != null) {
1907 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, ownerName);
1908 smallIconId = R.drawable.stat_sys_certificate_info;
1910 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
1911 smallIconId = android.R.drawable.stat_sys_warning;
1914 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
1915 dialogIntent.setFlags(
1916 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1917 dialogIntent.setPackage("com.android.settings");
1918 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
1919 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, userHandle);
1921 final Context userContext;
1923 userContext = mContext.createPackageContextAsUser("android", 0, userHandle);
1924 } catch (PackageManager.NameNotFoundException e) {
1925 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
1928 final Notification noti = new Notification.Builder(userContext)
1929 .setSmallIcon(smallIconId)
1930 .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning))
1931 .setContentText(contentText)
1932 .setContentIntent(notifyIntent)
1933 .setPriority(Notification.PRIORITY_HIGH)
1935 .setColor(mContext.getColor(
1936 com.android.internal.R.color.system_notification_accent_color))
1939 getNotificationManager().notifyAsUser(
1940 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
1945 * @param adminReceiver The admin to add
1946 * @param refreshing true = update an active admin, no error
1949 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
1953 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
1956 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
1957 Bundle onEnableData) {
1958 mContext.enforceCallingOrSelfPermission(
1959 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
1960 enforceCrossUserPermission(userHandle);
1962 DevicePolicyData policy = getUserData(userHandle);
1963 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle);
1965 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
1967 synchronized (this) {
1968 long ident = Binder.clearCallingIdentity();
1971 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
1972 throw new IllegalArgumentException("Admin is already added");
1974 ActiveAdmin newAdmin = new ActiveAdmin(info);
1975 policy.mAdminMap.put(adminReceiver, newAdmin);
1976 int replaceIndex = -1;
1977 final int N = policy.mAdminList.size();
1978 for (int i=0; i < N; i++) {
1979 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
1980 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
1985 if (replaceIndex == -1) {
1986 policy.mAdminList.add(newAdmin);
1987 enableIfNecessary(info.getPackageName(), userHandle);
1989 policy.mAdminList.set(replaceIndex, newAdmin);
1991 saveSettingsLocked(userHandle);
1992 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
1993 onEnableData, null);
1995 Binder.restoreCallingIdentity(ident);
2001 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2005 enforceCrossUserPermission(userHandle);
2006 synchronized (this) {
2007 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2012 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2016 enforceCrossUserPermission(userHandle);
2017 synchronized (this) {
2018 DevicePolicyData policyData = getUserData(userHandle);
2019 return policyData.mRemovingAdmins.contains(adminReceiver);
2024 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2028 enforceCrossUserPermission(userHandle);
2029 synchronized (this) {
2030 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2031 if (administrator == null) {
2032 throw new SecurityException("No active admin " + adminReceiver);
2034 return administrator.info.usesPolicy(policyId);
2039 @SuppressWarnings("unchecked")
2040 public List<ComponentName> getActiveAdmins(int userHandle) {
2042 return Collections.EMPTY_LIST;
2045 enforceCrossUserPermission(userHandle);
2046 synchronized (this) {
2047 DevicePolicyData policy = getUserData(userHandle);
2048 final int N = policy.mAdminList.size();
2052 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2053 for (int i=0; i<N; i++) {
2054 res.add(policy.mAdminList.get(i).info.getComponent());
2061 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2065 enforceCrossUserPermission(userHandle);
2066 synchronized (this) {
2067 DevicePolicyData policy = getUserData(userHandle);
2068 final int N = policy.mAdminList.size();
2069 for (int i=0; i<N; i++) {
2070 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2079 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
2083 enforceCrossUserPermission(userHandle);
2084 synchronized (this) {
2085 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2086 if (admin == null) {
2089 if (admin.getUid() != Binder.getCallingUid()) {
2090 // Active device owners must remain active admins.
2091 if (isDeviceOwner(adminReceiver.getPackageName())) {
2094 mContext.enforceCallingOrSelfPermission(
2095 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2097 long ident = Binder.clearCallingIdentity();
2099 removeActiveAdminLocked(adminReceiver, userHandle);
2101 Binder.restoreCallingIdentity(ident);
2107 public void setPasswordQuality(ComponentName who, int quality) {
2111 Preconditions.checkNotNull(who, "ComponentName is null");
2112 final int userHandle = UserHandle.getCallingUserId();
2113 validateQualityConstant(quality);
2115 synchronized (this) {
2116 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2117 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2118 if (ap.passwordQuality != quality) {
2119 ap.passwordQuality = quality;
2120 saveSettingsLocked(userHandle);
2126 public int getPasswordQuality(ComponentName who, int userHandle) {
2128 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2130 enforceCrossUserPermission(userHandle);
2131 synchronized (this) {
2132 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2135 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2136 return admin != null ? admin.passwordQuality : mode;
2139 // Return strictest policy for this user and profiles that are visible from this user.
2140 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2141 for (UserInfo userInfo : profiles) {
2142 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2143 final int N = policy.mAdminList.size();
2144 for (int i=0; i<N; i++) {
2145 ActiveAdmin admin = policy.mAdminList.get(i);
2146 if (mode < admin.passwordQuality) {
2147 mode = admin.passwordQuality;
2156 public void setPasswordMinimumLength(ComponentName who, int length) {
2160 Preconditions.checkNotNull(who, "ComponentName is null");
2161 final int userHandle = UserHandle.getCallingUserId();
2162 synchronized (this) {
2163 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2164 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2165 if (ap.minimumPasswordLength != length) {
2166 ap.minimumPasswordLength = length;
2167 saveSettingsLocked(userHandle);
2173 public int getPasswordMinimumLength(ComponentName who, int userHandle) {
2177 enforceCrossUserPermission(userHandle);
2178 synchronized (this) {
2182 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2183 return admin != null ? admin.minimumPasswordLength : length;
2186 // Return strictest policy for this user and profiles that are visible from this user.
2187 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2188 for (UserInfo userInfo : profiles) {
2189 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2190 final int N = policy.mAdminList.size();
2191 for (int i=0; i<N; i++) {
2192 ActiveAdmin admin = policy.mAdminList.get(i);
2193 if (length < admin.minimumPasswordLength) {
2194 length = admin.minimumPasswordLength;
2203 public void setPasswordHistoryLength(ComponentName who, int length) {
2207 Preconditions.checkNotNull(who, "ComponentName is null");
2208 final int userHandle = UserHandle.getCallingUserId();
2209 synchronized (this) {
2210 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2211 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2212 if (ap.passwordHistoryLength != length) {
2213 ap.passwordHistoryLength = length;
2214 saveSettingsLocked(userHandle);
2220 public int getPasswordHistoryLength(ComponentName who, int userHandle) {
2224 enforceCrossUserPermission(userHandle);
2225 synchronized (this) {
2229 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2230 return admin != null ? admin.passwordHistoryLength : length;
2233 // Return strictest policy for this user and profiles that are visible from this user.
2234 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2235 for (UserInfo userInfo : profiles) {
2236 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2237 final int N = policy.mAdminList.size();
2238 for (int i = 0; i < N; i++) {
2239 ActiveAdmin admin = policy.mAdminList.get(i);
2240 if (length < admin.passwordHistoryLength) {
2241 length = admin.passwordHistoryLength;
2250 public void setPasswordExpirationTimeout(ComponentName who, long timeout) {
2254 Preconditions.checkNotNull(who, "ComponentName is null");
2255 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
2256 final int userHandle = UserHandle.getCallingUserId();
2257 synchronized (this) {
2258 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2259 DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
2260 // Calling this API automatically bumps the expiration date
2261 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
2262 ap.passwordExpirationDate = expiration;
2263 ap.passwordExpirationTimeout = timeout;
2265 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
2266 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
2267 .format(new Date(expiration)));
2269 saveSettingsLocked(userHandle);
2270 // in case this is the first one
2271 setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
2276 * Return a single admin's expiration cycle time, or the min of all cycle times.
2277 * Returns 0 if not configured.
2280 public long getPasswordExpirationTimeout(ComponentName who, int userHandle) {
2284 enforceCrossUserPermission(userHandle);
2285 synchronized (this) {
2289 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2290 return admin != null ? admin.passwordExpirationTimeout : timeout;
2293 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2294 for (UserInfo userInfo : profiles) {
2295 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2296 final int N = policy.mAdminList.size();
2297 for (int i = 0; i < N; i++) {
2298 ActiveAdmin admin = policy.mAdminList.get(i);
2299 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
2300 && timeout > admin.passwordExpirationTimeout)) {
2301 timeout = admin.passwordExpirationTimeout;
2310 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
2311 final int userId = UserHandle.getCallingUserId();
2312 List<String> changedProviders = null;
2314 synchronized (this) {
2315 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2316 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2317 if (activeAdmin.crossProfileWidgetProviders == null) {
2318 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
2320 List<String> providers = activeAdmin.crossProfileWidgetProviders;
2321 if (!providers.contains(packageName)) {
2322 providers.add(packageName);
2323 changedProviders = new ArrayList<>(providers);
2324 saveSettingsLocked(userId);
2328 if (changedProviders != null) {
2329 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
2337 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
2338 final int userId = UserHandle.getCallingUserId();
2339 List<String> changedProviders = null;
2341 synchronized (this) {
2342 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2343 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2344 if (activeAdmin.crossProfileWidgetProviders == null) {
2347 List<String> providers = activeAdmin.crossProfileWidgetProviders;
2348 if (providers.remove(packageName)) {
2349 changedProviders = new ArrayList<>(providers);
2350 saveSettingsLocked(userId);
2354 if (changedProviders != null) {
2355 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
2363 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
2364 synchronized (this) {
2365 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2366 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2367 if (activeAdmin.crossProfileWidgetProviders == null
2368 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
2371 if (Binder.getCallingUid() == Process.myUid()) {
2372 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
2374 return activeAdmin.crossProfileWidgetProviders;
2380 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
2381 * Returns 0 if not configured.
2383 private long getPasswordExpirationLocked(ComponentName who, int userHandle) {
2387 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2388 return admin != null ? admin.passwordExpirationDate : timeout;
2391 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2392 for (UserInfo userInfo : profiles) {
2393 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2394 final int N = policy.mAdminList.size();
2395 for (int i = 0; i < N; i++) {
2396 ActiveAdmin admin = policy.mAdminList.get(i);
2397 if (timeout == 0L || (admin.passwordExpirationDate != 0
2398 && timeout > admin.passwordExpirationDate)) {
2399 timeout = admin.passwordExpirationDate;
2407 public long getPasswordExpiration(ComponentName who, int userHandle) {
2411 enforceCrossUserPermission(userHandle);
2412 synchronized (this) {
2413 return getPasswordExpirationLocked(who, userHandle);
2418 public void setPasswordMinimumUpperCase(ComponentName who, int length) {
2422 Preconditions.checkNotNull(who, "ComponentName is null");
2423 final int userHandle = UserHandle.getCallingUserId();
2424 synchronized (this) {
2425 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2426 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2427 if (ap.minimumPasswordUpperCase != length) {
2428 ap.minimumPasswordUpperCase = length;
2429 saveSettingsLocked(userHandle);
2435 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle) {
2439 enforceCrossUserPermission(userHandle);
2440 synchronized (this) {
2444 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2445 return admin != null ? admin.minimumPasswordUpperCase : length;
2448 // Return strictest policy for this user and profiles that are visible from this user.
2449 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2450 for (UserInfo userInfo : profiles) {
2451 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2452 final int N = policy.mAdminList.size();
2453 for (int i=0; i<N; i++) {
2454 ActiveAdmin admin = policy.mAdminList.get(i);
2455 if (length < admin.minimumPasswordUpperCase) {
2456 length = admin.minimumPasswordUpperCase;
2465 public void setPasswordMinimumLowerCase(ComponentName who, int length) {
2466 Preconditions.checkNotNull(who, "ComponentName is null");
2467 final int userHandle = UserHandle.getCallingUserId();
2468 synchronized (this) {
2469 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2470 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2471 if (ap.minimumPasswordLowerCase != length) {
2472 ap.minimumPasswordLowerCase = length;
2473 saveSettingsLocked(userHandle);
2479 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle) {
2483 enforceCrossUserPermission(userHandle);
2484 synchronized (this) {
2488 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2489 return admin != null ? admin.minimumPasswordLowerCase : length;
2492 // Return strictest policy for this user and profiles that are visible from this user.
2493 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2494 for (UserInfo userInfo : profiles) {
2495 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2496 final int N = policy.mAdminList.size();
2497 for (int i=0; i<N; i++) {
2498 ActiveAdmin admin = policy.mAdminList.get(i);
2499 if (length < admin.minimumPasswordLowerCase) {
2500 length = admin.minimumPasswordLowerCase;
2509 public void setPasswordMinimumLetters(ComponentName who, int length) {
2513 Preconditions.checkNotNull(who, "ComponentName is null");
2514 final int userHandle = UserHandle.getCallingUserId();
2515 synchronized (this) {
2516 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2517 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2518 if (ap.minimumPasswordLetters != length) {
2519 ap.minimumPasswordLetters = length;
2520 saveSettingsLocked(userHandle);
2526 public int getPasswordMinimumLetters(ComponentName who, int userHandle) {
2530 enforceCrossUserPermission(userHandle);
2531 synchronized (this) {
2535 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2536 return admin != null ? admin.minimumPasswordLetters : length;
2539 // Return strictest policy for this user and profiles that are visible from this user.
2540 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2541 for (UserInfo userInfo : profiles) {
2542 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2543 final int N = policy.mAdminList.size();
2544 for (int i=0; i<N; i++) {
2545 ActiveAdmin admin = policy.mAdminList.get(i);
2546 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2549 if (length < admin.minimumPasswordLetters) {
2550 length = admin.minimumPasswordLetters;
2559 public void setPasswordMinimumNumeric(ComponentName who, int length) {
2563 Preconditions.checkNotNull(who, "ComponentName is null");
2564 final int userHandle = UserHandle.getCallingUserId();
2565 synchronized (this) {
2566 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2567 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2568 if (ap.minimumPasswordNumeric != length) {
2569 ap.minimumPasswordNumeric = length;
2570 saveSettingsLocked(userHandle);
2576 public int getPasswordMinimumNumeric(ComponentName who, int userHandle) {
2580 enforceCrossUserPermission(userHandle);
2581 synchronized (this) {
2585 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2586 return admin != null ? admin.minimumPasswordNumeric : length;
2589 // Return strictest policy for this user and profiles that are visible from this user.
2590 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2591 for (UserInfo userInfo : profiles) {
2592 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2593 final int N = policy.mAdminList.size();
2594 for (int i = 0; i < N; i++) {
2595 ActiveAdmin admin = policy.mAdminList.get(i);
2596 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2599 if (length < admin.minimumPasswordNumeric) {
2600 length = admin.minimumPasswordNumeric;
2609 public void setPasswordMinimumSymbols(ComponentName who, int length) {
2613 Preconditions.checkNotNull(who, "ComponentName is null");
2614 final int userHandle = UserHandle.getCallingUserId();
2615 synchronized (this) {
2616 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2617 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2618 if (ap.minimumPasswordSymbols != length) {
2619 ap.minimumPasswordSymbols = length;
2620 saveSettingsLocked(userHandle);
2626 public int getPasswordMinimumSymbols(ComponentName who, int userHandle) {
2630 enforceCrossUserPermission(userHandle);
2631 synchronized (this) {
2635 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2636 return admin != null ? admin.minimumPasswordSymbols : length;
2639 // Return strictest policy for this user and profiles that are visible from this user.
2640 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2641 for (UserInfo userInfo : profiles) {
2642 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2643 final int N = policy.mAdminList.size();
2644 for (int i=0; i<N; i++) {
2645 ActiveAdmin admin = policy.mAdminList.get(i);
2646 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2649 if (length < admin.minimumPasswordSymbols) {
2650 length = admin.minimumPasswordSymbols;
2659 public void setPasswordMinimumNonLetter(ComponentName who, int length) {
2663 Preconditions.checkNotNull(who, "ComponentName is null");
2664 final int userHandle = UserHandle.getCallingUserId();
2665 synchronized (this) {
2666 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2667 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2668 if (ap.minimumPasswordNonLetter != length) {
2669 ap.minimumPasswordNonLetter = length;
2670 saveSettingsLocked(userHandle);
2676 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle) {
2680 enforceCrossUserPermission(userHandle);
2681 synchronized (this) {
2685 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2686 return admin != null ? admin.minimumPasswordNonLetter : length;
2689 // Return strictest policy for this user and profiles that are visible from this user.
2690 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2691 for (UserInfo userInfo : profiles) {
2692 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2693 final int N = policy.mAdminList.size();
2694 for (int i=0; i<N; i++) {
2695 ActiveAdmin admin = policy.mAdminList.get(i);
2696 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2699 if (length < admin.minimumPasswordNonLetter) {
2700 length = admin.minimumPasswordNonLetter;
2709 public boolean isActivePasswordSufficient(int userHandle) {
2713 enforceCrossUserPermission(userHandle);
2715 synchronized (this) {
2717 // The active password is stored in the user that runs the launcher
2718 // If the user this is called from is part of a profile group, that is the parent
2720 UserInfo parent = getProfileParent(userHandle);
2721 int id = (parent == null) ? userHandle : parent.id;
2722 DevicePolicyData policy = getUserDataUnchecked(id);
2724 // This API can only be called by an active device admin,
2725 // so try to retrieve it to check that the caller is one.
2726 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2727 if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle)
2728 || policy.mActivePasswordLength < getPasswordMinimumLength(null, userHandle)) {
2731 if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2734 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(null, userHandle)
2735 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(null, userHandle)
2736 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(null, userHandle)
2737 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(null, userHandle)
2738 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(null, userHandle)
2739 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(null, userHandle);
2744 public int getCurrentFailedPasswordAttempts(int userHandle) {
2745 synchronized (this) {
2746 // This API can only be called by an active device admin,
2747 // so try to retrieve it to check that the caller is one.
2748 getActiveAdminForCallerLocked(null,
2749 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2751 // The active password is stored in the parent.
2752 UserInfo parent = getProfileParent(userHandle);
2753 int id = (parent == null) ? userHandle : parent.id;
2754 DevicePolicyData policy = getUserDataUnchecked(id);
2756 return policy.mFailedPasswordAttempts;
2761 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num) {
2765 Preconditions.checkNotNull(who, "ComponentName is null");
2766 final int userHandle = UserHandle.getCallingUserId();
2767 synchronized (this) {
2768 // This API can only be called by an active device admin,
2769 // so try to retrieve it to check that the caller is one.
2770 getActiveAdminForCallerLocked(who,
2771 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
2772 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2773 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2774 if (ap.maximumFailedPasswordsForWipe != num) {
2775 ap.maximumFailedPasswordsForWipe = num;
2776 saveSettingsLocked(userHandle);
2782 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle) {
2786 enforceCrossUserPermission(userHandle);
2787 synchronized (this) {
2788 ActiveAdmin admin = (who != null) ? getActiveAdminUncheckedLocked(who, userHandle)
2789 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
2790 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
2795 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
2797 return UserHandle.USER_NULL;
2799 enforceCrossUserPermission(userHandle);
2800 synchronized (this) {
2801 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
2802 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
2807 * Returns the admin with the strictest policy on maximum failed passwords for this user and all
2808 * profiles that are visible from this user. If the policy for the primary and any other profile
2809 * are equal, it returns the admin for the primary profile.
2810 * Returns {@code null} if none of them have that policy set.
2812 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(int userHandle) {
2814 ActiveAdmin strictestAdmin = null;
2815 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
2816 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2817 for (ActiveAdmin admin : policy.mAdminList) {
2818 if (admin.maximumFailedPasswordsForWipe ==
2819 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
2820 continue; // No max number of failed passwords policy set for this profile.
2823 // We always favor the primary profile if several profiles have the same value set.
2825 count > admin.maximumFailedPasswordsForWipe ||
2826 (userInfo.isPrimary() && count >= admin.maximumFailedPasswordsForWipe)) {
2827 count = admin.maximumFailedPasswordsForWipe;
2828 strictestAdmin = admin;
2832 return strictestAdmin;
2836 public boolean resetPassword(String passwordOrNull, int flags) {
2840 final int userHandle = UserHandle.getCallingUserId();
2841 enforceNotManagedProfile(userHandle, "reset the password");
2843 String password = passwordOrNull != null ? passwordOrNull : "";
2846 synchronized (this) {
2847 // This api can only be called by an active device admin,
2848 // so try to retrieve it to check that the caller is one.
2849 getActiveAdminForCallerLocked(null,
2850 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
2851 quality = getPasswordQuality(null, userHandle);
2852 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
2853 int realQuality = LockPatternUtils.computePasswordQuality(password);
2854 if (realQuality < quality
2855 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2856 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
2857 + Integer.toHexString(realQuality)
2858 + " does not meet required quality 0x"
2859 + Integer.toHexString(quality));
2862 quality = Math.max(realQuality, quality);
2864 int length = getPasswordMinimumLength(null, userHandle);
2865 if (password.length() < length) {
2866 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
2867 + " does not meet required length " + length);
2870 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2877 for (int i = 0; i < password.length(); i++) {
2878 char c = password.charAt(i);
2879 if (c >= 'A' && c <= 'Z') {
2882 } else if (c >= 'a' && c <= 'z') {
2885 } else if (c >= '0' && c <= '9') {
2893 int neededLetters = getPasswordMinimumLetters(null, userHandle);
2894 if(letters < neededLetters) {
2895 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
2896 + " does not meet required number of letters " + neededLetters);
2899 int neededNumbers = getPasswordMinimumNumeric(null, userHandle);
2900 if (numbers < neededNumbers) {
2901 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
2902 + " does not meet required number of numerical digits "
2906 int neededLowerCase = getPasswordMinimumLowerCase(null, userHandle);
2907 if (lowercase < neededLowerCase) {
2908 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
2909 + " does not meet required number of lowercase letters "
2913 int neededUpperCase = getPasswordMinimumUpperCase(null, userHandle);
2914 if (uppercase < neededUpperCase) {
2915 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
2916 + " does not meet required number of uppercase letters "
2920 int neededSymbols = getPasswordMinimumSymbols(null, userHandle);
2921 if (symbols < neededSymbols) {
2922 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
2923 + " does not meet required number of special symbols " + neededSymbols);
2926 int neededNonLetter = getPasswordMinimumNonLetter(null, userHandle);
2927 if (nonletter < neededNonLetter) {
2928 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
2929 + " does not meet required number of non-letter characters "
2936 int callingUid = Binder.getCallingUid();
2937 DevicePolicyData policy = getUserData(userHandle);
2938 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
2939 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
2943 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwnerOrInitializer(callingUid);
2944 boolean doNotAskCredentialsOnBoot =
2945 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
2946 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
2947 setDoNotAskCredentialsOnBoot();
2950 // Don't do this with the lock held, because it is going to call
2951 // back in to the service.
2952 long ident = Binder.clearCallingIdentity();
2954 LockPatternUtils utils = new LockPatternUtils(mContext);
2955 if (!TextUtils.isEmpty(password)) {
2956 utils.saveLockPassword(password, null, quality, userHandle);
2958 utils.clearLock(userHandle);
2960 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
2962 utils.requireCredentialEntry(UserHandle.USER_ALL);
2964 synchronized (this) {
2965 int newOwner = requireEntry ? callingUid : -1;
2966 if (policy.mPasswordOwner != newOwner) {
2967 policy.mPasswordOwner = newOwner;
2968 saveSettingsLocked(userHandle);
2972 Binder.restoreCallingIdentity(ident);
2978 private void setDoNotAskCredentialsOnBoot() {
2979 synchronized (this) {
2980 DevicePolicyData policyData = getUserData(UserHandle.USER_OWNER);
2981 if (!policyData.doNotAskCredentialsOnBoot) {
2982 policyData.doNotAskCredentialsOnBoot = true;
2983 saveSettingsLocked(UserHandle.USER_OWNER);
2989 public boolean getDoNotAskCredentialsOnBoot() {
2990 mContext.enforceCallingOrSelfPermission(
2991 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
2992 synchronized (this) {
2993 DevicePolicyData policyData = getUserData(UserHandle.USER_OWNER);
2994 return policyData.doNotAskCredentialsOnBoot;
2999 public void setMaximumTimeToLock(ComponentName who, long timeMs) {
3003 Preconditions.checkNotNull(who, "ComponentName is null");
3004 final int userHandle = UserHandle.getCallingUserId();
3005 synchronized (this) {
3006 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3007 DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
3008 if (ap.maximumTimeToUnlock != timeMs) {
3009 ap.maximumTimeToUnlock = timeMs;
3010 saveSettingsLocked(userHandle);
3011 updateMaximumTimeToLockLocked(getUserData(userHandle));
3016 void updateMaximumTimeToLockLocked(DevicePolicyData policy) {
3017 long timeMs = getMaximumTimeToLock(null, policy.mUserHandle);
3018 if (policy.mLastMaximumTimeToLock == timeMs) {
3022 long ident = Binder.clearCallingIdentity();
3025 timeMs = Integer.MAX_VALUE;
3027 // Make sure KEEP_SCREEN_ON is disabled, since that
3028 // would allow bypassing of the maximum time to lock.
3029 Settings.Global.putInt(mContext.getContentResolver(),
3030 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
3033 policy.mLastMaximumTimeToLock = timeMs;
3034 mPowerManagerInternal.setMaximumScreenOffTimeoutFromDeviceAdmin((int)timeMs);
3036 Binder.restoreCallingIdentity(ident);
3041 public long getMaximumTimeToLock(ComponentName who, int userHandle) {
3045 enforceCrossUserPermission(userHandle);
3046 synchronized (this) {
3050 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3051 return admin != null ? admin.maximumTimeToUnlock : time;
3054 // Return strictest policy for this user and profiles that are visible from this user.
3055 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3056 for (UserInfo userInfo : profiles) {
3057 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
3058 final int N = policy.mAdminList.size();
3059 for (int i=0; i<N; i++) {
3060 ActiveAdmin admin = policy.mAdminList.get(i);
3062 time = admin.maximumTimeToUnlock;
3063 } else if (admin.maximumTimeToUnlock != 0
3064 && time > admin.maximumTimeToUnlock) {
3065 time = admin.maximumTimeToUnlock;
3074 public void lockNow() {
3078 synchronized (this) {
3079 // This API can only be called by an active device admin,
3080 // so try to retrieve it to check that the caller is one.
3081 getActiveAdminForCallerLocked(null,
3082 DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
3087 private void lockNowUnchecked() {
3088 long ident = Binder.clearCallingIdentity();
3090 // Power off the display
3091 mPowerManager.goToSleep(SystemClock.uptimeMillis(),
3092 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
3093 // Ensure the device is locked
3094 new LockPatternUtils(mContext).requireCredentialEntry(UserHandle.USER_ALL);
3095 getWindowManager().lockNow(null);
3096 } catch (RemoteException e) {
3098 Binder.restoreCallingIdentity(ident);
3102 private boolean isExtStorageEncrypted() {
3103 String state = SystemProperties.get("vold.decrypt");
3104 return !"".equals(state);
3108 public void enforceCanManageCaCerts(ComponentName who) {
3110 if (!isCallerDelegatedCertInstaller()) {
3111 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
3114 synchronized (this) {
3115 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3120 private boolean isCallerDelegatedCertInstaller() {
3121 final int callingUid = Binder.getCallingUid();
3122 final int userHandle = UserHandle.getUserId(callingUid);
3123 synchronized (this) {
3124 final DevicePolicyData policy = getUserData(userHandle);
3125 if (policy.mDelegatedCertInstallerPackage == null) {
3130 int uid = mContext.getPackageManager().getPackageUid(
3131 policy.mDelegatedCertInstallerPackage, userHandle);
3132 return uid == callingUid;
3133 } catch (NameNotFoundException e) {
3140 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
3141 enforceCanManageCaCerts(admin);
3145 X509Certificate cert = parseCert(certBuffer);
3146 pemCert = Credentials.convertToPem(cert);
3147 } catch (CertificateException ce) {
3148 Log.e(LOG_TAG, "Problem converting cert", ce);
3150 } catch (IOException ioe) {
3151 Log.e(LOG_TAG, "Problem reading cert", ioe);
3155 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3156 final long id = Binder.clearCallingIdentity();
3158 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
3160 keyChainConnection.getService().installCaCertificate(pemCert);
3162 } catch (RemoteException e) {
3163 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
3165 keyChainConnection.close();
3167 } catch (InterruptedException e1) {
3168 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
3169 Thread.currentThread().interrupt();
3171 Binder.restoreCallingIdentity(id);
3176 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
3177 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
3178 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
3183 public void uninstallCaCerts(ComponentName admin, String[] aliases) {
3184 enforceCanManageCaCerts(admin);
3186 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3187 final long id = Binder.clearCallingIdentity();
3189 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
3191 for (int i = 0 ; i < aliases.length; i++) {
3192 keyChainConnection.getService().deleteCaCertificate(aliases[i]);
3194 } catch (RemoteException e) {
3195 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
3197 keyChainConnection.close();
3199 } catch (InterruptedException ie) {
3200 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
3201 Thread.currentThread().interrupt();
3203 Binder.restoreCallingIdentity(id);
3208 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, String alias) {
3210 if (!isCallerDelegatedCertInstaller()) {
3211 throw new SecurityException("who == null, but caller is not cert installer");
3214 synchronized (this) {
3215 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3218 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3219 final long id = Binder.clearCallingIdentity();
3221 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
3223 IKeyChainService keyChain = keyChainConnection.getService();
3224 return keyChain.installKeyPair(privKey, cert, alias);
3225 } catch (RemoteException e) {
3226 Log.e(LOG_TAG, "Installing certificate", e);
3228 keyChainConnection.close();
3230 } catch (InterruptedException e) {
3231 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
3232 Thread.currentThread().interrupt();
3234 Binder.restoreCallingIdentity(id);
3240 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
3241 final IBinder response) {
3242 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
3243 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
3247 final UserHandle caller = Binder.getCallingUserHandle();
3248 // If there is a profile owner, redirect to that; otherwise query the device owner.
3249 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
3250 if (aliasChooser == null && caller.isOwner()) {
3251 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdmin();
3252 if (deviceOwnerAdmin != null) {
3253 aliasChooser = deviceOwnerAdmin.info.getComponent();
3256 if (aliasChooser == null) {
3257 sendPrivateKeyAliasResponse(null, response);
3261 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
3262 intent.setComponent(aliasChooser);
3263 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
3264 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
3265 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
3266 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
3268 final long id = Binder.clearCallingIdentity();
3270 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
3272 public void onReceive(Context context, Intent intent) {
3273 final String chosenAlias = getResultData();
3274 sendPrivateKeyAliasResponse(chosenAlias, response);
3276 }, null, Activity.RESULT_OK, null, null);
3278 Binder.restoreCallingIdentity(id);
3282 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
3283 final IKeyChainAliasCallback keyChainAliasResponse =
3284 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
3285 new AsyncTask<Void, Void, Void>() {
3287 protected Void doInBackground(Void... unused) {
3289 keyChainAliasResponse.alias(alias);
3290 } catch (Exception e) {
3291 // Catch everything (not just RemoteException): caller could throw a
3292 // RuntimeException back across processes.
3293 Log.e(LOG_TAG, "error while responding to callback", e);
3301 public void setCertInstallerPackage(ComponentName who, String installerPackage)
3302 throws SecurityException {
3303 int userHandle = UserHandle.getCallingUserId();
3304 synchronized (this) {
3305 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3306 DevicePolicyData policy = getUserData(userHandle);
3307 policy.mDelegatedCertInstallerPackage = installerPackage;
3308 saveSettingsLocked(userHandle);
3313 public String getCertInstallerPackage(ComponentName who) throws SecurityException {
3314 int userHandle = UserHandle.getCallingUserId();
3315 synchronized (this) {
3316 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3317 DevicePolicyData policy = getUserData(userHandle);
3318 return policy.mDelegatedCertInstallerPackage;
3322 private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
3323 if (wipeExtRequested) {
3324 StorageManager sm = (StorageManager) mContext.getSystemService(
3325 Context.STORAGE_SERVICE);
3326 sm.wipeAdoptableDisks();
3329 RecoverySystem.rebootWipeUserData(mContext, reason);
3330 } catch (IOException | SecurityException e) {
3331 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
3336 public void wipeData(int flags, final int userHandle) {
3340 enforceCrossUserPermission(userHandle);
3341 final String source;
3342 synchronized (this) {
3343 // This API can only be called by an active device admin,
3344 // so try to retrieve it to check that the caller is one.
3345 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
3346 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
3348 final ComponentName cname = admin.info.getComponent();
3349 if (cname != null) {
3350 source = cname.flattenToShortString();
3352 source = admin.info.getPackageName();
3355 long ident = Binder.clearCallingIdentity();
3357 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
3358 boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName())
3359 && !hasUserSetupCompleted(userHandle);
3360 if (userHandle != UserHandle.USER_OWNER
3361 || !(isDeviceOwner(admin.info.getPackageName())
3362 || ownsInitialization)) {
3363 throw new SecurityException(
3364 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
3366 PersistentDataBlockManager manager = (PersistentDataBlockManager)
3367 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
3368 if (manager != null) {
3373 Binder.restoreCallingIdentity(ident);
3376 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
3377 wipeDeviceNoLock(wipeExtRequested, userHandle,
3378 "DevicePolicyManager.wipeData() from " + source);
3381 private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
3382 long ident = Binder.clearCallingIdentity();
3384 if (userHandle == UserHandle.USER_OWNER) {
3385 wipeDataNoLock(wipeExtRequested, reason);
3387 mHandler.post(new Runnable() {
3391 IActivityManager am = ActivityManagerNative.getDefault();
3392 if (am.getCurrentUser().id == userHandle) {
3393 am.switchUser(UserHandle.USER_OWNER);
3396 boolean isManagedProfile = isManagedProfile(userHandle);
3397 if (!mUserManager.removeUser(userHandle)) {
3398 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
3399 } else if (isManagedProfile) {
3400 sendWipeProfileNotification();
3402 } catch (RemoteException re) {
3409 Binder.restoreCallingIdentity(ident);
3413 private void sendWipeProfileNotification() {
3414 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
3415 Notification notification = new Notification.Builder(mContext)
3416 .setSmallIcon(android.R.drawable.stat_sys_warning)
3417 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
3418 .setContentText(contentText)
3419 .setColor(mContext.getColor(R.color.system_notification_accent_color))
3420 .setStyle(new Notification.BigTextStyle().bigText(contentText))
3422 getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
3425 private void clearWipeProfileNotification() {
3426 getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
3430 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
3434 enforceCrossUserPermission(userHandle);
3435 mContext.enforceCallingOrSelfPermission(
3436 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3438 synchronized (this) {
3439 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
3440 if (admin == null) {
3442 result.sendResult(null);
3443 } catch (RemoteException e) {
3447 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
3448 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3449 intent.setComponent(admin.info.getComponent());
3450 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
3451 null, new BroadcastReceiver() {
3453 public void onReceive(Context context, Intent intent) {
3455 result.sendResult(getResultExtras(false));
3456 } catch (RemoteException e) {
3459 }, null, Activity.RESULT_OK, null, null);
3464 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
3465 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
3469 enforceCrossUserPermission(userHandle);
3470 enforceNotManagedProfile(userHandle, "set the active password");
3472 mContext.enforceCallingOrSelfPermission(
3473 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3474 DevicePolicyData p = getUserData(userHandle);
3476 validateQualityConstant(quality);
3478 synchronized (this) {
3479 if (p.mActivePasswordQuality != quality || p.mActivePasswordLength != length
3480 || p.mFailedPasswordAttempts != 0 || p.mActivePasswordLetters != letters
3481 || p.mActivePasswordUpperCase != uppercase
3482 || p.mActivePasswordLowerCase != lowercase
3483 || p.mActivePasswordNumeric != numbers
3484 || p.mActivePasswordSymbols != symbols
3485 || p.mActivePasswordNonLetter != nonletter) {
3486 long ident = Binder.clearCallingIdentity();
3488 p.mActivePasswordQuality = quality;
3489 p.mActivePasswordLength = length;
3490 p.mActivePasswordLetters = letters;
3491 p.mActivePasswordLowerCase = lowercase;
3492 p.mActivePasswordUpperCase = uppercase;
3493 p.mActivePasswordNumeric = numbers;
3494 p.mActivePasswordSymbols = symbols;
3495 p.mActivePasswordNonLetter = nonletter;
3496 p.mFailedPasswordAttempts = 0;
3497 saveSettingsLocked(userHandle);
3498 updatePasswordExpirationsLocked(userHandle);
3499 setExpirationAlarmCheckLocked(mContext, p);
3500 sendAdminCommandToSelfAndProfilesLocked(
3501 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
3502 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
3504 Binder.restoreCallingIdentity(ident);
3511 * Called any time the device password is updated. Resets all password expiration clocks.
3513 private void updatePasswordExpirationsLocked(int userHandle) {
3514 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3515 for (UserInfo userInfo : profiles) {
3516 int profileId = userInfo.id;
3517 DevicePolicyData policy = getUserDataUnchecked(profileId);
3518 final int N = policy.mAdminList.size();
3520 for (int i=0; i<N; i++) {
3521 ActiveAdmin admin = policy.mAdminList.get(i);
3522 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
3523 long timeout = admin.passwordExpirationTimeout;
3524 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3525 admin.passwordExpirationDate = expiration;
3529 saveSettingsLocked(profileId);
3534 public void reportFailedPasswordAttempt(int userHandle) {
3535 enforceCrossUserPermission(userHandle);
3536 enforceNotManagedProfile(userHandle, "report failed password attempt");
3537 mContext.enforceCallingOrSelfPermission(
3538 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3540 long ident = Binder.clearCallingIdentity();
3542 boolean wipeData = false;
3544 synchronized (this) {
3545 DevicePolicyData policy = getUserData(userHandle);
3546 policy.mFailedPasswordAttempts++;
3547 saveSettingsLocked(userHandle);
3549 ActiveAdmin strictestAdmin =
3550 getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
3551 int max = strictestAdmin != null
3552 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
3553 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
3554 // Wipe the user/profile associated with the policy that was violated. This
3555 // is not necessarily calling user: if the policy that fired was from a
3556 // managed profile rather than the main user profile, we wipe former only.
3558 identifier = strictestAdmin.getUserHandle().getIdentifier();
3560 sendAdminCommandToSelfAndProfilesLocked(
3561 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
3562 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3566 // Call without holding lock.
3567 wipeDeviceNoLock(false, identifier,
3568 "reportFailedPasswordAttempt()");
3571 Binder.restoreCallingIdentity(ident);
3576 public void reportSuccessfulPasswordAttempt(int userHandle) {
3577 enforceCrossUserPermission(userHandle);
3578 mContext.enforceCallingOrSelfPermission(
3579 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3581 synchronized (this) {
3582 DevicePolicyData policy = getUserData(userHandle);
3583 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
3584 long ident = Binder.clearCallingIdentity();
3586 policy.mFailedPasswordAttempts = 0;
3587 policy.mPasswordOwner = -1;
3588 saveSettingsLocked(userHandle);
3590 sendAdminCommandToSelfAndProfilesLocked(
3591 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
3592 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3595 Binder.restoreCallingIdentity(ident);
3602 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
3603 String exclusionList) {
3607 synchronized(this) {
3608 Preconditions.checkNotNull(who, "ComponentName is null");
3610 // Only check if owner has set global proxy. We don't allow other users to set it.
3611 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3612 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3613 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
3615 // Scan through active admins and find if anyone has already
3616 // set the global proxy.
3617 Set<ComponentName> compSet = policy.mAdminMap.keySet();
3618 for (ComponentName component : compSet) {
3619 ActiveAdmin ap = policy.mAdminMap.get(component);
3620 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
3621 // Another admin already sets the global proxy
3622 // Return it to the caller.
3627 // If the user is not the owner, don't set the global proxy. Fail silently.
3628 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3629 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
3630 + UserHandle.getCallingUserId() + " is not permitted.");
3633 if (proxySpec == null) {
3634 admin.specifiesGlobalProxy = false;
3635 admin.globalProxySpec = null;
3636 admin.globalProxyExclusionList = null;
3639 admin.specifiesGlobalProxy = true;
3640 admin.globalProxySpec = proxySpec;
3641 admin.globalProxyExclusionList = exclusionList;
3644 // Reset the global proxy accordingly
3645 // Do this using system permissions, as apps cannot write to secure settings
3646 long origId = Binder.clearCallingIdentity();
3648 resetGlobalProxyLocked(policy);
3650 Binder.restoreCallingIdentity(origId);
3657 public ComponentName getGlobalProxyAdmin(int userHandle) {
3661 enforceCrossUserPermission(userHandle);
3662 synchronized(this) {
3663 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3664 // Scan through active admins and find if anyone has already
3665 // set the global proxy.
3666 final int N = policy.mAdminList.size();
3667 for (int i = 0; i < N; i++) {
3668 ActiveAdmin ap = policy.mAdminList.get(i);
3669 if (ap.specifiesGlobalProxy) {
3670 // Device admin sets the global proxy
3671 // Return it to the caller.
3672 return ap.info.getComponent();
3676 // No device admin sets the global proxy.
3681 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
3682 synchronized (this) {
3683 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3685 long token = Binder.clearCallingIdentity();
3687 ConnectivityManager connectivityManager = (ConnectivityManager)
3688 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
3689 connectivityManager.setGlobalProxy(proxyInfo);
3691 Binder.restoreCallingIdentity(token);
3695 private void resetGlobalProxyLocked(DevicePolicyData policy) {
3696 final int N = policy.mAdminList.size();
3697 for (int i = 0; i < N; i++) {
3698 ActiveAdmin ap = policy.mAdminList.get(i);
3699 if (ap.specifiesGlobalProxy) {
3700 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
3704 // No device admins defining global proxies - reset global proxy settings to none
3705 saveGlobalProxyLocked(null, null);
3708 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
3709 if (exclusionList == null) {
3712 if (proxySpec == null) {
3715 // Remove white spaces
3716 proxySpec = proxySpec.trim();
3717 String data[] = proxySpec.split(":");
3718 int proxyPort = 8080;
3719 if (data.length > 1) {
3721 proxyPort = Integer.parseInt(data[1]);
3722 } catch (NumberFormatException e) {}
3724 exclusionList = exclusionList.trim();
3725 ContentResolver res = mContext.getContentResolver();
3727 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
3728 if (!proxyProperties.isValid()) {
3729 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
3732 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
3733 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
3734 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3739 * Set the storage encryption request for a single admin. Returns the new total request
3740 * status (for all admins).
3743 public int setStorageEncryption(ComponentName who, boolean encrypt) {
3745 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3747 Preconditions.checkNotNull(who, "ComponentName is null");
3748 final int userHandle = UserHandle.getCallingUserId();
3749 synchronized (this) {
3750 // Check for permissions
3751 // Only owner can set storage encryption
3752 if (userHandle != UserHandle.USER_OWNER
3753 || UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3754 Slog.w(LOG_TAG, "Only owner is allowed to set storage encryption. User "
3755 + UserHandle.getCallingUserId() + " is not permitted.");
3759 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3760 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
3762 // Quick exit: If the filesystem does not support encryption, we can exit early.
3763 if (!isEncryptionSupported()) {
3764 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3767 // (1) Record the value for the admin so it's sticky
3768 if (ap.encryptionRequested != encrypt) {
3769 ap.encryptionRequested = encrypt;
3770 saveSettingsLocked(userHandle);
3773 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3774 // (2) Compute "max" for all admins
3775 boolean newRequested = false;
3776 final int N = policy.mAdminList.size();
3777 for (int i = 0; i < N; i++) {
3778 newRequested |= policy.mAdminList.get(i).encryptionRequested;
3781 // Notify OS of new request
3782 setEncryptionRequested(newRequested);
3784 // Return the new global request status
3786 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3787 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3792 * Get the current storage encryption request status for a given admin, or aggregate of all
3796 public boolean getStorageEncryption(ComponentName who, int userHandle) {
3800 enforceCrossUserPermission(userHandle);
3801 synchronized (this) {
3802 // Check for permissions if a particular caller is specified
3804 // When checking for a single caller, status is based on caller's request
3805 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
3806 return ap != null ? ap.encryptionRequested : false;
3809 // If no particular caller is specified, return the aggregate set of requests.
3810 // This is short circuited by returning true on the first hit.
3811 DevicePolicyData policy = getUserData(userHandle);
3812 final int N = policy.mAdminList.size();
3813 for (int i = 0; i < N; i++) {
3814 if (policy.mAdminList.get(i).encryptionRequested) {
3823 * Get the current encryption status of the device.
3826 public int getStorageEncryptionStatus(int userHandle) {
3828 // Ok to return current status.
3830 enforceCrossUserPermission(userHandle);
3831 return getEncryptionStatus();
3835 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
3837 private boolean isEncryptionSupported() {
3838 // Note, this can be implemented as
3839 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3840 // But is provided as a separate internal method if there's a faster way to do a
3841 // simple check for supported-or-not.
3842 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3846 * Hook to low-levels: Reporting the current status of encryption.
3847 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
3848 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
3849 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, or
3850 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
3852 private int getEncryptionStatus() {
3853 String status = SystemProperties.get("ro.crypto.state", "unsupported");
3854 if ("encrypted".equalsIgnoreCase(status)) {
3855 final long token = Binder.clearCallingIdentity();
3857 return LockPatternUtils.isDeviceEncrypted()
3858 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3859 : DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
3861 Binder.restoreCallingIdentity(token);
3863 } else if ("unencrypted".equalsIgnoreCase(status)) {
3864 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3866 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3871 * Hook to low-levels: If needed, record the new admin setting for encryption.
3873 private void setEncryptionRequested(boolean encrypt) {
3878 * Set whether the screen capture is disabled for the user managed by the specified admin.
3881 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
3885 Preconditions.checkNotNull(who, "ComponentName is null");
3886 final int userHandle = UserHandle.getCallingUserId();
3887 synchronized (this) {
3888 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3889 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3890 if (ap.disableScreenCapture != disabled) {
3891 ap.disableScreenCapture = disabled;
3892 saveSettingsLocked(userHandle);
3893 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
3899 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
3900 * active admin (if given admin is null).
3903 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
3907 synchronized (this) {
3909 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3910 return (admin != null) ? admin.disableScreenCapture : false;
3913 DevicePolicyData policy = getUserData(userHandle);
3914 final int N = policy.mAdminList.size();
3915 for (int i = 0; i < N; i++) {
3916 ActiveAdmin admin = policy.mAdminList.get(i);
3917 if (admin.disableScreenCapture) {
3925 private void updateScreenCaptureDisabledInWindowManager(int userHandle, boolean disabled) {
3926 long ident = Binder.clearCallingIdentity();
3928 getWindowManager().setScreenCaptureDisabled(userHandle, disabled);
3929 } catch (RemoteException e) {
3930 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
3932 Binder.restoreCallingIdentity(ident);
3937 * Set whether auto time is required by the specified admin (must be device owner).
3940 public void setAutoTimeRequired(ComponentName who, boolean required) {
3944 Preconditions.checkNotNull(who, "ComponentName is null");
3945 final int userHandle = UserHandle.getCallingUserId();
3946 synchronized (this) {
3947 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3948 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3949 if (admin.requireAutoTime != required) {
3950 admin.requireAutoTime = required;
3951 saveSettingsLocked(userHandle);
3955 // Turn AUTO_TIME on in settings if it is required
3957 long ident = Binder.clearCallingIdentity();
3959 Settings.Global.putInt(mContext.getContentResolver(),
3960 Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
3962 Binder.restoreCallingIdentity(ident);
3968 * Returns whether or not auto time is required by the device owner.
3971 public boolean getAutoTimeRequired() {
3975 synchronized (this) {
3976 ActiveAdmin deviceOwner = getDeviceOwnerAdmin();
3977 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
3982 * The system property used to share the state of the camera. The native camera service
3983 * is expected to read this property and act accordingly. The userId should be appended
3986 public static final String SYSTEM_PROP_DISABLE_CAMERA_PREFIX = "sys.secpolicy.camera.off_";
3989 * Disables all device cameras according to the specified admin.
3992 public void setCameraDisabled(ComponentName who, boolean disabled) {
3996 Preconditions.checkNotNull(who, "ComponentName is null");
3997 final int userHandle = UserHandle.getCallingUserId();
3998 synchronized (this) {
3999 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4000 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
4001 if (ap.disableCamera != disabled) {
4002 ap.disableCamera = disabled;
4003 saveSettingsLocked(userHandle);
4005 syncDeviceCapabilitiesLocked(getUserData(userHandle));
4010 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
4014 public boolean getCameraDisabled(ComponentName who, int userHandle) {
4018 synchronized (this) {
4020 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4021 return (admin != null) ? admin.disableCamera : false;
4024 DevicePolicyData policy = getUserData(userHandle);
4025 // Determine whether or not the device camera is disabled for any active admins.
4026 final int N = policy.mAdminList.size();
4027 for (int i = 0; i < N; i++) {
4028 ActiveAdmin admin = policy.mAdminList.get(i);
4029 if (admin.disableCamera) {
4038 * Selectively disable keyguard features.
4041 public void setKeyguardDisabledFeatures(ComponentName who, int which) {
4045 Preconditions.checkNotNull(who, "ComponentName is null");
4046 final int userHandle = UserHandle.getCallingUserId();
4047 if (isManagedProfile(userHandle)) {
4048 which = which & PROFILE_KEYGUARD_FEATURES;
4050 synchronized (this) {
4051 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4052 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
4053 if (ap.disabledKeyguardFeatures != which) {
4054 ap.disabledKeyguardFeatures = which;
4055 saveSettingsLocked(userHandle);
4057 syncDeviceCapabilitiesLocked(getUserData(userHandle));
4062 * Gets the disabled state for features in keyguard for the given admin,
4063 * or the aggregate of all active admins if who is null.
4066 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle) {
4070 enforceCrossUserPermission(userHandle);
4071 long ident = Binder.clearCallingIdentity();
4073 synchronized (this) {
4075 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4076 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
4079 UserInfo user = mUserManager.getUserInfo(userHandle);
4080 final List<UserInfo> profiles;
4081 if (user.isManagedProfile()) {
4082 // If we are being asked about a managed profile just return
4083 // keyguard features disabled by admins in the profile.
4084 profiles = new ArrayList<UserInfo>(1);
4087 // Otherwise return those set by admins in the user
4088 // and its profiles.
4089 profiles = mUserManager.getProfiles(userHandle);
4092 // Determine which keyguard features are disabled by any active admin.
4094 for (UserInfo userInfo : profiles) {
4095 DevicePolicyData policy = getUserData(userInfo.id);
4096 final int N = policy.mAdminList.size();
4097 for (int i = 0; i < N; i++) {
4098 ActiveAdmin admin = policy.mAdminList.get(i);
4099 if (userInfo.id == userHandle || !userInfo.isManagedProfile()) {
4100 // If we are being asked explictly about this user
4101 // return all disabled features even if its a managed profile.
4102 which |= admin.disabledKeyguardFeatures;
4104 // Otherwise a managed profile is only allowed to disable
4105 // some features on the parent user.
4106 which |= (admin.disabledKeyguardFeatures
4107 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
4114 Binder.restoreCallingIdentity(ident);
4119 public boolean setDeviceOwner(String packageName, String ownerName) {
4123 if (packageName == null
4124 || !DeviceOwner.isInstalled(packageName, mContext.getPackageManager())) {
4125 throw new IllegalArgumentException("Invalid package name " + packageName
4126 + " for device owner");
4128 synchronized (this) {
4129 enforceCanSetDeviceOwner();
4131 // Shutting down backup manager service permanently.
4132 long ident = Binder.clearCallingIdentity();
4134 IBackupManager ibm = IBackupManager.Stub.asInterface(
4135 ServiceManager.getService(Context.BACKUP_SERVICE));
4136 ibm.setBackupServiceActive(UserHandle.USER_OWNER, false);
4137 } catch (RemoteException e) {
4138 throw new IllegalStateException("Failed deactivating backup service.", e);
4140 Binder.restoreCallingIdentity(ident);
4143 if (mDeviceOwner == null) {
4144 // Device owner is not set and does not exist, set it.
4145 mDeviceOwner = DeviceOwner.createWithDeviceOwner(packageName, ownerName);
4147 // Device owner state already exists, update it.
4148 mDeviceOwner.setDeviceOwner(packageName, ownerName);
4150 mDeviceOwner.writeOwnerFile();
4151 updateDeviceOwnerLocked();
4152 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
4154 ident = Binder.clearCallingIdentity();
4156 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
4158 Binder.restoreCallingIdentity(ident);
4165 public boolean isDeviceOwner(String packageName) {
4169 synchronized (this) {
4170 return mDeviceOwner != null
4171 && mDeviceOwner.hasDeviceOwner()
4172 && mDeviceOwner.getDeviceOwnerPackageName().equals(packageName);
4177 public String getDeviceOwner() {
4181 synchronized (this) {
4182 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
4183 return mDeviceOwner.getDeviceOwnerPackageName();
4190 public String getDeviceOwnerName() {
4194 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
4195 synchronized (this) {
4196 if (mDeviceOwner == null || !mDeviceOwner.hasDeviceOwner()) {
4199 String deviceOwnerPackage = mDeviceOwner.getDeviceOwnerPackageName();
4200 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_OWNER);
4204 // Returns the active device owner or null if there is no device owner.
4205 private ActiveAdmin getDeviceOwnerAdmin() {
4206 String deviceOwnerPackageName = getDeviceOwner();
4207 if (deviceOwnerPackageName == null) {
4211 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
4212 final int n = policy.mAdminList.size();
4213 for (int i = 0; i < n; i++) {
4214 ActiveAdmin admin = policy.mAdminList.get(i);
4215 if (deviceOwnerPackageName.equals(admin.info.getPackageName())) {
4223 public void clearDeviceOwner(String packageName) {
4224 Preconditions.checkNotNull(packageName, "packageName is null");
4226 int uid = mContext.getPackageManager().getPackageUid(packageName, 0);
4227 if (uid != Binder.getCallingUid()) {
4228 throw new SecurityException("Invalid packageName");
4230 } catch (NameNotFoundException e) {
4231 throw new SecurityException(e);
4233 if (!isDeviceOwner(packageName)) {
4234 throw new SecurityException("clearDeviceOwner can only be called by the device owner");
4236 synchronized (this) {
4237 clearUserPoliciesLocked(new UserHandle(UserHandle.USER_OWNER));
4238 if (mDeviceOwner != null) {
4239 mDeviceOwner.clearDeviceOwner();
4240 mDeviceOwner.writeOwnerFile();
4241 updateDeviceOwnerLocked();
4247 public boolean setDeviceInitializer(ComponentName who, ComponentName initializer) {
4251 if (initializer == null || !DeviceOwner.isInstalled(
4252 initializer.getPackageName(), mContext.getPackageManager())) {
4253 throw new IllegalArgumentException("Invalid component name " + initializer
4254 + " for device initializer");
4256 boolean isInitializerSystemApp;
4258 isInitializerSystemApp = isSystemApp(AppGlobals.getPackageManager(),
4259 initializer.getPackageName(), Binder.getCallingUserHandle().getIdentifier());
4260 } catch (RemoteException | IllegalArgumentException e) {
4261 isInitializerSystemApp = false;
4262 Slog.e(LOG_TAG, "Fail to check if device initialzer is system app.", e);
4264 if (!isInitializerSystemApp) {
4265 throw new IllegalArgumentException("Only system app can be set as device initializer.");
4267 synchronized (this) {
4268 enforceCanSetDeviceInitializer(who);
4270 if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4271 throw new IllegalStateException(
4272 "Trying to set device initializer but device initializer is already set.");
4275 if (mDeviceOwner == null) {
4276 // Device owner state does not exist, create it.
4277 mDeviceOwner = DeviceOwner.createWithDeviceInitializer(initializer);
4279 // Device owner already exists, update it.
4280 mDeviceOwner.setDeviceInitializer(initializer);
4283 addDeviceInitializerToLockTaskPackagesLocked(UserHandle.USER_OWNER);
4284 mDeviceOwner.writeOwnerFile();
4289 private void enforceCanSetDeviceInitializer(ComponentName who) {
4291 mContext.enforceCallingOrSelfPermission(
4292 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
4293 if (hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4294 throw new IllegalStateException(
4295 "Trying to set device initializer but device is already provisioned.");
4298 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4303 public boolean isDeviceInitializer(String packageName) {
4307 synchronized (this) {
4308 return mDeviceOwner != null
4309 && mDeviceOwner.hasDeviceInitializer()
4310 && mDeviceOwner.getDeviceInitializerPackageName().equals(packageName);
4315 public String getDeviceInitializer() {
4319 synchronized (this) {
4320 if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4321 return mDeviceOwner.getDeviceInitializerPackageName();
4328 public ComponentName getDeviceInitializerComponent() {
4332 synchronized (this) {
4333 if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4334 return mDeviceOwner.getDeviceInitializerComponent();
4341 public void clearDeviceInitializer(ComponentName who) {
4345 Preconditions.checkNotNull(who, "ComponentName is null");
4347 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, UserHandle.getCallingUserId());
4349 if (admin.getUid() != Binder.getCallingUid()) {
4350 throw new SecurityException("Admin " + who + " is not owned by uid "
4351 + Binder.getCallingUid());
4354 if (!isDeviceInitializer(admin.info.getPackageName())
4355 && !isDeviceOwner(admin.info.getPackageName())) {
4356 throw new SecurityException(
4357 "clearDeviceInitializer can only be called by the device initializer/owner");
4359 synchronized (this) {
4360 long ident = Binder.clearCallingIdentity();
4362 if (mDeviceOwner != null) {
4363 mDeviceOwner.clearDeviceInitializer();
4364 mDeviceOwner.writeOwnerFile();
4367 Binder.restoreCallingIdentity(ident);
4373 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
4378 || !DeviceOwner.isInstalledForUser(who.getPackageName(), userHandle)) {
4379 throw new IllegalArgumentException("Component " + who
4380 + " not installed for userId:" + userHandle);
4382 synchronized (this) {
4383 enforceCanSetProfileOwner(userHandle);
4384 if (mDeviceOwner == null) {
4385 // Device owner state does not exist, create it.
4386 mDeviceOwner = DeviceOwner.createWithProfileOwner(who, ownerName,
4389 // Device owner state already exists, update it.
4390 mDeviceOwner.setProfileOwner(who, ownerName, userHandle);
4392 mDeviceOwner.writeOwnerFile();
4398 public void clearProfileOwner(ComponentName who) {
4402 UserHandle callingUser = Binder.getCallingUserHandle();
4403 // Check if this is the profile owner who is calling
4404 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4405 synchronized (this) {
4406 clearUserPoliciesLocked(callingUser);
4407 if (mDeviceOwner != null) {
4408 mDeviceOwner.removeProfileOwner(callingUser.getIdentifier());
4409 mDeviceOwner.writeOwnerFile();
4414 private void clearUserPoliciesLocked(UserHandle userHandle) {
4415 int userId = userHandle.getIdentifier();
4416 // Reset some of the user-specific policies
4417 DevicePolicyData policy = getUserData(userId);
4418 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
4419 policy.mDelegatedCertInstallerPackage = null;
4420 policy.mStatusBarDisabled = false;
4421 saveSettingsLocked(userId);
4423 final long ident = Binder.clearCallingIdentity();
4425 clearUserRestrictions(userHandle);
4426 AppGlobals.getPackageManager().updatePermissionFlagsForAllApps(
4427 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
4428 0 /* flagValues */, userHandle.getIdentifier());
4429 } catch (RemoteException re) {
4431 Binder.restoreCallingIdentity(ident);
4436 private void clearUserRestrictions(UserHandle userHandle) {
4437 Bundle userRestrictions = mUserManager.getUserRestrictions();
4438 mUserManager.setUserRestrictions(new Bundle(), userHandle);
4439 IAudioService iAudioService = IAudioService.Stub.asInterface(
4440 ServiceManager.getService(Context.AUDIO_SERVICE));
4441 if (userRestrictions.getBoolean(UserManager.DISALLOW_ADJUST_VOLUME)) {
4443 iAudioService.setMasterMute(true, 0, mContext.getPackageName(),
4444 userHandle.getIdentifier());
4445 } catch (RemoteException e) {
4446 // Not much we can do here.
4449 if (userRestrictions.getBoolean(UserManager.DISALLOW_UNMUTE_MICROPHONE)) {
4451 iAudioService.setMicrophoneMute(true, mContext.getPackageName(),
4452 userHandle.getIdentifier());
4453 } catch (RemoteException e) {
4454 // Not much we can do here.
4460 public boolean hasUserSetupCompleted() {
4461 return hasUserSetupCompleted(UserHandle.getCallingUserId());
4464 private boolean hasUserSetupCompleted(int userHandle) {
4468 DevicePolicyData policy = getUserData(userHandle);
4469 // If policy is null, return true, else check if the setup has completed.
4470 return policy == null || policy.mUserSetupComplete;
4474 public boolean setUserEnabled(ComponentName who) {
4478 synchronized (this) {
4480 throw new NullPointerException("ComponentName is null");
4482 int userId = UserHandle.getCallingUserId();
4484 ActiveAdmin activeAdmin =
4485 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4486 if (!isDeviceInitializer(activeAdmin.info.getPackageName())) {
4487 throw new SecurityException(
4488 "This method can only be called by device initializers");
4491 long id = Binder.clearCallingIdentity();
4493 if (!isDeviceOwner(activeAdmin.info.getPackageName())) {
4494 IPackageManager ipm = AppGlobals.getPackageManager();
4495 ipm.setComponentEnabledSetting(who,
4496 PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
4497 PackageManager.DONT_KILL_APP, userId);
4499 removeActiveAdmin(who, userId);
4502 if (userId == UserHandle.USER_OWNER) {
4503 Settings.Global.putInt(mContext.getContentResolver(),
4504 Settings.Global.DEVICE_PROVISIONED, 1);
4506 Settings.Secure.putIntForUser(mContext.getContentResolver(),
4507 Settings.Secure.USER_SETUP_COMPLETE, 1, userId);
4508 } catch (RemoteException e) {
4509 Log.i(LOG_TAG, "Can't talk to package manager", e);
4512 restoreCallingIdentity(id);
4519 public void setProfileEnabled(ComponentName who) {
4523 Preconditions.checkNotNull(who, "ComponentName is null");
4524 final int userHandle = UserHandle.getCallingUserId();
4525 synchronized (this) {
4526 // Check if this is the profile owner who is calling
4527 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4528 int userId = UserHandle.getCallingUserId();
4530 long id = Binder.clearCallingIdentity();
4532 mUserManager.setUserEnabled(userId);
4533 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
4534 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle));
4535 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
4536 Intent.FLAG_RECEIVER_FOREGROUND);
4537 // TODO This should send to parent of profile (which is always owner at the moment).
4538 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
4540 restoreCallingIdentity(id);
4546 public void setProfileName(ComponentName who, String profileName) {
4547 Preconditions.checkNotNull(who, "ComponentName is null");
4548 int userId = UserHandle.getCallingUserId();
4549 // Check if this is the profile owner (includes device owner).
4550 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4552 long id = Binder.clearCallingIdentity();
4554 mUserManager.setUserName(userId, profileName);
4556 restoreCallingIdentity(id);
4561 public ComponentName getProfileOwner(int userHandle) {
4566 synchronized (this) {
4567 if (mDeviceOwner != null) {
4568 return mDeviceOwner.getProfileOwnerComponent(userHandle);
4574 // Returns the active profile owner for this user or null if the current user has no
4576 private ActiveAdmin getProfileOwnerAdmin(int userHandle) {
4577 ComponentName profileOwner =
4578 mDeviceOwner != null ? mDeviceOwner.getProfileOwnerComponent(userHandle) : null;
4579 if (profileOwner == null) {
4582 DevicePolicyData policy = getUserData(userHandle);
4583 final int n = policy.mAdminList.size();
4584 for (int i = 0; i < n; i++) {
4585 ActiveAdmin admin = policy.mAdminList.get(i);
4586 if (profileOwner.equals(admin.info.getComponent())) {
4594 public String getProfileOwnerName(int userHandle) {
4598 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
4599 ComponentName profileOwner = getProfileOwner(userHandle);
4600 if (profileOwner == null) {
4603 return getApplicationLabel(profileOwner.getPackageName(), userHandle);
4607 * Canonical name for a given package.
4609 private String getApplicationLabel(String packageName, int userHandle) {
4610 long token = Binder.clearCallingIdentity();
4612 final Context userContext;
4614 UserHandle handle = new UserHandle(userHandle);
4615 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
4616 } catch (PackageManager.NameNotFoundException nnfe) {
4617 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
4620 ApplicationInfo appInfo = userContext.getApplicationInfo();
4621 CharSequence result = null;
4622 if (appInfo != null) {
4623 PackageManager pm = userContext.getPackageManager();
4624 result = pm.getApplicationLabel(appInfo);
4626 return result != null ? result.toString() : null;
4628 Binder.restoreCallingIdentity(token);
4633 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
4635 * The profile owner can only be set before the user setup phase has completed,
4638 * - adb if there are not accounts.
4640 private void enforceCanSetProfileOwner(int userHandle) {
4641 UserInfo info = mUserManager.getUserInfo(userHandle);
4643 // User doesn't exist.
4644 throw new IllegalArgumentException(
4645 "Attempted to set profile owner for invalid userId: " + userHandle);
4647 if (info.isGuest()) {
4648 throw new IllegalStateException("Cannot set a profile owner on a guest");
4650 if (getProfileOwner(userHandle) != null) {
4651 throw new IllegalStateException("Trying to set the profile owner, but profile owner "
4652 + "is already set.");
4654 int callingUid = Binder.getCallingUid();
4655 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
4656 if (hasUserSetupCompleted(userHandle) &&
4657 AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) {
4658 throw new IllegalStateException("Not allowed to set the profile owner because "
4659 + "there are already some accounts on the profile");
4663 mContext.enforceCallingOrSelfPermission(
4664 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
4665 if (hasUserSetupCompleted(userHandle)
4666 && UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
4667 throw new IllegalStateException("Cannot set the profile owner on a user which is "
4668 + "already set-up");
4673 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
4675 * The device owner can only be set before the setup phase of the primary user has completed,
4676 * except for adb if no accounts or additional users are present on the device.
4678 private void enforceCanSetDeviceOwner() {
4679 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
4680 throw new IllegalStateException("Trying to set the device owner, but device owner "
4681 + "is already set.");
4683 int callingUid = Binder.getCallingUid();
4684 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
4685 if (!hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4688 if (mUserManager.getUserCount() > 1) {
4689 throw new IllegalStateException("Not allowed to set the device owner because there "
4690 + "are already several users on the device");
4692 if (AccountManager.get(mContext).getAccounts().length > 0) {
4693 throw new IllegalStateException("Not allowed to set the device owner because there "
4694 + "are already some accounts on the device");
4698 mContext.enforceCallingOrSelfPermission(
4699 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
4700 if (hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4701 throw new IllegalStateException("Cannot set the device owner if the device is "
4702 + "already set-up");
4706 private void enforceCrossUserPermission(int userHandle) {
4707 if (userHandle < 0) {
4708 throw new IllegalArgumentException("Invalid userId " + userHandle);
4710 final int callingUid = Binder.getCallingUid();
4711 if (userHandle == UserHandle.getUserId(callingUid)) return;
4712 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4713 mContext.enforceCallingOrSelfPermission(
4714 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have"
4715 + " INTERACT_ACROSS_USERS_FULL permission");
4719 private void enforceSystemProcess(String message) {
4720 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4721 throw new SecurityException(message);
4725 private void enforceNotManagedProfile(int userHandle, String message) {
4726 if(isManagedProfile(userHandle)) {
4727 throw new SecurityException("You can not " + message + " for a managed profile. ");
4731 private UserInfo getProfileParent(int userHandle) {
4732 long ident = Binder.clearCallingIdentity();
4734 return mUserManager.getProfileParent(userHandle);
4736 Binder.restoreCallingIdentity(ident);
4740 private boolean isManagedProfile(int userHandle) {
4741 long ident = Binder.clearCallingIdentity();
4743 return mUserManager.getUserInfo(userHandle).isManagedProfile();
4745 Binder.restoreCallingIdentity(ident);
4749 private void enableIfNecessary(String packageName, int userId) {
4751 IPackageManager ipm = AppGlobals.getPackageManager();
4752 ApplicationInfo ai = ipm.getApplicationInfo(packageName,
4753 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
4755 if (ai.enabledSetting
4756 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
4757 ipm.setApplicationEnabledSetting(packageName,
4758 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
4759 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
4761 } catch (RemoteException e) {
4766 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4767 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4768 != PackageManager.PERMISSION_GRANTED) {
4770 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
4771 + Binder.getCallingPid()
4772 + ", uid=" + Binder.getCallingUid());
4776 final Printer p = new PrintWriterPrinter(pw);
4778 synchronized (this) {
4779 p.println("Current Device Policy Manager state:");
4780 if (mDeviceOwner != null) {
4781 mDeviceOwner.dump(" ", pw);
4783 int userCount = mUserData.size();
4784 for (int u = 0; u < userCount; u++) {
4785 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
4786 p.println(" Enabled Device Admins (User " + policy.mUserHandle + "):");
4787 final int N = policy.mAdminList.size();
4788 for (int i=0; i<N; i++) {
4789 ActiveAdmin ap = policy.mAdminList.get(i);
4791 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
4796 if (!policy.mRemovingAdmins.isEmpty()) {
4797 p.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
4798 + policy.mRemovingAdmins);
4802 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
4808 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
4809 ComponentName activity) {
4810 Preconditions.checkNotNull(who, "ComponentName is null");
4811 final int userHandle = UserHandle.getCallingUserId();
4812 synchronized (this) {
4813 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4815 IPackageManager pm = AppGlobals.getPackageManager();
4816 long id = Binder.clearCallingIdentity();
4818 pm.addPersistentPreferredActivity(filter, activity, userHandle);
4819 } catch (RemoteException re) {
4822 restoreCallingIdentity(id);
4828 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
4829 Preconditions.checkNotNull(who, "ComponentName is null");
4830 final int userHandle = UserHandle.getCallingUserId();
4831 synchronized (this) {
4832 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4834 IPackageManager pm = AppGlobals.getPackageManager();
4835 long id = Binder.clearCallingIdentity();
4837 pm.clearPackagePersistentPreferredActivities(packageName, userHandle);
4838 } catch (RemoteException re) {
4841 restoreCallingIdentity(id);
4847 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
4848 Preconditions.checkNotNull(who, "ComponentName is null");
4849 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4850 synchronized (this) {
4851 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4853 long id = Binder.clearCallingIdentity();
4855 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
4857 restoreCallingIdentity(id);
4863 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
4864 PersistableBundle args) {
4868 Preconditions.checkNotNull(admin, "admin is null");
4869 Preconditions.checkNotNull(agent, "agent is null");
4870 final int userHandle = UserHandle.getCallingUserId();
4871 enforceNotManagedProfile(userHandle, "set trust agent configuration");
4872 synchronized (this) {
4873 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
4874 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
4875 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
4876 saveSettingsLocked(userHandle);
4877 syncDeviceCapabilitiesLocked(getUserData(userHandle));
4882 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
4883 ComponentName agent, int userHandle) {
4887 Preconditions.checkNotNull(agent, "agent null");
4888 enforceCrossUserPermission(userHandle);
4890 synchronized (this) {
4891 final String componentName = agent.flattenToString();
4892 if (admin != null) {
4893 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle);
4894 if (ap == null) return null;
4895 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
4896 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
4897 List<PersistableBundle> result = new ArrayList<PersistableBundle>();
4898 result.add(trustAgentInfo.options);
4902 // Return strictest policy for this user and profiles that are visible from this user.
4903 final List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
4904 List<PersistableBundle> result = null;
4906 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
4907 // of the options. If any admin doesn't have options, discard options for the rest
4909 boolean allAdminsHaveOptions = true;
4910 for (UserInfo userInfo : profiles) {
4911 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4912 final int N = policy.mAdminList.size();
4913 for (int i=0; i < N; i++) {
4914 final ActiveAdmin active = policy.mAdminList.get(i);
4915 final boolean disablesTrust = (active.disabledKeyguardFeatures
4916 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
4917 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
4918 if (info != null && info.options != null && !info.options.isEmpty()) {
4919 if (disablesTrust) {
4920 if (result == null) {
4921 result = new ArrayList<PersistableBundle>();
4923 result.add(info.options);
4925 Log.w(LOG_TAG, "Ignoring admin " + active.info
4926 + " because it has trust options but doesn't declare "
4927 + "KEYGUARD_DISABLE_TRUST_AGENTS");
4929 } else if (disablesTrust) {
4930 allAdminsHaveOptions = false;
4935 return allAdminsHaveOptions ? result : null;
4940 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
4941 Preconditions.checkNotNull(who, "ComponentName is null");
4942 synchronized (this) {
4943 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4945 int userHandle = UserHandle.getCallingUserId();
4946 DevicePolicyData userData = getUserData(userHandle);
4947 userData.mRestrictionsProvider = permissionProvider;
4948 saveSettingsLocked(userHandle);
4953 public ComponentName getRestrictionsProvider(int userHandle) {
4954 synchronized (this) {
4955 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4956 throw new SecurityException("Only the system can query the permission provider");
4958 DevicePolicyData userData = getUserData(userHandle);
4959 return userData != null ? userData.mRestrictionsProvider : null;
4964 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
4965 Preconditions.checkNotNull(who, "ComponentName is null");
4966 int callingUserId = UserHandle.getCallingUserId();
4967 synchronized (this) {
4968 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4970 IPackageManager pm = AppGlobals.getPackageManager();
4971 long id = Binder.clearCallingIdentity();
4973 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
4974 pm.addCrossProfileIntentFilter(filter, who.getPackageName(), callingUserId,
4975 UserHandle.USER_OWNER, 0);
4977 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
4978 pm.addCrossProfileIntentFilter(filter, who.getPackageName(),
4979 UserHandle.USER_OWNER, callingUserId, 0);
4981 } catch (RemoteException re) {
4984 restoreCallingIdentity(id);
4990 public void clearCrossProfileIntentFilters(ComponentName who) {
4991 Preconditions.checkNotNull(who, "ComponentName is null");
4992 int callingUserId = UserHandle.getCallingUserId();
4993 synchronized (this) {
4994 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4995 IPackageManager pm = AppGlobals.getPackageManager();
4996 long id = Binder.clearCallingIdentity();
4998 // Removing those that go from the managed profile to the primary user.
4999 pm.clearCrossProfileIntentFilters(callingUserId, who.getPackageName());
5000 // And those that go from the primary user to the managed profile.
5001 // If we want to support multiple managed profiles, we will have to only remove
5002 // those that have callingUserId as their target.
5003 pm.clearCrossProfileIntentFilters(UserHandle.USER_OWNER, who.getPackageName());
5004 } catch (RemoteException re) {
5007 restoreCallingIdentity(id);
5013 * @return true if all packages in enabledPackages are either in the list
5014 * permittedList or are a system app.
5016 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
5017 List<String> permittedList) {
5018 int userIdToCheck = UserHandle.getCallingUserId();
5019 long id = Binder.clearCallingIdentity();
5021 // If we have an enabled packages list for a managed profile the packages
5022 // we should check are installed for the parent user.
5023 UserInfo user = mUserManager.getUserInfo(userIdToCheck);
5024 if (user.isManagedProfile()) {
5025 userIdToCheck = user.profileGroupId;
5028 IPackageManager pm = AppGlobals.getPackageManager();
5029 for (String enabledPackage : enabledPackages) {
5030 boolean systemService = false;
5032 ApplicationInfo applicationInfo = pm.getApplicationInfo(enabledPackage,
5033 PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
5034 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5035 } catch (RemoteException e) {
5036 Log.i(LOG_TAG, "Can't talk to package managed", e);
5038 if (!systemService && !permittedList.contains(enabledPackage)) {
5043 restoreCallingIdentity(id);
5048 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
5049 // Not using AccessibilityManager.getInstance because that guesses
5050 // at the user you require based on callingUid and caches for a given
5052 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
5053 IAccessibilityManager service = iBinder == null
5054 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
5055 return new AccessibilityManager(mContext, service, userId);
5059 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
5063 Preconditions.checkNotNull(who, "ComponentName is null");
5065 if (packageList != null) {
5066 int userId = UserHandle.getCallingUserId();
5067 List<AccessibilityServiceInfo> enabledServices = null;
5068 long id = Binder.clearCallingIdentity();
5070 UserInfo user = mUserManager.getUserInfo(userId);
5071 if (user.isManagedProfile()) {
5072 userId = user.profileGroupId;
5074 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
5075 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
5076 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
5078 restoreCallingIdentity(id);
5081 if (enabledServices != null) {
5082 List<String> enabledPackages = new ArrayList<String>();
5083 for (AccessibilityServiceInfo service : enabledServices) {
5084 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
5086 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
5087 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
5088 + "because it contains already enabled accesibility services.");
5094 synchronized (this) {
5095 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5096 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5097 admin.permittedAccessiblityServices = packageList;
5098 saveSettingsLocked(UserHandle.getCallingUserId());
5104 public List getPermittedAccessibilityServices(ComponentName who) {
5108 Preconditions.checkNotNull(who, "ComponentName is null");
5110 synchronized (this) {
5111 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5112 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5113 return admin.permittedAccessiblityServices;
5118 public List getPermittedAccessibilityServicesForUser(int userId) {
5122 synchronized (this) {
5123 List<String> result = null;
5124 // If we have multiple profiles we return the intersection of the
5125 // permitted lists. This can happen in cases where we have a device
5126 // and profile owner.
5127 List<UserInfo> profiles = mUserManager.getProfiles(userId);
5128 final int PROFILES_SIZE = profiles.size();
5129 for (int i = 0; i < PROFILES_SIZE; ++i) {
5130 // Just loop though all admins, only device or profiles
5131 // owners can have permitted lists set.
5132 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
5133 final int N = policy.mAdminList.size();
5134 for (int j = 0; j < N; j++) {
5135 ActiveAdmin admin = policy.mAdminList.get(j);
5136 List<String> fromAdmin = admin.permittedAccessiblityServices;
5137 if (fromAdmin != null) {
5138 if (result == null) {
5139 result = new ArrayList<String>(fromAdmin);
5141 result.retainAll(fromAdmin);
5147 // If we have a permitted list add all system accessibility services.
5148 if (result != null) {
5149 long id = Binder.clearCallingIdentity();
5151 UserInfo user = mUserManager.getUserInfo(userId);
5152 if (user.isManagedProfile()) {
5153 userId = user.profileGroupId;
5155 AccessibilityManager accessibilityManager =
5156 getAccessibilityManagerForUser(userId);
5157 List<AccessibilityServiceInfo> installedServices =
5158 accessibilityManager.getInstalledAccessibilityServiceList();
5160 IPackageManager pm = AppGlobals.getPackageManager();
5161 if (installedServices != null) {
5162 for (AccessibilityServiceInfo service : installedServices) {
5163 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
5164 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
5165 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5166 result.add(serviceInfo.packageName);
5171 restoreCallingIdentity(id);
5179 private boolean checkCallerIsCurrentUserOrProfile() {
5180 int callingUserId = UserHandle.getCallingUserId();
5181 long token = Binder.clearCallingIdentity();
5183 UserInfo currentUser;
5184 UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
5186 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
5187 } catch (RemoteException e) {
5188 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
5192 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
5193 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
5194 + "of a user that isn't the foreground user.");
5197 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
5198 Slog.e(LOG_TAG, "Cannot set permitted input methods "
5199 + "of a user that isn't the foreground user.");
5203 Binder.restoreCallingIdentity(token);
5209 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
5213 Preconditions.checkNotNull(who, "ComponentName is null");
5215 // TODO When InputMethodManager supports per user calls remove
5216 // this restriction.
5217 if (!checkCallerIsCurrentUserOrProfile()) {
5221 if (packageList != null) {
5222 // InputMethodManager fetches input methods for current user.
5223 // So this can only be set when calling user is the current user
5224 // or parent is current user in case of managed profiles.
5225 InputMethodManager inputMethodManager = (InputMethodManager) mContext
5226 .getSystemService(Context.INPUT_METHOD_SERVICE);
5227 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
5229 if (enabledImes != null) {
5230 List<String> enabledPackages = new ArrayList<String>();
5231 for (InputMethodInfo ime : enabledImes) {
5232 enabledPackages.add(ime.getPackageName());
5234 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
5235 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
5236 + "because it contains already enabled input method.");
5242 synchronized (this) {
5243 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5244 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5245 admin.permittedInputMethods = packageList;
5246 saveSettingsLocked(UserHandle.getCallingUserId());
5252 public List getPermittedInputMethods(ComponentName who) {
5256 Preconditions.checkNotNull(who, "ComponentName is null");
5258 synchronized (this) {
5259 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5260 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5261 return admin.permittedInputMethods;
5266 public List getPermittedInputMethodsForCurrentUser() {
5267 UserInfo currentUser;
5269 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
5270 } catch (RemoteException e) {
5271 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
5272 // Activity managed is dead, just allow all IMEs
5276 int userId = currentUser.id;
5277 synchronized (this) {
5278 List<String> result = null;
5279 // If we have multiple profiles we return the intersection of the
5280 // permitted lists. This can happen in cases where we have a device
5281 // and profile owner.
5282 List<UserInfo> profiles = mUserManager.getProfiles(userId);
5283 final int PROFILES_SIZE = profiles.size();
5284 for (int i = 0; i < PROFILES_SIZE; ++i) {
5285 // Just loop though all admins, only device or profiles
5286 // owners can have permitted lists set.
5287 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
5288 final int N = policy.mAdminList.size();
5289 for (int j = 0; j < N; j++) {
5290 ActiveAdmin admin = policy.mAdminList.get(j);
5291 List<String> fromAdmin = admin.permittedInputMethods;
5292 if (fromAdmin != null) {
5293 if (result == null) {
5294 result = new ArrayList<String>(fromAdmin);
5296 result.retainAll(fromAdmin);
5302 // If we have a permitted list add all system input methods.
5303 if (result != null) {
5304 InputMethodManager inputMethodManager = (InputMethodManager) mContext
5305 .getSystemService(Context.INPUT_METHOD_SERVICE);
5306 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
5307 long id = Binder.clearCallingIdentity();
5309 IPackageManager pm = AppGlobals.getPackageManager();
5311 for (InputMethodInfo ime : imes) {
5312 ServiceInfo serviceInfo = ime.getServiceInfo();
5313 ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
5314 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5315 result.add(serviceInfo.packageName);
5320 restoreCallingIdentity(id);
5328 public UserHandle createUser(ComponentName who, String name) {
5329 Preconditions.checkNotNull(who, "ComponentName is null");
5330 synchronized (this) {
5331 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5333 long id = Binder.clearCallingIdentity();
5335 UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */);
5336 if (userInfo != null) {
5337 return userInfo.getUserHandle();
5341 restoreCallingIdentity(id);
5347 public UserHandle createAndInitializeUser(ComponentName who, String name,
5348 String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) {
5349 UserHandle user = createUser(who, name);
5353 long id = Binder.clearCallingIdentity();
5355 String profileOwnerPkg = profileOwnerComponent.getPackageName();
5356 final IPackageManager ipm = AppGlobals.getPackageManager();
5357 IActivityManager activityManager = ActivityManagerNative.getDefault();
5359 final int userHandle = user.getIdentifier();
5361 // Install the profile owner if not present.
5362 if (!ipm.isPackageAvailable(profileOwnerPkg, userHandle)) {
5363 ipm.installExistingPackageAsUser(profileOwnerPkg, userHandle);
5366 // Start user in background.
5367 activityManager.startUserInBackground(userHandle);
5368 } catch (RemoteException e) {
5369 Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e);
5372 setActiveAdmin(profileOwnerComponent, true, userHandle, adminExtras);
5373 setProfileOwner(profileOwnerComponent, ownerName, userHandle);
5376 restoreCallingIdentity(id);
5381 public boolean removeUser(ComponentName who, UserHandle userHandle) {
5382 Preconditions.checkNotNull(who, "ComponentName is null");
5383 synchronized (this) {
5384 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5386 long id = Binder.clearCallingIdentity();
5388 return mUserManager.removeUser(userHandle.getIdentifier());
5390 restoreCallingIdentity(id);
5396 public boolean switchUser(ComponentName who, UserHandle userHandle) {
5397 Preconditions.checkNotNull(who, "ComponentName is null");
5398 synchronized (this) {
5399 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5401 long id = Binder.clearCallingIdentity();
5403 int userId = UserHandle.USER_OWNER;
5404 if (userHandle != null) {
5405 userId = userHandle.getIdentifier();
5407 return ActivityManagerNative.getDefault().switchUser(userId);
5408 } catch (RemoteException e) {
5409 Log.e(LOG_TAG, "Couldn't switch user", e);
5412 restoreCallingIdentity(id);
5418 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
5419 Preconditions.checkNotNull(who, "ComponentName is null");
5420 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
5422 synchronized (this) {
5423 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5425 long id = Binder.clearCallingIdentity();
5427 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
5428 // if no restrictions were saved, mUserManager.getApplicationRestrictions
5429 // returns null, but DPM method should return an empty Bundle as per JavaDoc
5430 return bundle != null ? bundle : Bundle.EMPTY;
5432 restoreCallingIdentity(id);
5438 public void setUserRestriction(ComponentName who, String key, boolean enabled) {
5439 Preconditions.checkNotNull(who, "ComponentName is null");
5440 final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
5441 final int userHandle = user.getIdentifier();
5442 synchronized (this) {
5443 ActiveAdmin activeAdmin =
5444 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5445 boolean isDeviceOwner = isDeviceOwner(activeAdmin.info.getPackageName());
5446 if (!isDeviceOwner && userHandle != UserHandle.USER_OWNER
5447 && DEVICE_OWNER_USER_RESTRICTIONS.contains(key)) {
5448 throw new SecurityException("Profile owners cannot set user restriction " + key);
5450 if (IMMUTABLE_USER_RESTRICTIONS.contains(key)) {
5451 throw new SecurityException("User restriction " + key + " cannot be changed");
5453 boolean alreadyRestricted = mUserManager.hasUserRestriction(key, user);
5455 IAudioService iAudioService = null;
5456 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)
5457 || UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5458 iAudioService = IAudioService.Stub.asInterface(
5459 ServiceManager.getService(Context.AUDIO_SERVICE));
5462 long id = Binder.clearCallingIdentity();
5464 if (enabled && !alreadyRestricted) {
5465 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
5466 iAudioService.setMicrophoneMute(true, mContext.getPackageName(),
5468 } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5469 iAudioService.setMasterMute(true, 0, mContext.getPackageName(),
5472 if (UserManager.DISALLOW_CONFIG_WIFI.equals(key)) {
5473 Settings.Secure.putIntForUser(mContext.getContentResolver(),
5474 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0,
5476 } else if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
5477 Settings.Secure.putIntForUser(mContext.getContentResolver(),
5478 Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF,
5480 Settings.Secure.putStringForUser(mContext.getContentResolver(),
5481 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, "",
5483 } else if (UserManager.DISALLOW_DEBUGGING_FEATURES.equals(key)) {
5484 // Only disable adb if changing for primary user, since it is global
5485 if (userHandle == UserHandle.USER_OWNER) {
5486 Settings.Global.putStringForUser(mContext.getContentResolver(),
5487 Settings.Global.ADB_ENABLED, "0", userHandle);
5489 } else if (UserManager.ENSURE_VERIFY_APPS.equals(key)) {
5490 Settings.Global.putStringForUser(mContext.getContentResolver(),
5491 Settings.Global.PACKAGE_VERIFIER_ENABLE, "1",
5493 Settings.Global.putStringForUser(mContext.getContentResolver(),
5494 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1",
5496 } else if (UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES.equals(key)) {
5497 Settings.Secure.putIntForUser(mContext.getContentResolver(),
5498 Settings.Secure.INSTALL_NON_MARKET_APPS, 0,
5502 mUserManager.setUserRestriction(key, enabled, user);
5503 if (enabled != alreadyRestricted) {
5504 if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
5505 // Send out notifications however as some clients may want to reread the
5506 // value which actually changed due to a restriction having been applied.
5507 final String property = Settings.Secure.SYS_PROP_SETTING_VERSION;
5508 long version = SystemProperties.getLong(property, 0) + 1;
5509 SystemProperties.set(property, Long.toString(version));
5511 final String name = Settings.Secure.LOCATION_PROVIDERS_ALLOWED;
5512 Uri url = Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
5513 mContext.getContentResolver().notifyChange(url, null, true, userHandle);
5516 if (!enabled && alreadyRestricted) {
5517 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
5518 iAudioService.setMicrophoneMute(false, mContext.getPackageName(),
5520 } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5521 iAudioService.setMasterMute(false, 0, mContext.getPackageName(),
5525 } catch (RemoteException re) {
5526 Slog.e(LOG_TAG, "Failed to talk to AudioService.", re);
5528 restoreCallingIdentity(id);
5530 sendChangedNotification(userHandle);
5535 public boolean setApplicationHidden(ComponentName who, String packageName,
5537 Preconditions.checkNotNull(who, "ComponentName is null");
5538 int callingUserId = UserHandle.getCallingUserId();
5539 synchronized (this) {
5540 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5542 long id = Binder.clearCallingIdentity();
5544 IPackageManager pm = AppGlobals.getPackageManager();
5545 return pm.setApplicationHiddenSettingAsUser(packageName, hidden, callingUserId);
5546 } catch (RemoteException re) {
5548 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
5550 restoreCallingIdentity(id);
5557 public boolean isApplicationHidden(ComponentName who, String packageName) {
5558 Preconditions.checkNotNull(who, "ComponentName is null");
5559 int callingUserId = UserHandle.getCallingUserId();
5560 synchronized (this) {
5561 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5563 long id = Binder.clearCallingIdentity();
5565 IPackageManager pm = AppGlobals.getPackageManager();
5566 return pm.getApplicationHiddenSettingAsUser(packageName, callingUserId);
5567 } catch (RemoteException re) {
5569 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
5571 restoreCallingIdentity(id);
5578 public void enableSystemApp(ComponentName who, String packageName) {
5579 Preconditions.checkNotNull(who, "ComponentName is null");
5580 synchronized (this) {
5581 // This API can only be called by an active device admin,
5582 // so try to retrieve it to check that the caller is one.
5583 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5585 int userId = UserHandle.getCallingUserId();
5586 long id = Binder.clearCallingIdentity();
5590 Slog.v(LOG_TAG, "installing " + packageName + " for "
5594 UserManager um = UserManager.get(mContext);
5595 UserInfo primaryUser = um.getProfileParent(userId);
5597 // Call did not come from a managed profile
5598 if (primaryUser == null) {
5599 primaryUser = um.getUserInfo(userId);
5602 IPackageManager pm = AppGlobals.getPackageManager();
5603 if (!isSystemApp(pm, packageName, primaryUser.id)) {
5604 throw new IllegalArgumentException("Only system apps can be enabled this way.");
5608 pm.installExistingPackageAsUser(packageName, userId);
5610 } catch (RemoteException re) {
5612 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
5614 restoreCallingIdentity(id);
5620 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
5621 Preconditions.checkNotNull(who, "ComponentName is null");
5622 synchronized (this) {
5623 // This API can only be called by an active device admin,
5624 // so try to retrieve it to check that the caller is one.
5625 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5627 int userId = UserHandle.getCallingUserId();
5628 long id = Binder.clearCallingIdentity();
5631 UserManager um = UserManager.get(mContext);
5632 UserInfo primaryUser = um.getProfileParent(userId);
5634 // Call did not come from a managed profile.
5635 if (primaryUser == null) {
5636 primaryUser = um.getUserInfo(userId);
5639 IPackageManager pm = AppGlobals.getPackageManager();
5640 List<ResolveInfo> activitiesToEnable = pm.queryIntentActivities(intent,
5641 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5645 if (DBG) Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
5646 int numberOfAppsInstalled = 0;
5647 if (activitiesToEnable != null) {
5648 for (ResolveInfo info : activitiesToEnable) {
5649 if (info.activityInfo != null) {
5650 String packageName = info.activityInfo.packageName;
5651 if (isSystemApp(pm, packageName, primaryUser.id)) {
5652 numberOfAppsInstalled++;
5653 pm.installExistingPackageAsUser(packageName, userId);
5655 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
5661 return numberOfAppsInstalled;
5662 } catch (RemoteException e) {
5664 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
5667 restoreCallingIdentity(id);
5672 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
5673 throws RemoteException {
5674 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
5676 if (appInfo == null) {
5677 throw new IllegalArgumentException("The application " + packageName +
5678 " is not present on this device");
5680 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5684 public void setAccountManagementDisabled(ComponentName who, String accountType,
5689 Preconditions.checkNotNull(who, "ComponentName is null");
5690 synchronized (this) {
5691 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5692 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5694 ap.accountTypesWithManagementDisabled.add(accountType);
5696 ap.accountTypesWithManagementDisabled.remove(accountType);
5698 saveSettingsLocked(UserHandle.getCallingUserId());
5703 public String[] getAccountTypesWithManagementDisabled() {
5704 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
5708 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
5709 enforceCrossUserPermission(userId);
5713 synchronized (this) {
5714 DevicePolicyData policy = getUserData(userId);
5715 final int N = policy.mAdminList.size();
5716 HashSet<String> resultSet = new HashSet<String>();
5717 for (int i = 0; i < N; i++) {
5718 ActiveAdmin admin = policy.mAdminList.get(i);
5719 resultSet.addAll(admin.accountTypesWithManagementDisabled);
5721 return resultSet.toArray(new String[resultSet.size()]);
5726 public void setUninstallBlocked(ComponentName who, String packageName,
5727 boolean uninstallBlocked) {
5728 Preconditions.checkNotNull(who, "ComponentName is null");
5729 final int userId = UserHandle.getCallingUserId();
5730 synchronized (this) {
5731 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5733 long id = Binder.clearCallingIdentity();
5735 IPackageManager pm = AppGlobals.getPackageManager();
5736 pm.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
5737 } catch (RemoteException re) {
5738 // Shouldn't happen.
5739 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
5741 restoreCallingIdentity(id);
5747 public boolean isUninstallBlocked(ComponentName who, String packageName) {
5748 // This function should return true if and only if the package is blocked by
5749 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
5750 // when the package is a system app, or when it is an active device admin.
5751 final int userId = UserHandle.getCallingUserId();
5753 synchronized (this) {
5755 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5758 long id = Binder.clearCallingIdentity();
5760 IPackageManager pm = AppGlobals.getPackageManager();
5761 return pm.getBlockUninstallForUser(packageName, userId);
5762 } catch (RemoteException re) {
5763 // Shouldn't happen.
5764 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
5766 restoreCallingIdentity(id);
5773 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
5777 Preconditions.checkNotNull(who, "ComponentName is null");
5778 synchronized (this) {
5779 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5780 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5781 if (admin.disableCallerId != disabled) {
5782 admin.disableCallerId = disabled;
5783 saveSettingsLocked(UserHandle.getCallingUserId());
5789 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
5793 Preconditions.checkNotNull(who, "ComponentName is null");
5794 synchronized (this) {
5795 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5796 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5797 return admin.disableCallerId;
5802 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
5803 // TODO: Should there be a check to make sure this relationship is within a profile group?
5804 //enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5805 synchronized (this) {
5806 ActiveAdmin admin = getProfileOwnerAdmin(userId);
5807 return (admin != null) ? admin.disableCallerId : false;
5812 public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5813 Intent originalIntent) {
5814 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(
5815 actualLookupKey, actualContactId, originalIntent);
5816 final int callingUserId = UserHandle.getCallingUserId();
5818 final long ident = Binder.clearCallingIdentity();
5820 synchronized (this) {
5821 final int managedUserId = getManagedUserId(callingUserId);
5822 if (managedUserId < 0) {
5825 if (getCrossProfileCallerIdDisabledForUser(managedUserId)) {
5828 "Cross-profile contacts access disabled for user " + managedUserId);
5832 ContactsInternal.startQuickContactWithErrorToastForUser(
5833 mContext, intent, new UserHandle(managedUserId));
5836 Binder.restoreCallingIdentity(ident);
5841 * @return the user ID of the managed user that is linked to the current user, if any.
5844 public int getManagedUserId(int callingUserId) {
5846 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
5849 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
5850 if (ui.id == callingUserId || !ui.isManagedProfile()) {
5851 continue; // Caller user self, or not a managed profile. Skip.
5854 Log.v(LOG_TAG, "Managed user=" + ui.id);
5859 Log.v(LOG_TAG, "Managed user not found.");
5865 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
5869 Preconditions.checkNotNull(who, "ComponentName is null");
5870 synchronized (this) {
5871 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5872 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5873 if (admin.disableBluetoothContactSharing != disabled) {
5874 admin.disableBluetoothContactSharing = disabled;
5875 saveSettingsLocked(UserHandle.getCallingUserId());
5881 public boolean getBluetoothContactSharingDisabled(ComponentName who) {
5885 Preconditions.checkNotNull(who, "ComponentName is null");
5886 synchronized (this) {
5887 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5888 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5889 return admin.disableBluetoothContactSharing;
5894 public boolean getBluetoothContactSharingDisabledForUser(int userId) {
5895 // TODO: Should there be a check to make sure this relationship is
5896 // within a profile group?
5897 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5898 synchronized (this) {
5899 ActiveAdmin admin = getProfileOwnerAdmin(userId);
5900 return (admin != null) ? admin.disableBluetoothContactSharing : false;
5905 * Sets which packages may enter lock task mode.
5907 * This function can only be called by the device owner.
5908 * @param packages The list of packages allowed to enter lock task mode.
5911 public void setLockTaskPackages(ComponentName who, String[] packages)
5912 throws SecurityException {
5913 Preconditions.checkNotNull(who, "ComponentName is null");
5914 synchronized (this) {
5915 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5917 int userHandle = Binder.getCallingUserHandle().getIdentifier();
5918 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
5922 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
5923 DevicePolicyData policy = getUserData(userHandle);
5924 policy.mLockTaskPackages = packages;
5926 // Store the settings persistently.
5927 saveSettingsLocked(userHandle);
5928 updateLockTaskPackagesLocked(packages, userHandle);
5932 * This function returns the list of components allowed to start the task lock mode.
5935 public String[] getLockTaskPackages(ComponentName who) {
5936 Preconditions.checkNotNull(who, "ComponentName is null");
5937 synchronized (this) {
5938 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5939 int userHandle = Binder.getCallingUserHandle().getIdentifier();
5940 final List<String> packages = getLockTaskPackagesLocked(userHandle);
5941 return packages.toArray(new String[packages.size()]);
5945 private List<String> getLockTaskPackagesLocked(int userHandle) {
5946 final DevicePolicyData policy = getUserData(userHandle);
5947 return policy.mLockTaskPackages;
5951 * This function lets the caller know whether the given package is allowed to start the
5953 * @param pkg The package to check
5956 public boolean isLockTaskPermitted(String pkg) {
5957 // Get current user's devicepolicy
5958 int uid = Binder.getCallingUid();
5959 int userHandle = UserHandle.getUserId(uid);
5960 DevicePolicyData policy = getUserData(userHandle);
5961 synchronized (this) {
5962 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
5963 String lockTaskPackage = policy.mLockTaskPackages.get(i);
5965 // If the given package equals one of the packages stored our list,
5966 // we allow this package to start lock task mode.
5967 if (lockTaskPackage.equals(pkg)) {
5976 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
5977 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
5978 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
5980 synchronized (this) {
5981 final DevicePolicyData policy = getUserData(userHandle);
5982 Bundle adminExtras = new Bundle();
5983 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
5984 for (ActiveAdmin admin : policy.mAdminList) {
5985 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
5986 boolean ownsProfile = (getProfileOwner(userHandle) != null
5987 && getProfileOwner(userHandle).equals(admin.info.getPackageName()));
5988 if (ownsDevice || ownsProfile) {
5990 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
5993 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
6001 public void setGlobalSetting(ComponentName who, String setting, String value) {
6002 final ContentResolver contentResolver = mContext.getContentResolver();
6003 Preconditions.checkNotNull(who, "ComponentName is null");
6005 synchronized (this) {
6006 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6008 // Some settings are no supported any more. However we do not want to throw a
6009 // SecurityException to avoid breaking apps.
6010 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
6011 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
6015 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
6016 throw new SecurityException(String.format(
6017 "Permission denial: device owners cannot update %1$s", setting));
6020 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
6021 // ignore if it contradicts an existing policy
6022 long timeMs = getMaximumTimeToLock(who, UserHandle.getCallingUserId());
6023 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
6028 long id = Binder.clearCallingIdentity();
6030 Settings.Global.putString(contentResolver, setting, value);
6032 restoreCallingIdentity(id);
6038 public void setSecureSetting(ComponentName who, String setting, String value) {
6039 Preconditions.checkNotNull(who, "ComponentName is null");
6040 int callingUserId = UserHandle.getCallingUserId();
6041 final ContentResolver contentResolver = mContext.getContentResolver();
6043 synchronized (this) {
6044 ActiveAdmin activeAdmin =
6045 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6047 if (isDeviceOwner(activeAdmin.info.getPackageName())) {
6048 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
6049 throw new SecurityException(String.format(
6050 "Permission denial: Device owners cannot update %1$s", setting));
6052 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
6053 throw new SecurityException(String.format(
6054 "Permission denial: Profile owners cannot update %1$s", setting));
6057 long id = Binder.clearCallingIdentity();
6059 Settings.Secure.putStringForUser(contentResolver, setting, value, callingUserId);
6061 restoreCallingIdentity(id);
6067 public void setMasterVolumeMuted(ComponentName who, boolean on) {
6068 Preconditions.checkNotNull(who, "ComponentName is null");
6069 synchronized (this) {
6070 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6071 int userId = UserHandle.getCallingUserId();
6072 long identity = Binder.clearCallingIdentity();
6074 IAudioService iAudioService = IAudioService.Stub.asInterface(
6075 ServiceManager.getService(Context.AUDIO_SERVICE));
6076 iAudioService.setMasterMute(on, 0, mContext.getPackageName(), userId);
6077 } catch (RemoteException re) {
6078 Slog.e(LOG_TAG, "Failed to setMasterMute", re);
6080 Binder.restoreCallingIdentity(identity);
6086 public boolean isMasterVolumeMuted(ComponentName who) {
6087 Preconditions.checkNotNull(who, "ComponentName is null");
6088 synchronized (this) {
6089 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6091 AudioManager audioManager =
6092 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
6093 return audioManager.isMasterMute();
6098 public void setUserIcon(ComponentName who, Bitmap icon) {
6099 synchronized (this) {
6100 Preconditions.checkNotNull(who, "ComponentName is null");
6101 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6103 int userId = UserHandle.getCallingUserId();
6104 long id = Binder.clearCallingIdentity();
6106 mUserManager.setUserIcon(userId, icon);
6108 restoreCallingIdentity(id);
6114 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
6115 Preconditions.checkNotNull(who, "ComponentName is null");
6116 synchronized (this) {
6117 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6119 final int userId = UserHandle.getCallingUserId();
6120 LockPatternUtils utils = new LockPatternUtils(mContext);
6122 long ident = Binder.clearCallingIdentity();
6124 // disallow disabling the keyguard if a password is currently set
6125 if (disabled && utils.isSecure(userId)) {
6128 utils.setLockScreenDisabled(disabled, userId);
6130 Binder.restoreCallingIdentity(ident);
6136 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
6137 int userId = UserHandle.getCallingUserId();
6138 synchronized (this) {
6139 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6140 DevicePolicyData policy = getUserData(userId);
6141 if (policy.mStatusBarDisabled != disabled) {
6142 if (!setStatusBarDisabledInternal(disabled, userId)) {
6145 policy.mStatusBarDisabled = disabled;
6146 saveSettingsLocked(userId);
6152 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
6153 long ident = Binder.clearCallingIdentity();
6155 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
6156 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
6157 if (statusBarService != null) {
6158 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
6159 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
6160 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
6161 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
6164 } catch (RemoteException e) {
6165 Slog.e(LOG_TAG, "Failed to disable the status bar", e);
6167 Binder.restoreCallingIdentity(ident);
6173 * We need to update the internal state of whether a user has completed setup once. After
6174 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
6175 * as we don't trust any apps that might try to reset it.
6177 * Unfortunately, we don't know which user's setup state was changed, so we write all of
6180 void updateUserSetupComplete() {
6181 List<UserInfo> users = mUserManager.getUsers(true);
6182 ContentResolver resolver = mContext.getContentResolver();
6183 final int N = users.size();
6184 for (int i = 0; i < N; i++) {
6185 int userHandle = users.get(i).id;
6186 if (Settings.Secure.getIntForUser(resolver, Settings.Secure.USER_SETUP_COMPLETE, 0,
6188 DevicePolicyData policy = getUserData(userHandle);
6189 if (!policy.mUserSetupComplete) {
6190 policy.mUserSetupComplete = true;
6191 synchronized (this) {
6192 // The DeviceInitializer was whitelisted but now should be removed.
6193 removeDeviceInitializerFromLockTaskPackages(userHandle);
6194 saveSettingsLocked(userHandle);
6201 private void addDeviceInitializerToLockTaskPackagesLocked(int userHandle) {
6202 if (hasUserSetupCompleted(userHandle)) {
6206 final String deviceInitializerPackage = getDeviceInitializer();
6207 if (deviceInitializerPackage == null) {
6211 final List<String> packages = getLockTaskPackagesLocked(userHandle);
6212 if (!packages.contains(deviceInitializerPackage)) {
6213 packages.add(deviceInitializerPackage);
6214 setLockTaskPackagesLocked(userHandle, packages);
6218 private void removeDeviceInitializerFromLockTaskPackages(int userHandle) {
6219 final String deviceInitializerPackage = getDeviceInitializer();
6220 if (deviceInitializerPackage == null) {
6224 List<String> packages = getLockTaskPackagesLocked(userHandle);
6225 if (packages.remove(deviceInitializerPackage)) {
6226 setLockTaskPackagesLocked(userHandle, packages);
6230 private class SetupContentObserver extends ContentObserver {
6232 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
6233 Settings.Secure.USER_SETUP_COMPLETE);
6235 public SetupContentObserver(Handler handler) {
6239 void register(ContentResolver resolver) {
6240 resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
6244 public void onChange(boolean selfChange, Uri uri) {
6245 if (mUserSetupComplete.equals(uri)) {
6246 updateUserSetupComplete();
6251 private final class LocalService extends DevicePolicyManagerInternal {
6252 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
6255 public List<String> getCrossProfileWidgetProviders(int profileId) {
6256 synchronized (DevicePolicyManagerService.this) {
6257 if (mDeviceOwner == null) {
6258 return Collections.emptyList();
6260 ComponentName ownerComponent = mDeviceOwner.getProfileOwnerComponent(profileId);
6261 if (ownerComponent == null) {
6262 return Collections.emptyList();
6265 DevicePolicyData policy = getUserDataUnchecked(profileId);
6266 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
6268 if (admin == null || admin.crossProfileWidgetProviders == null
6269 || admin.crossProfileWidgetProviders.isEmpty()) {
6270 return Collections.emptyList();
6273 return admin.crossProfileWidgetProviders;
6278 public void addOnCrossProfileWidgetProvidersChangeListener(
6279 OnCrossProfileWidgetProvidersChangeListener listener) {
6280 synchronized (DevicePolicyManagerService.this) {
6281 if (mWidgetProviderListeners == null) {
6282 mWidgetProviderListeners = new ArrayList<>();
6284 if (!mWidgetProviderListeners.contains(listener)) {
6285 mWidgetProviderListeners.add(listener);
6291 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
6292 final int userId = UserHandle.getUserId(uid);
6293 synchronized(DevicePolicyManagerService.this) {
6294 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
6298 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
6299 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
6300 synchronized (DevicePolicyManagerService.this) {
6301 listeners = new ArrayList<>(mWidgetProviderListeners);
6303 final int listenerCount = listeners.size();
6304 for (int i = 0; i < listenerCount; i++) {
6305 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
6306 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
6312 * Returns true if specified admin is allowed to limit passwords and has a
6313 * {@code passwordQuality} of at least {@code minPasswordQuality}
6315 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
6316 if (admin.passwordQuality < minPasswordQuality) {
6319 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
6323 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
6324 if (policy != null && !policy.isValid()) {
6325 throw new IllegalArgumentException("Invalid system update policy.");
6327 synchronized (this) {
6328 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6329 if (policy == null) {
6330 mDeviceOwner.clearSystemUpdatePolicy();
6332 mDeviceOwner.setSystemUpdatePolicy(policy);
6334 mDeviceOwner.writeOwnerFile();
6336 mContext.sendBroadcastAsUser(
6337 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
6342 public SystemUpdatePolicy getSystemUpdatePolicy() {
6343 synchronized (this) {
6344 SystemUpdatePolicy policy = mDeviceOwner.getSystemUpdatePolicy();
6345 if (policy != null && !policy.isValid()) {
6346 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
6354 * Checks if the caller of the method is the device owner app or device initialization app.
6356 * @param callerUid UID of the caller.
6357 * @return true if the caller is the device owner app or device initializer.
6359 private boolean isCallerDeviceOwnerOrInitializer(int callerUid) {
6360 String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
6361 for (String pkg : pkgs) {
6362 if (isDeviceOwner(pkg) || isDeviceInitializer(pkg)) {
6370 public void notifyPendingSystemUpdate(long updateReceivedTime) {
6371 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
6372 "Only the system update service can broadcast update information");
6374 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
6375 Slog.w(LOG_TAG, "Only the system update service in the primary user" +
6376 "can broadcast update information.");
6379 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
6380 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
6381 updateReceivedTime);
6383 synchronized (this) {
6384 String deviceOwnerPackage = getDeviceOwner();
6385 if (deviceOwnerPackage == null) {
6389 ActivityInfo[] receivers = null;
6391 receivers = mContext.getPackageManager().getPackageInfo(
6392 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
6393 } catch (NameNotFoundException e) {
6394 Log.e(LOG_TAG, "Cannot find device owner package", e);
6396 if (receivers != null) {
6397 long ident = Binder.clearCallingIdentity();
6399 for (int i = 0; i < receivers.length; i++) {
6400 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
6401 intent.setComponent(new ComponentName(deviceOwnerPackage,
6402 receivers[i].name));
6403 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
6407 Binder.restoreCallingIdentity(ident);
6414 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
6415 int userId = UserHandle.getCallingUserId();
6416 synchronized (this) {
6417 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6418 DevicePolicyData userPolicy = getUserData(userId);
6419 if (userPolicy.mPermissionPolicy != policy) {
6420 userPolicy.mPermissionPolicy = policy;
6421 saveSettingsLocked(userId);
6427 public int getPermissionPolicy(ComponentName admin) throws RemoteException {
6428 int userId = UserHandle.getCallingUserId();
6429 synchronized (this) {
6430 DevicePolicyData userPolicy = getUserData(userId);
6431 return userPolicy.mPermissionPolicy;
6436 public boolean setPermissionGrantState(ComponentName admin, String packageName,
6437 String permission, int grantState) throws RemoteException {
6438 UserHandle user = Binder.getCallingUserHandle();
6439 synchronized (this) {
6440 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6441 long ident = Binder.clearCallingIdentity();
6443 final ApplicationInfo ai = AppGlobals.getPackageManager()
6444 .getApplicationInfo(packageName, 0, user.getIdentifier());
6445 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
6446 if (targetSdkVersion < android.os.Build.VERSION_CODES.M) {
6449 if (!isRuntimePermission(permission)) {
6450 EventLog.writeEvent(0x534e4554, "62623498", user.getIdentifier(), "");
6453 final PackageManager packageManager = mContext.getPackageManager();
6454 switch (grantState) {
6455 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
6456 packageManager.grantRuntimePermission(packageName, permission, user);
6457 packageManager.updatePermissionFlags(permission, packageName,
6458 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6459 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
6462 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
6463 packageManager.revokeRuntimePermission(packageName,
6465 packageManager.updatePermissionFlags(permission, packageName,
6466 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6467 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
6470 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
6471 packageManager.updatePermissionFlags(permission, packageName,
6472 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
6476 } catch (SecurityException se) {
6478 } catch (NameNotFoundException e) {
6481 Binder.restoreCallingIdentity(ident);
6486 public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
6487 final PackageManager packageManager = mContext.getPackageManager();
6488 PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
6489 return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
6490 == PermissionInfo.PROTECTION_DANGEROUS;
6494 public int getPermissionGrantState(ComponentName admin, String packageName,
6495 String permission) throws RemoteException {
6496 PackageManager packageManager = mContext.getPackageManager();
6498 UserHandle user = Binder.getCallingUserHandle();
6499 synchronized (this) {
6500 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6501 long ident = Binder.clearCallingIdentity();
6503 int granted = AppGlobals.getPackageManager().checkPermission(permission,
6504 packageName, user.getIdentifier());
6505 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
6506 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
6507 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
6508 // Not controlled by policy
6509 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
6511 // Policy controlled so return result based on permission grant state
6512 return granted == PackageManager.PERMISSION_GRANTED
6513 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
6514 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
6517 Binder.restoreCallingIdentity(ident);