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.WIPE_EXTERNAL_STORAGE;
21 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
22 import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
24 import android.accessibilityservice.AccessibilityServiceInfo;
25 import android.accounts.AccountManager;
26 import android.app.Activity;
27 import android.app.ActivityManagerNative;
28 import android.app.AlarmManager;
29 import android.app.AppGlobals;
30 import android.app.IActivityManager;
31 import android.app.Notification;
32 import android.app.NotificationManager;
33 import android.app.PendingIntent;
34 import android.app.admin.DeviceAdminInfo;
35 import android.app.admin.DeviceAdminReceiver;
36 import android.app.admin.DevicePolicyManager;
37 import android.app.admin.DevicePolicyManagerInternal;
38 import android.app.admin.IDevicePolicyManager;
39 import android.app.backup.IBackupManager;
40 import android.content.BroadcastReceiver;
41 import android.content.ComponentName;
42 import android.content.ContentResolver;
43 import android.content.Context;
44 import android.content.Intent;
45 import android.content.IntentFilter;
46 import android.content.pm.ApplicationInfo;
47 import android.content.pm.IPackageManager;
48 import android.content.pm.PackageManager;
49 import android.content.pm.PackageManager.NameNotFoundException;
50 import android.content.pm.ResolveInfo;
51 import android.content.pm.UserInfo;
52 import android.database.ContentObserver;
53 import android.hardware.usb.UsbManager;
54 import android.media.AudioManager;
55 import android.media.IAudioService;
56 import android.net.ConnectivityManager;
57 import android.net.ProxyInfo;
58 import android.net.Uri;
59 import android.os.AsyncTask;
60 import android.os.Binder;
61 import android.os.Bundle;
62 import android.os.Environment;
63 import android.os.FileUtils;
64 import android.os.Handler;
65 import android.os.IBinder;
66 import android.os.PersistableBundle;
67 import android.os.PowerManager;
68 import android.os.PowerManagerInternal;
69 import android.os.Process;
70 import android.os.RecoverySystem;
71 import android.os.RemoteCallback;
72 import android.os.RemoteException;
73 import android.os.ServiceManager;
74 import android.os.SystemClock;
75 import android.os.SystemProperties;
76 import android.os.UserHandle;
77 import android.os.UserManager;
78 import android.provider.Settings;
79 import android.security.Credentials;
80 import android.security.IKeyChainService;
81 import android.security.KeyChain;
82 import android.security.KeyChain.KeyChainConnection;
83 import android.text.TextUtils;
84 import android.service.persistentdata.PersistentDataBlockManager;
85 import android.util.Log;
86 import android.util.PrintWriterPrinter;
87 import android.util.Printer;
88 import android.util.Slog;
89 import android.util.SparseArray;
90 import android.util.Xml;
91 import android.view.accessibility.AccessibilityManager;
92 import android.view.accessibility.IAccessibilityManager;
93 import android.view.inputmethod.InputMethodInfo;
94 import android.view.inputmethod.InputMethodManager;
95 import android.view.IWindowManager;
97 import com.android.internal.R;
98 import com.android.internal.os.storage.ExternalStorageFormatter;
99 import com.android.internal.util.FastXmlSerializer;
100 import com.android.internal.util.JournaledFile;
101 import com.android.internal.util.XmlUtils;
102 import com.android.internal.widget.LockPatternUtils;
103 import com.android.server.LocalServices;
104 import com.android.server.SystemService;
105 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
107 import org.xmlpull.v1.XmlPullParser;
109 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
110 import static org.xmlpull.v1.XmlPullParser.END_TAG;
111 import static org.xmlpull.v1.XmlPullParser.TEXT;
113 import org.xmlpull.v1.XmlPullParserException;
114 import org.xmlpull.v1.XmlSerializer;
116 import java.io.ByteArrayInputStream;
118 import java.io.FileDescriptor;
119 import java.io.FileInputStream;
120 import java.io.FileNotFoundException;
121 import java.io.FileOutputStream;
122 import java.io.IOException;
123 import java.io.PrintWriter;
124 import java.security.cert.CertificateException;
125 import java.security.cert.CertificateFactory;
126 import java.security.cert.X509Certificate;
127 import java.text.DateFormat;
128 import java.util.ArrayList;
129 import java.util.Collections;
130 import java.util.Date;
131 import java.util.HashMap;
132 import java.util.HashSet;
133 import java.util.List;
134 import java.util.Map.Entry;
135 import java.util.Set;
138 * Implementation of the device policy APIs.
140 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
142 private static final String LOG_TAG = "DevicePolicyManagerService";
144 private static final String DEVICE_POLICIES_XML = "device_policies.xml";
146 private static final String LOCK_TASK_COMPONENTS_XML = "lock-task-component";
148 private static final int REQUEST_EXPIRE_PASSWORD = 5571;
150 private static final long MS_PER_DAY = 86400 * 1000;
152 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
154 protected static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
155 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
157 private static final int MONITORING_CERT_NOTIFICATION_ID = R.string.ssl_ca_cert_warning;
159 private static final boolean DBG = false;
161 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
162 private static final String ATTR_SETUP_COMPLETE = "setup-complete";
164 private static final Set<String> DEVICE_OWNER_USER_RESTRICTIONS;
166 DEVICE_OWNER_USER_RESTRICTIONS = new HashSet();
167 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_USB_FILE_TRANSFER);
168 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_TETHERING);
169 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_FACTORY_RESET);
170 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADD_USER);
171 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
172 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
173 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
174 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_UNMUTE_MICROPHONE);
175 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADJUST_VOLUME);
176 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SMS);
179 private static final Set<String> SECURE_SETTINGS_WHITELIST;
180 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
181 private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
183 SECURE_SETTINGS_WHITELIST = new HashSet();
184 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
185 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
186 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
188 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new HashSet();
189 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
190 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
192 GLOBAL_SETTINGS_WHITELIST = new HashSet();
193 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
194 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
195 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
196 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.BLUETOOTH_ON);
197 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
198 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
199 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.MODE_RINGER);
200 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.NETWORK_PREFERENCE);
201 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
202 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_ON);
203 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
206 final Context mContext;
207 final UserManager mUserManager;
208 final PowerManager.WakeLock mWakeLock;
210 final LocalService mLocalService;
212 final PowerManager mPowerManager;
213 final PowerManagerInternal mPowerManagerInternal;
215 IWindowManager mIWindowManager;
216 NotificationManager mNotificationManager;
218 // Stores and loads state on device and profile owners.
219 private DeviceOwner mDeviceOwner;
222 * Whether or not device admin feature is supported. If it isn't return defaults for all
225 private boolean mHasFeature;
227 public static final class Lifecycle extends SystemService {
228 private DevicePolicyManagerService mService;
230 public Lifecycle(Context context) {
232 mService = new DevicePolicyManagerService(context);
236 public void onStart() {
237 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
241 public void onBootPhase(int phase) {
242 if (phase == PHASE_LOCK_SETTINGS_READY) {
243 mService.systemReady();
248 public static class DevicePolicyData {
249 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
250 int mActivePasswordLength = 0;
251 int mActivePasswordUpperCase = 0;
252 int mActivePasswordLowerCase = 0;
253 int mActivePasswordLetters = 0;
254 int mActivePasswordNumeric = 0;
255 int mActivePasswordSymbols = 0;
256 int mActivePasswordNonLetter = 0;
257 int mFailedPasswordAttempts = 0;
260 int mPasswordOwner = -1;
261 long mLastMaximumTimeToLock = -1;
262 boolean mUserSetupComplete = false;
264 final HashMap<ComponentName, ActiveAdmin> mAdminMap
265 = new HashMap<ComponentName, ActiveAdmin>();
266 final ArrayList<ActiveAdmin> mAdminList
267 = new ArrayList<ActiveAdmin>();
268 final ArrayList<ComponentName> mRemovingAdmins
269 = new ArrayList<ComponentName>();
271 // This is the list of component allowed to start lock task mode.
272 final List<String> mLockTaskPackages = new ArrayList<String>();
274 ComponentName mRestrictionsProvider;
276 public DevicePolicyData(int userHandle) {
277 mUserHandle = userHandle;
281 final SparseArray<DevicePolicyData> mUserData = new SparseArray<DevicePolicyData>();
283 Handler mHandler = new Handler();
285 BroadcastReceiver mReceiver = new BroadcastReceiver() {
287 public void onReceive(Context context, Intent intent) {
288 final String action = intent.getAction();
289 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
291 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
292 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
293 if (DBG) Slog.v(LOG_TAG, "Sending password expiration notifications for action "
294 + action + " for user " + userHandle);
295 mHandler.post(new Runnable() {
297 handlePasswordExpirationNotification(userHandle);
301 if (Intent.ACTION_BOOT_COMPLETED.equals(action)
302 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
303 new MonitoringCertNotificationTask().execute(intent);
305 if (Intent.ACTION_USER_REMOVED.equals(action)) {
306 removeUserData(userHandle);
307 } else if (Intent.ACTION_USER_STARTED.equals(action)
308 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
310 if (Intent.ACTION_USER_STARTED.equals(action)) {
311 // Reset the policy data
312 synchronized (DevicePolicyManagerService.this) {
313 mUserData.remove(userHandle);
316 handlePackagesChanged(null /* check all admins */, userHandle);
317 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
318 || (Intent.ACTION_PACKAGE_ADDED.equals(action)
319 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
320 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
321 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
322 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
323 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
328 static class ActiveAdmin {
329 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
330 private static final String TAG_DISABLE_CAMERA = "disable-camera";
331 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
332 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
333 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
334 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
335 private static final String TAG_ACCOUNT_TYPE = "account-type";
336 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
337 = "permitted-accessiblity-services";
338 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
339 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
340 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
341 private static final String TAG_TRUST_AGENT_COMPONENT = "component";
342 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
343 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
344 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
345 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
346 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
347 private static final String TAG_PERMITTED_IMES = "permitted-imes";
348 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
349 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
350 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
351 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
352 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
353 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
354 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
355 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
356 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
357 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
358 private static final String ATTR_VALUE = "value";
359 private static final String TAG_PASSWORD_QUALITY = "password-quality";
360 private static final String TAG_POLICIES = "policies";
361 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
362 "cross-profile-widget-providers";
363 private static final String TAG_PROVIDER = "provider";
364 private static final String TAG_PACKAGE_LIST_ITEM = "item";
366 final DeviceAdminInfo info;
368 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
370 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
371 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
373 static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
374 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
376 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
377 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
379 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
380 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
382 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
383 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
385 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
386 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
388 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
389 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
391 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
392 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
394 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
395 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
397 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
398 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
400 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
401 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
403 static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
404 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
406 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
408 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
410 boolean encryptionRequested = false;
411 boolean disableCamera = false;
412 boolean disableCallerId = false;
413 boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
414 boolean requireAutoTime = false; // Can only be set by a device owner.
416 static class TrustAgentInfo {
417 public PersistableBundle options;
418 TrustAgentInfo(PersistableBundle bundle) {
423 Set<String> accountTypesWithManagementDisabled = new HashSet<String>();
425 // The list of permitted accessibility services package namesas set by a profile
426 // or device owner. Null means all accessibility services are allowed, empty means
427 // none except system services are allowed.
428 List<String> permittedAccessiblityServices;
430 // The list of permitted input methods package names as set by a profile or device owner.
431 // Null means all input methods are allowed, empty means none except system imes are
433 List<String> permittedInputMethods;
435 // TODO: review implementation decisions with frameworks team
436 boolean specifiesGlobalProxy = false;
437 String globalProxySpec = null;
438 String globalProxyExclusionList = null;
440 HashMap<String, TrustAgentInfo> trustAgentInfos = new HashMap<String, TrustAgentInfo>();
442 List<String> crossProfileWidgetProviders;
444 ActiveAdmin(DeviceAdminInfo _info) {
448 int getUid() { return info.getActivityInfo().applicationInfo.uid; }
450 public UserHandle getUserHandle() {
451 return new UserHandle(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
454 void writeToXml(XmlSerializer out)
455 throws IllegalArgumentException, IllegalStateException, IOException {
456 out.startTag(null, TAG_POLICIES);
457 info.writePoliciesToXml(out);
458 out.endTag(null, TAG_POLICIES);
459 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
460 out.startTag(null, TAG_PASSWORD_QUALITY);
461 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
462 out.endTag(null, TAG_PASSWORD_QUALITY);
463 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
464 out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
465 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
466 out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
468 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
469 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
470 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
471 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
473 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
474 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
475 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
476 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
478 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
479 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
480 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
481 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
483 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
484 out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
485 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
486 out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
488 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
489 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
490 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
491 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
493 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
494 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
495 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
496 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
498 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
499 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
500 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
501 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
504 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
505 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
506 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
507 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
509 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
510 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
511 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
512 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
514 if (specifiesGlobalProxy) {
515 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
516 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
517 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
518 if (globalProxySpec != null) {
519 out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
520 out.attribute(null, ATTR_VALUE, globalProxySpec);
521 out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
523 if (globalProxyExclusionList != null) {
524 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
525 out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
526 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
529 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
530 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
531 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
532 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
534 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
535 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
536 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
537 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
539 if (encryptionRequested) {
540 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
541 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
542 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
545 out.startTag(null, TAG_DISABLE_CAMERA);
546 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
547 out.endTag(null, TAG_DISABLE_CAMERA);
549 if (disableCallerId) {
550 out.startTag(null, TAG_DISABLE_CALLER_ID);
551 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
552 out.endTag(null, TAG_DISABLE_CALLER_ID);
554 if (disableScreenCapture) {
555 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
556 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
557 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
559 if (requireAutoTime) {
560 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
561 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
562 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
564 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
565 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
566 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
567 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
569 if (!accountTypesWithManagementDisabled.isEmpty()) {
570 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
571 for (String ac : accountTypesWithManagementDisabled) {
572 out.startTag(null, TAG_ACCOUNT_TYPE);
573 out.attribute(null, ATTR_VALUE, ac);
574 out.endTag(null, TAG_ACCOUNT_TYPE);
576 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
578 if (!trustAgentInfos.isEmpty()) {
579 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
580 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
581 for (Entry<String, TrustAgentInfo> entry : set) {
582 TrustAgentInfo trustAgentInfo = entry.getValue();
583 out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
584 out.attribute(null, ATTR_VALUE, entry.getKey());
585 if (trustAgentInfo.options != null) {
586 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
588 trustAgentInfo.options.saveToXml(out);
589 } catch (XmlPullParserException e) {
590 Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
592 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
594 out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
596 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
598 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
599 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
600 final int providerCount = crossProfileWidgetProviders.size();
601 for (int i = 0; i < providerCount; i++) {
602 String provider = crossProfileWidgetProviders.get(i);
603 out.startTag(null, TAG_PROVIDER);
604 out.attribute(null, ATTR_VALUE, provider);
605 out.endTag(null, TAG_PROVIDER);
607 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
609 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
610 permittedAccessiblityServices);
611 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
614 void writePackageListToXml(XmlSerializer out, String outerTag,
615 List<String> packageList)
616 throws IllegalArgumentException, IllegalStateException, IOException {
617 if (packageList == null) {
621 out.startTag(null, outerTag);
622 for (String packageName : packageList) {
623 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
624 out.attribute(null, ATTR_VALUE, packageName);
625 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
627 out.endTag(null, outerTag);
630 void readFromXml(XmlPullParser parser)
631 throws XmlPullParserException, IOException {
632 int outerDepth = parser.getDepth();
634 while ((type=parser.next()) != END_DOCUMENT
635 && (type != END_TAG || parser.getDepth() > outerDepth)) {
636 if (type == END_TAG || type == TEXT) {
639 String tag = parser.getName();
640 if (TAG_POLICIES.equals(tag)) {
641 info.readPoliciesFromXml(parser);
642 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
643 passwordQuality = Integer.parseInt(
644 parser.getAttributeValue(null, ATTR_VALUE));
645 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
646 minimumPasswordLength = Integer.parseInt(
647 parser.getAttributeValue(null, ATTR_VALUE));
648 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
649 passwordHistoryLength = Integer.parseInt(
650 parser.getAttributeValue(null, ATTR_VALUE));
651 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
652 minimumPasswordUpperCase = Integer.parseInt(
653 parser.getAttributeValue(null, ATTR_VALUE));
654 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
655 minimumPasswordLowerCase = Integer.parseInt(
656 parser.getAttributeValue(null, ATTR_VALUE));
657 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
658 minimumPasswordLetters = Integer.parseInt(
659 parser.getAttributeValue(null, ATTR_VALUE));
660 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
661 minimumPasswordNumeric = Integer.parseInt(
662 parser.getAttributeValue(null, ATTR_VALUE));
663 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
664 minimumPasswordSymbols = Integer.parseInt(
665 parser.getAttributeValue(null, ATTR_VALUE));
666 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
667 minimumPasswordNonLetter = Integer.parseInt(
668 parser.getAttributeValue(null, ATTR_VALUE));
669 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
670 maximumTimeToUnlock = Long.parseLong(
671 parser.getAttributeValue(null, ATTR_VALUE));
672 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
673 maximumFailedPasswordsForWipe = Integer.parseInt(
674 parser.getAttributeValue(null, ATTR_VALUE));
675 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
676 specifiesGlobalProxy = Boolean.parseBoolean(
677 parser.getAttributeValue(null, ATTR_VALUE));
678 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
680 parser.getAttributeValue(null, ATTR_VALUE);
681 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
682 globalProxyExclusionList =
683 parser.getAttributeValue(null, ATTR_VALUE);
684 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
685 passwordExpirationTimeout = Long.parseLong(
686 parser.getAttributeValue(null, ATTR_VALUE));
687 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
688 passwordExpirationDate = Long.parseLong(
689 parser.getAttributeValue(null, ATTR_VALUE));
690 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
691 encryptionRequested = Boolean.parseBoolean(
692 parser.getAttributeValue(null, ATTR_VALUE));
693 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
694 disableCamera = Boolean.parseBoolean(
695 parser.getAttributeValue(null, ATTR_VALUE));
696 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
697 disableCallerId = Boolean.parseBoolean(
698 parser.getAttributeValue(null, ATTR_VALUE));
699 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
700 disableScreenCapture = Boolean.parseBoolean(
701 parser.getAttributeValue(null, ATTR_VALUE));
702 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
703 requireAutoTime= Boolean.parseBoolean(
704 parser.getAttributeValue(null, ATTR_VALUE));
705 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
706 disabledKeyguardFeatures = Integer.parseInt(
707 parser.getAttributeValue(null, ATTR_VALUE));
708 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
709 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
710 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
711 trustAgentInfos = getAllTrustAgentInfos(parser, tag);
712 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
713 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
714 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
715 permittedAccessiblityServices = readPackageList(parser, tag);
716 } else if (TAG_PERMITTED_IMES.equals(tag)) {
717 permittedInputMethods = readPackageList(parser, tag);
719 Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
721 XmlUtils.skipCurrentTag(parser);
725 private List<String> readPackageList(XmlPullParser parser,
726 String tag) throws XmlPullParserException, IOException {
727 List<String> result = new ArrayList<String>();
728 int outerDepth = parser.getDepth();
730 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
731 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
732 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
735 String outerTag = parser.getName();
736 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
737 String packageName = parser.getAttributeValue(null, ATTR_VALUE);
738 if (packageName != null) {
739 result.add(packageName);
741 Slog.w(LOG_TAG, "Package name missing under " + outerTag);
744 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag);
750 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
751 throws XmlPullParserException, IOException {
752 int outerDepthDAM = parser.getDepth();
754 Set<String> result = new HashSet<String>();
755 while ((typeDAM=parser.next()) != END_DOCUMENT
756 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
757 if (typeDAM == END_TAG || typeDAM == TEXT) {
760 String tagDAM = parser.getName();
761 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
762 result.add(parser.getAttributeValue(null, ATTR_VALUE));
764 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
770 private HashMap<String, TrustAgentInfo> getAllTrustAgentInfos(
771 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
772 int outerDepthDAM = parser.getDepth();
774 HashMap<String, TrustAgentInfo> result = new HashMap<String, TrustAgentInfo>();
775 while ((typeDAM=parser.next()) != END_DOCUMENT
776 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
777 if (typeDAM == END_TAG || typeDAM == TEXT) {
780 String tagDAM = parser.getName();
781 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
782 final String component = parser.getAttributeValue(null, ATTR_VALUE);
783 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
784 result.put(component, trustAgentInfo);
786 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
792 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
793 throws XmlPullParserException, IOException {
794 int outerDepthDAM = parser.getDepth();
796 TrustAgentInfo result = new TrustAgentInfo(null);
797 while ((typeDAM=parser.next()) != END_DOCUMENT
798 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
799 if (typeDAM == END_TAG || typeDAM == TEXT) {
802 String tagDAM = parser.getName();
803 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
804 PersistableBundle bundle = new PersistableBundle();
805 bundle.restoreFromXml(parser);
806 result.options = bundle;
808 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
814 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
815 throws XmlPullParserException, IOException {
816 int outerDepthDAM = parser.getDepth();
818 ArrayList<String> result = null;
819 while ((typeDAM=parser.next()) != END_DOCUMENT
820 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
821 if (typeDAM == END_TAG || typeDAM == TEXT) {
824 String tagDAM = parser.getName();
825 if (TAG_PROVIDER.equals(tagDAM)) {
826 final String provider = parser.getAttributeValue(null, ATTR_VALUE);
827 if (result == null) {
828 result = new ArrayList<>();
830 result.add(provider);
832 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM);
838 void dump(String prefix, PrintWriter pw) {
839 pw.print(prefix); pw.print("uid="); pw.println(getUid());
840 pw.print(prefix); pw.println("policies:");
841 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
843 for (int i=0; i<pols.size(); i++) {
844 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag);
847 pw.print(prefix); pw.print("passwordQuality=0x");
848 pw.println(Integer.toHexString(passwordQuality));
849 pw.print(prefix); pw.print("minimumPasswordLength=");
850 pw.println(minimumPasswordLength);
851 pw.print(prefix); pw.print("passwordHistoryLength=");
852 pw.println(passwordHistoryLength);
853 pw.print(prefix); pw.print("minimumPasswordUpperCase=");
854 pw.println(minimumPasswordUpperCase);
855 pw.print(prefix); pw.print("minimumPasswordLowerCase=");
856 pw.println(minimumPasswordLowerCase);
857 pw.print(prefix); pw.print("minimumPasswordLetters=");
858 pw.println(minimumPasswordLetters);
859 pw.print(prefix); pw.print("minimumPasswordNumeric=");
860 pw.println(minimumPasswordNumeric);
861 pw.print(prefix); pw.print("minimumPasswordSymbols=");
862 pw.println(minimumPasswordSymbols);
863 pw.print(prefix); pw.print("minimumPasswordNonLetter=");
864 pw.println(minimumPasswordNonLetter);
865 pw.print(prefix); pw.print("maximumTimeToUnlock=");
866 pw.println(maximumTimeToUnlock);
867 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
868 pw.println(maximumFailedPasswordsForWipe);
869 pw.print(prefix); pw.print("specifiesGlobalProxy=");
870 pw.println(specifiesGlobalProxy);
871 pw.print(prefix); pw.print("passwordExpirationTimeout=");
872 pw.println(passwordExpirationTimeout);
873 pw.print(prefix); pw.print("passwordExpirationDate=");
874 pw.println(passwordExpirationDate);
875 if (globalProxySpec != null) {
876 pw.print(prefix); pw.print("globalProxySpec=");
877 pw.println(globalProxySpec);
879 if (globalProxyExclusionList != null) {
880 pw.print(prefix); pw.print("globalProxyEclusionList=");
881 pw.println(globalProxyExclusionList);
883 pw.print(prefix); pw.print("encryptionRequested=");
884 pw.println(encryptionRequested);
885 pw.print(prefix); pw.print("disableCamera=");
886 pw.println(disableCamera);
887 pw.print(prefix); pw.print("disableCallerId=");
888 pw.println(disableCallerId);
889 pw.print(prefix); pw.print("disableScreenCapture=");
890 pw.println(disableScreenCapture);
891 pw.print(prefix); pw.print("requireAutoTime=");
892 pw.println(requireAutoTime);
893 pw.print(prefix); pw.print("disabledKeyguardFeatures=");
894 pw.println(disabledKeyguardFeatures);
895 pw.print(prefix); pw.print("crossProfileWidgetProviders=");
896 pw.println(crossProfileWidgetProviders);
897 if (!(permittedAccessiblityServices == null)) {
898 pw.print(prefix); pw.print("permittedAccessibilityServices=");
899 pw.println(permittedAccessiblityServices.toString());
901 if (!(permittedInputMethods == null)) {
902 pw.print(prefix); pw.print("permittedInputMethods=");
903 pw.println(permittedInputMethods.toString());
908 private void handlePackagesChanged(String packageName, int userHandle) {
909 boolean removed = false;
910 if (DBG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
911 DevicePolicyData policy = getUserData(userHandle);
912 IPackageManager pm = AppGlobals.getPackageManager();
913 synchronized (this) {
914 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
915 ActiveAdmin aa = policy.mAdminList.get(i);
917 // If we're checking all packages or if the specific one we're checking matches,
918 // then check if the package and receiver still exist.
919 final String adminPackage = aa.info.getPackageName();
920 if (packageName == null || packageName.equals(adminPackage)) {
921 if (pm.getPackageInfo(adminPackage, 0, userHandle) == null
922 || pm.getReceiverInfo(aa.info.getComponent(), 0, userHandle)
925 policy.mAdminList.remove(i);
926 policy.mAdminMap.remove(aa.info.getComponent());
929 } catch (RemoteException re) {
934 validatePasswordOwnerLocked(policy);
935 syncDeviceCapabilitiesLocked(policy);
936 saveSettingsLocked(policy.mUserHandle);
942 * Instantiates the service.
944 public DevicePolicyManagerService(Context context) {
946 mUserManager = UserManager.get(mContext);
947 mHasFeature = context.getPackageManager().hasSystemFeature(
948 PackageManager.FEATURE_DEVICE_ADMIN);
949 mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
950 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
951 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DPM");
952 mLocalService = new LocalService();
954 // Skip the rest of the initialization
957 IntentFilter filter = new IntentFilter();
958 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
959 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
960 filter.addAction(Intent.ACTION_USER_REMOVED);
961 filter.addAction(Intent.ACTION_USER_STARTED);
962 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
963 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
964 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
965 filter = new IntentFilter();
966 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
967 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
968 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
969 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
970 filter.addDataScheme("package");
971 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
973 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
977 * Creates and loads the policy data from xml.
978 * @param userHandle the user for whom to load the policy data
981 DevicePolicyData getUserData(int userHandle) {
982 synchronized (this) {
983 DevicePolicyData policy = mUserData.get(userHandle);
984 if (policy == null) {
985 policy = new DevicePolicyData(userHandle);
986 mUserData.append(userHandle, policy);
987 loadSettingsLocked(policy, userHandle);
994 * Creates and loads the policy data from xml for data that is shared between
995 * various profiles of a user. In contrast to {@link #getUserData(int)}
996 * it allows access to data of users other than the calling user.
998 * This function should only be used for shared data, e.g. everything regarding
999 * passwords and should be removed once multiple screen locks are present.
1000 * @param userHandle the user for whom to load the policy data
1003 DevicePolicyData getUserDataUnchecked(int userHandle) {
1004 long ident = Binder.clearCallingIdentity();
1006 return getUserData(userHandle);
1008 Binder.restoreCallingIdentity(ident);
1012 void removeUserData(int userHandle) {
1013 synchronized (this) {
1014 if (userHandle == UserHandle.USER_OWNER) {
1015 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1018 if (mDeviceOwner != null) {
1019 mDeviceOwner.removeProfileOwner(userHandle);
1020 mDeviceOwner.writeOwnerFile();
1023 DevicePolicyData policy = mUserData.get(userHandle);
1024 if (policy != null) {
1025 mUserData.remove(userHandle);
1027 File policyFile = new File(Environment.getUserSystemDirectory(userHandle),
1028 DEVICE_POLICIES_XML);
1029 policyFile.delete();
1030 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1032 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1035 void loadDeviceOwner() {
1036 synchronized (this) {
1037 mDeviceOwner = DeviceOwner.load();
1042 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1043 * reminders. Clears alarm if no expirations are configured.
1045 protected void setExpirationAlarmCheckLocked(Context context, DevicePolicyData policy) {
1046 final long expiration = getPasswordExpirationLocked(null, policy.mUserHandle);
1047 final long now = System.currentTimeMillis();
1048 final long timeToExpire = expiration - now;
1049 final long alarmTime;
1050 if (expiration == 0) {
1051 // No expirations are currently configured: Cancel alarm.
1053 } else if (timeToExpire <= 0) {
1054 // The password has already expired: Repeat every 24 hours.
1055 alarmTime = now + MS_PER_DAY;
1057 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before
1058 // the expiration time.
1059 long alarmInterval = timeToExpire % MS_PER_DAY;
1060 if (alarmInterval == 0) {
1061 alarmInterval = MS_PER_DAY;
1063 alarmTime = now + alarmInterval;
1066 long token = Binder.clearCallingIdentity();
1068 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1069 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1070 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1071 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1072 new UserHandle(policy.mUserHandle));
1074 if (alarmTime != 0) {
1075 am.set(AlarmManager.RTC, alarmTime, pi);
1078 Binder.restoreCallingIdentity(token);
1082 private IWindowManager getWindowManager() {
1083 if (mIWindowManager == null) {
1084 IBinder b = ServiceManager.getService(Context.WINDOW_SERVICE);
1085 mIWindowManager = IWindowManager.Stub.asInterface(b);
1087 return mIWindowManager;
1090 private NotificationManager getNotificationManager() {
1091 if (mNotificationManager == null) {
1092 mNotificationManager =
1093 (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
1095 return mNotificationManager;
1098 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1099 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1101 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1102 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1108 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1109 throws SecurityException {
1110 final int callingUid = Binder.getCallingUid();
1111 final int userHandle = UserHandle.getUserId(callingUid);
1112 final DevicePolicyData policy = getUserData(userHandle);
1114 List<ActiveAdmin> candidates = new ArrayList<ActiveAdmin>();
1116 // Build a list of admins for this uid matching the given ComponentName
1118 ActiveAdmin admin = policy.mAdminMap.get(who);
1119 if (admin == null) {
1120 throw new SecurityException("No active admin " + who);
1122 if (admin.getUid() != callingUid) {
1123 throw new SecurityException("Admin " + who + " is not owned by uid "
1124 + Binder.getCallingUid());
1126 candidates.add(admin);
1128 for (ActiveAdmin admin : policy.mAdminList) {
1129 if (admin.getUid() == callingUid) {
1130 candidates.add(admin);
1135 // Try to find an admin which can use reqPolicy
1136 for (ActiveAdmin admin : candidates) {
1137 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
1138 boolean ownsProfile = (getProfileOwner(userHandle) != null
1139 && getProfileOwner(userHandle).getPackageName()
1140 .equals(admin.info.getPackageName()));
1142 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1146 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1147 if (ownsDevice || ownsProfile) {
1151 if (admin.info.usesPolicy(reqPolicy)) {
1158 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1159 throw new SecurityException("Admin " + candidates.get(0).info.getComponent()
1160 + " does not own the device");
1162 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1163 throw new SecurityException("Admin " + candidates.get(0).info.getComponent()
1164 + " does not own the profile");
1166 throw new SecurityException("Admin " + candidates.get(0).info.getComponent()
1167 + " did not specify uses-policy for: "
1168 + candidates.get(0).info.getTagForPolicy(reqPolicy));
1170 throw new SecurityException("No active admin owned by uid "
1171 + Binder.getCallingUid() + " for policy #" + reqPolicy);
1175 void sendAdminCommandLocked(ActiveAdmin admin, String action) {
1176 sendAdminCommandLocked(admin, action, null);
1179 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
1180 sendAdminCommandLocked(admin, action, null, result);
1184 * Send an update to one specific admin, get notified when that admin returns a result.
1186 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
1187 BroadcastReceiver result) {
1188 Intent intent = new Intent(action);
1189 intent.setComponent(admin.info.getComponent());
1190 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
1191 intent.putExtra("expiration", admin.passwordExpirationDate);
1193 if (adminExtras != null) {
1194 intent.putExtras(adminExtras);
1196 if (result != null) {
1197 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
1198 null, result, mHandler, Activity.RESULT_OK, null, null);
1200 mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
1205 * Send an update to all admins of a user that enforce a specified policy.
1207 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
1208 final DevicePolicyData policy = getUserData(userHandle);
1209 final int count = policy.mAdminList.size();
1211 for (int i = 0; i < count; i++) {
1212 final ActiveAdmin admin = policy.mAdminList.get(i);
1213 if (admin.info.usesPolicy(reqPolicy)) {
1214 sendAdminCommandLocked(admin, action);
1221 * Send an update intent to all admins of a user and its profiles. Only send to admins that
1222 * enforce a specified policy.
1224 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
1226 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1227 for (UserInfo ui : profiles) {
1229 sendAdminCommandLocked(action, reqPolicy, id);
1233 void removeActiveAdminLocked(final ComponentName adminReceiver, int userHandle) {
1234 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
1235 if (admin != null) {
1236 synchronized (this) {
1237 getUserData(userHandle).mRemovingAdmins.add(adminReceiver);
1239 sendAdminCommandLocked(admin,
1240 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
1241 new BroadcastReceiver() {
1243 public void onReceive(Context context, Intent intent) {
1244 synchronized (DevicePolicyManagerService.this) {
1245 int userHandle = admin.getUserHandle().getIdentifier();
1246 DevicePolicyData policy = getUserData(userHandle);
1247 boolean doProxyCleanup = admin.info.usesPolicy(
1248 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
1249 policy.mAdminList.remove(admin);
1250 policy.mAdminMap.remove(adminReceiver);
1251 validatePasswordOwnerLocked(policy);
1252 syncDeviceCapabilitiesLocked(policy);
1253 if (doProxyCleanup) {
1254 resetGlobalProxyLocked(getUserData(userHandle));
1256 saveSettingsLocked(userHandle);
1257 updateMaximumTimeToLockLocked(policy);
1258 policy.mRemovingAdmins.remove(adminReceiver);
1265 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle) {
1269 enforceCrossUserPermission(userHandle);
1270 Intent resolveIntent = new Intent();
1271 resolveIntent.setComponent(adminName);
1272 List<ResolveInfo> infos = mContext.getPackageManager().queryBroadcastReceivers(
1274 PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
1276 if (infos == null || infos.size() <= 0) {
1277 throw new IllegalArgumentException("Unknown admin: " + adminName);
1281 return new DeviceAdminInfo(mContext, infos.get(0));
1282 } catch (XmlPullParserException e) {
1283 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
1286 } catch (IOException e) {
1287 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
1293 private static JournaledFile makeJournaledFile(int userHandle) {
1294 final String base = userHandle == 0
1295 ? "/data/system/" + DEVICE_POLICIES_XML
1296 : new File(Environment.getUserSystemDirectory(userHandle), DEVICE_POLICIES_XML)
1298 return new JournaledFile(new File(base), new File(base + ".tmp"));
1301 private void saveSettingsLocked(int userHandle) {
1302 DevicePolicyData policy = getUserData(userHandle);
1303 JournaledFile journal = makeJournaledFile(userHandle);
1304 FileOutputStream stream = null;
1306 stream = new FileOutputStream(journal.chooseForWrite(), false);
1307 XmlSerializer out = new FastXmlSerializer();
1308 out.setOutput(stream, "utf-8");
1309 out.startDocument(null, true);
1311 out.startTag(null, "policies");
1312 if (policy.mRestrictionsProvider != null) {
1313 out.attribute(null, ATTR_PERMISSION_PROVIDER,
1314 policy.mRestrictionsProvider.flattenToString());
1316 if (policy.mUserSetupComplete) {
1317 out.attribute(null, ATTR_SETUP_COMPLETE,
1318 Boolean.toString(true));
1321 final int N = policy.mAdminList.size();
1322 for (int i=0; i<N; i++) {
1323 ActiveAdmin ap = policy.mAdminList.get(i);
1325 out.startTag(null, "admin");
1326 out.attribute(null, "name", ap.info.getComponent().flattenToString());
1328 out.endTag(null, "admin");
1332 if (policy.mPasswordOwner >= 0) {
1333 out.startTag(null, "password-owner");
1334 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
1335 out.endTag(null, "password-owner");
1338 if (policy.mFailedPasswordAttempts != 0) {
1339 out.startTag(null, "failed-password-attempts");
1340 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
1341 out.endTag(null, "failed-password-attempts");
1344 if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
1345 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
1346 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
1347 || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
1348 out.startTag(null, "active-password");
1349 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
1350 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
1351 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
1352 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
1353 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
1354 out.attribute(null, "numeric", Integer
1355 .toString(policy.mActivePasswordNumeric));
1356 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
1357 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
1358 out.endTag(null, "active-password");
1361 for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
1362 String component = policy.mLockTaskPackages.get(i);
1363 out.startTag(null, LOCK_TASK_COMPONENTS_XML);
1364 out.attribute(null, "name", component);
1365 out.endTag(null, LOCK_TASK_COMPONENTS_XML);
1368 out.endTag(null, "policies");
1372 FileUtils.sync(stream);
1375 sendChangedNotification(userHandle);
1376 } catch (IOException e) {
1378 if (stream != null) {
1381 } catch (IOException ex) {
1388 private void sendChangedNotification(int userHandle) {
1389 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1390 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1391 long ident = Binder.clearCallingIdentity();
1393 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
1395 Binder.restoreCallingIdentity(ident);
1399 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
1400 JournaledFile journal = makeJournaledFile(userHandle);
1401 FileInputStream stream = null;
1402 File file = journal.chooseForRead();
1404 stream = new FileInputStream(file);
1405 XmlPullParser parser = Xml.newPullParser();
1406 parser.setInput(stream, null);
1409 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1410 && type != XmlPullParser.START_TAG) {
1412 String tag = parser.getName();
1413 if (!"policies".equals(tag)) {
1414 throw new XmlPullParserException(
1415 "Settings do not start with policies tag: found " + tag);
1418 // Extract the permission provider component name if available
1419 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
1420 if (permissionProvider != null) {
1421 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
1423 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
1424 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
1425 policy.mUserSetupComplete = true;
1428 type = parser.next();
1429 int outerDepth = parser.getDepth();
1430 policy.mLockTaskPackages.clear();
1431 policy.mAdminList.clear();
1432 policy.mAdminMap.clear();
1433 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1434 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1435 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1438 tag = parser.getName();
1439 if ("admin".equals(tag)) {
1440 String name = parser.getAttributeValue(null, "name");
1442 DeviceAdminInfo dai = findAdmin(
1443 ComponentName.unflattenFromString(name), userHandle);
1444 if (DBG && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
1446 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
1447 + dai.getActivityInfo().applicationInfo.uid + " for user "
1451 ActiveAdmin ap = new ActiveAdmin(dai);
1452 ap.readFromXml(parser);
1453 policy.mAdminMap.put(ap.info.getComponent(), ap);
1455 } catch (RuntimeException e) {
1456 Slog.w(LOG_TAG, "Failed loading admin " + name, e);
1458 } else if ("failed-password-attempts".equals(tag)) {
1459 policy.mFailedPasswordAttempts = Integer.parseInt(
1460 parser.getAttributeValue(null, "value"));
1461 XmlUtils.skipCurrentTag(parser);
1462 } else if ("password-owner".equals(tag)) {
1463 policy.mPasswordOwner = Integer.parseInt(
1464 parser.getAttributeValue(null, "value"));
1465 XmlUtils.skipCurrentTag(parser);
1466 } else if ("active-password".equals(tag)) {
1467 policy.mActivePasswordQuality = Integer.parseInt(
1468 parser.getAttributeValue(null, "quality"));
1469 policy.mActivePasswordLength = Integer.parseInt(
1470 parser.getAttributeValue(null, "length"));
1471 policy.mActivePasswordUpperCase = Integer.parseInt(
1472 parser.getAttributeValue(null, "uppercase"));
1473 policy.mActivePasswordLowerCase = Integer.parseInt(
1474 parser.getAttributeValue(null, "lowercase"));
1475 policy.mActivePasswordLetters = Integer.parseInt(
1476 parser.getAttributeValue(null, "letters"));
1477 policy.mActivePasswordNumeric = Integer.parseInt(
1478 parser.getAttributeValue(null, "numeric"));
1479 policy.mActivePasswordSymbols = Integer.parseInt(
1480 parser.getAttributeValue(null, "symbols"));
1481 policy.mActivePasswordNonLetter = Integer.parseInt(
1482 parser.getAttributeValue(null, "nonletter"));
1483 XmlUtils.skipCurrentTag(parser);
1484 } else if (LOCK_TASK_COMPONENTS_XML.equals(tag)) {
1485 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
1486 XmlUtils.skipCurrentTag(parser);
1488 Slog.w(LOG_TAG, "Unknown tag: " + tag);
1489 XmlUtils.skipCurrentTag(parser);
1492 } catch (NullPointerException e) {
1493 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1494 } catch (NumberFormatException e) {
1495 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1496 } catch (XmlPullParserException e) {
1497 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1498 } catch (FileNotFoundException e) {
1499 // Don't be noisy, this is normal if we haven't defined any policies.
1500 } catch (IOException e) {
1501 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1502 } catch (IndexOutOfBoundsException e) {
1503 Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1506 if (stream != null) {
1509 } catch (IOException e) {
1513 // Generate a list of admins from the admin map
1514 policy.mAdminList.addAll(policy.mAdminMap.values());
1516 // Validate that what we stored for the password quality matches
1517 // sufficiently what is currently set. Note that this is only
1518 // a sanity check in case the two get out of sync; this should
1519 // never normally happen.
1520 LockPatternUtils utils = new LockPatternUtils(mContext);
1521 if (utils.getActivePasswordQuality() < policy.mActivePasswordQuality) {
1522 Slog.w(LOG_TAG, "Active password quality 0x"
1523 + Integer.toHexString(policy.mActivePasswordQuality)
1524 + " does not match actual quality 0x"
1525 + Integer.toHexString(utils.getActivePasswordQuality()));
1526 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
1527 policy.mActivePasswordLength = 0;
1528 policy.mActivePasswordUpperCase = 0;
1529 policy.mActivePasswordLowerCase = 0;
1530 policy.mActivePasswordLetters = 0;
1531 policy.mActivePasswordNumeric = 0;
1532 policy.mActivePasswordSymbols = 0;
1533 policy.mActivePasswordNonLetter = 0;
1536 validatePasswordOwnerLocked(policy);
1537 syncDeviceCapabilitiesLocked(policy);
1538 updateMaximumTimeToLockLocked(policy);
1541 static void validateQualityConstant(int quality) {
1543 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
1544 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
1545 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
1546 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
1547 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
1548 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
1549 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
1550 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
1553 throw new IllegalArgumentException("Invalid quality constant: 0x"
1554 + Integer.toHexString(quality));
1557 void validatePasswordOwnerLocked(DevicePolicyData policy) {
1558 if (policy.mPasswordOwner >= 0) {
1559 boolean haveOwner = false;
1560 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1561 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
1567 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
1568 + " no longer active; disabling");
1569 policy.mPasswordOwner = -1;
1575 * Pushes down policy information to the system for any policies related to general device
1576 * capabilities that need to be enforced by lower level services (e.g. Camera services).
1578 void syncDeviceCapabilitiesLocked(DevicePolicyData policy) {
1579 // Ensure the status of the camera is synced down to the system. Interested native services
1580 // should monitor this value and act accordingly.
1581 boolean systemState = SystemProperties.getBoolean(SYSTEM_PROP_DISABLE_CAMERA, false);
1582 boolean cameraDisabled = getCameraDisabled(null, policy.mUserHandle);
1583 if (cameraDisabled != systemState) {
1584 long token = Binder.clearCallingIdentity();
1586 String value = cameraDisabled ? "1" : "0";
1587 if (DBG) Slog.v(LOG_TAG, "Change in camera state ["
1588 + SYSTEM_PROP_DISABLE_CAMERA + "] = " + value);
1589 SystemProperties.set(SYSTEM_PROP_DISABLE_CAMERA, value);
1591 Binder.restoreCallingIdentity(token);
1596 public void systemReady() {
1600 getUserData(UserHandle.USER_OWNER);
1603 // Register an observer for watching for user setup complete.
1604 new SetupContentObserver(mHandler).register(mContext.getContentResolver());
1605 // Initialize the user setup state, to handle the upgrade case.
1606 updateUserSetupComplete();
1608 // Update the screen capture disabled cache in the window manager
1609 List<UserInfo> users = mUserManager.getUsers(true);
1610 final int N = users.size();
1611 for (int i = 0; i < N; i++) {
1612 int userHandle = users.get(i).id;
1613 updateScreenCaptureDisabledInWindowManager(userHandle,
1614 getScreenCaptureDisabled(null, userHandle));
1619 private void cleanUpOldUsers() {
1620 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
1622 Set<Integer> usersWithProfileOwners;
1623 Set<Integer> usersWithData;
1624 synchronized(this) {
1625 usersWithProfileOwners = mDeviceOwner != null
1626 ? mDeviceOwner.getProfileOwnerKeys() : new HashSet<Integer>();
1627 usersWithData = new HashSet<Integer>();
1628 for (int i = 0; i < mUserData.size(); i++) {
1629 usersWithData.add(mUserData.keyAt(i));
1632 List<UserInfo> allUsers = mUserManager.getUsers();
1634 Set<Integer> deletedUsers = new HashSet<Integer>();
1635 deletedUsers.addAll(usersWithProfileOwners);
1636 deletedUsers.addAll(usersWithData);
1637 for (UserInfo userInfo : allUsers) {
1638 deletedUsers.remove(userInfo.id);
1640 for (Integer userId : deletedUsers) {
1641 removeUserData(userId);
1645 private void handlePasswordExpirationNotification(int userHandle) {
1646 synchronized (this) {
1647 final long now = System.currentTimeMillis();
1649 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1650 for (UserInfo ui : profiles) {
1651 int profileUserHandle = ui.id;
1652 final DevicePolicyData policy = getUserData(profileUserHandle);
1653 final int count = policy.mAdminList.size();
1655 for (int i = 0; i < count; i++) {
1656 final ActiveAdmin admin = policy.mAdminList.get(i);
1657 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
1658 && admin.passwordExpirationTimeout > 0L
1659 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
1660 && admin.passwordExpirationDate > 0L) {
1661 sendAdminCommandLocked(admin,
1662 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
1667 setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
1671 private class MonitoringCertNotificationTask extends AsyncTask<Intent, Void, Void> {
1673 protected Void doInBackground(Intent... params) {
1674 int userHandle = params[0].getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
1676 if (userHandle == UserHandle.USER_ALL) {
1677 for (UserInfo userInfo : mUserManager.getUsers()) {
1678 manageNotification(userInfo.getUserHandle());
1681 manageNotification(new UserHandle(userHandle));
1686 private void manageNotification(UserHandle userHandle) {
1687 if (!mUserManager.isUserRunning(userHandle)) {
1691 // Call out to KeyChain to check for user-added CAs
1692 boolean hasCert = false;
1694 KeyChainConnection kcs = KeyChain.bindAsUser(mContext, userHandle);
1696 if (!kcs.getService().getUserCaAliases().getList().isEmpty()) {
1699 } catch (RemoteException e) {
1700 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
1704 } catch (InterruptedException e) {
1705 Thread.currentThread().interrupt();
1706 } catch (RuntimeException e) {
1707 Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
1710 getNotificationManager().cancelAsUser(
1711 null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
1715 // Build and show a warning notification
1718 final String ownerName = getDeviceOwnerName();
1719 if (isManagedProfile(userHandle.getIdentifier())) {
1720 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_administrator);
1721 smallIconId = R.drawable.stat_sys_certificate_info;
1722 } else if (ownerName != null) {
1723 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, ownerName);
1724 smallIconId = R.drawable.stat_sys_certificate_info;
1726 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
1727 smallIconId = android.R.drawable.stat_sys_warning;
1730 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
1731 dialogIntent.setFlags(
1732 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1733 dialogIntent.setPackage("com.android.settings");
1734 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
1735 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, userHandle);
1737 final Context userContext;
1739 userContext = mContext.createPackageContextAsUser("android", 0, userHandle);
1740 } catch (PackageManager.NameNotFoundException e) {
1741 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
1744 final Notification noti = new Notification.Builder(userContext)
1745 .setSmallIcon(smallIconId)
1746 .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning))
1747 .setContentText(contentText)
1748 .setContentIntent(notifyIntent)
1749 .setPriority(Notification.PRIORITY_HIGH)
1751 .setColor(mContext.getResources().getColor(
1752 com.android.internal.R.color.system_notification_accent_color))
1755 getNotificationManager().notifyAsUser(
1756 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
1761 * @param adminReceiver The admin to add
1762 * @param refreshing true = update an active admin, no error
1764 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
1768 setActiveAdmin(adminReceiver, refreshing, userHandle, null);
1771 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
1772 Bundle onEnableData) {
1773 mContext.enforceCallingOrSelfPermission(
1774 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
1775 enforceCrossUserPermission(userHandle);
1777 DevicePolicyData policy = getUserData(userHandle);
1778 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle);
1780 throw new IllegalArgumentException("Bad admin: " + adminReceiver);
1782 synchronized (this) {
1783 long ident = Binder.clearCallingIdentity();
1786 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
1787 throw new IllegalArgumentException("Admin is already added");
1789 ActiveAdmin newAdmin = new ActiveAdmin(info);
1790 policy.mAdminMap.put(adminReceiver, newAdmin);
1791 int replaceIndex = -1;
1792 final int N = policy.mAdminList.size();
1793 for (int i=0; i < N; i++) {
1794 ActiveAdmin oldAdmin = policy.mAdminList.get(i);
1795 if (oldAdmin.info.getComponent().equals(adminReceiver)) {
1800 if (replaceIndex == -1) {
1801 policy.mAdminList.add(newAdmin);
1802 enableIfNecessary(info.getPackageName(), userHandle);
1804 policy.mAdminList.set(replaceIndex, newAdmin);
1806 saveSettingsLocked(userHandle);
1807 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
1808 onEnableData, null);
1810 Binder.restoreCallingIdentity(ident);
1815 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
1819 enforceCrossUserPermission(userHandle);
1820 synchronized (this) {
1821 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
1826 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
1830 enforceCrossUserPermission(userHandle);
1831 synchronized (this) {
1832 DevicePolicyData policyData = getUserData(userHandle);
1833 return policyData.mRemovingAdmins.contains(adminReceiver);
1837 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
1841 enforceCrossUserPermission(userHandle);
1842 synchronized (this) {
1843 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
1844 if (administrator == null) {
1845 throw new SecurityException("No active admin " + adminReceiver);
1847 return administrator.info.usesPolicy(policyId);
1851 @SuppressWarnings("unchecked")
1852 public List<ComponentName> getActiveAdmins(int userHandle) {
1854 return Collections.EMPTY_LIST;
1857 enforceCrossUserPermission(userHandle);
1858 synchronized (this) {
1859 DevicePolicyData policy = getUserData(userHandle);
1860 final int N = policy.mAdminList.size();
1864 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
1865 for (int i=0; i<N; i++) {
1866 res.add(policy.mAdminList.get(i).info.getComponent());
1872 public boolean packageHasActiveAdmins(String packageName, int userHandle) {
1876 enforceCrossUserPermission(userHandle);
1877 synchronized (this) {
1878 DevicePolicyData policy = getUserData(userHandle);
1879 final int N = policy.mAdminList.size();
1880 for (int i=0; i<N; i++) {
1881 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
1889 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
1893 enforceCrossUserPermission(userHandle);
1894 synchronized (this) {
1895 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
1896 if (admin == null) {
1899 if (admin.getUid() != Binder.getCallingUid()) {
1900 // If trying to remove device owner, refuse when the caller is not the owner.
1901 if (isDeviceOwner(adminReceiver.getPackageName())) {
1904 mContext.enforceCallingOrSelfPermission(
1905 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
1907 long ident = Binder.clearCallingIdentity();
1909 removeActiveAdminLocked(adminReceiver, userHandle);
1911 Binder.restoreCallingIdentity(ident);
1916 public void setPasswordQuality(ComponentName who, int quality, int userHandle) {
1920 validateQualityConstant(quality);
1921 enforceCrossUserPermission(userHandle);
1923 synchronized (this) {
1925 throw new NullPointerException("ComponentName is null");
1927 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
1928 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
1929 if (ap.passwordQuality != quality) {
1930 ap.passwordQuality = quality;
1931 saveSettingsLocked(userHandle);
1936 public int getPasswordQuality(ComponentName who, int userHandle) {
1938 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
1940 enforceCrossUserPermission(userHandle);
1941 synchronized (this) {
1942 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
1945 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1946 return admin != null ? admin.passwordQuality : mode;
1949 // Return strictest policy for this user and profiles that are visible from this user.
1950 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1951 for (UserInfo userInfo : profiles) {
1952 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
1953 final int N = policy.mAdminList.size();
1954 for (int i=0; i<N; i++) {
1955 ActiveAdmin admin = policy.mAdminList.get(i);
1956 if (mode < admin.passwordQuality) {
1957 mode = admin.passwordQuality;
1965 public void setPasswordMinimumLength(ComponentName who, int length, int userHandle) {
1969 enforceCrossUserPermission(userHandle);
1970 synchronized (this) {
1972 throw new NullPointerException("ComponentName is null");
1974 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
1975 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
1976 if (ap.minimumPasswordLength != length) {
1977 ap.minimumPasswordLength = length;
1978 saveSettingsLocked(userHandle);
1983 public int getPasswordMinimumLength(ComponentName who, int userHandle) {
1987 enforceCrossUserPermission(userHandle);
1988 synchronized (this) {
1992 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1993 return admin != null ? admin.minimumPasswordLength : length;
1996 // Return strictest policy for this user and profiles that are visible from this user.
1997 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1998 for (UserInfo userInfo : profiles) {
1999 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2000 final int N = policy.mAdminList.size();
2001 for (int i=0; i<N; i++) {
2002 ActiveAdmin admin = policy.mAdminList.get(i);
2003 if (length < admin.minimumPasswordLength) {
2004 length = admin.minimumPasswordLength;
2012 public void setPasswordHistoryLength(ComponentName who, int length, int userHandle) {
2016 enforceCrossUserPermission(userHandle);
2017 synchronized (this) {
2019 throw new NullPointerException("ComponentName is null");
2021 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2022 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2023 if (ap.passwordHistoryLength != length) {
2024 ap.passwordHistoryLength = length;
2025 saveSettingsLocked(userHandle);
2030 public int getPasswordHistoryLength(ComponentName who, int userHandle) {
2034 enforceCrossUserPermission(userHandle);
2035 synchronized (this) {
2039 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2040 return admin != null ? admin.passwordHistoryLength : length;
2043 // Return strictest policy for this user and profiles that are visible from this user.
2044 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2045 for (UserInfo userInfo : profiles) {
2046 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2047 final int N = policy.mAdminList.size();
2048 for (int i = 0; i < N; i++) {
2049 ActiveAdmin admin = policy.mAdminList.get(i);
2050 if (length < admin.passwordHistoryLength) {
2051 length = admin.passwordHistoryLength;
2059 public void setPasswordExpirationTimeout(ComponentName who, long timeout, int userHandle) {
2063 enforceCrossUserPermission(userHandle);
2064 synchronized (this) {
2066 throw new NullPointerException("ComponentName is null");
2069 throw new IllegalArgumentException("Timeout must be >= 0 ms");
2071 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2072 DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
2073 // Calling this API automatically bumps the expiration date
2074 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
2075 ap.passwordExpirationDate = expiration;
2076 ap.passwordExpirationTimeout = timeout;
2078 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
2079 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
2080 .format(new Date(expiration)));
2082 saveSettingsLocked(userHandle);
2083 // in case this is the first one
2084 setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
2089 * Return a single admin's expiration cycle time, or the min of all cycle times.
2090 * Returns 0 if not configured.
2092 public long getPasswordExpirationTimeout(ComponentName who, int userHandle) {
2096 enforceCrossUserPermission(userHandle);
2097 synchronized (this) {
2101 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2102 return admin != null ? admin.passwordExpirationTimeout : timeout;
2105 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2106 for (UserInfo userInfo : profiles) {
2107 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2108 final int N = policy.mAdminList.size();
2109 for (int i = 0; i < N; i++) {
2110 ActiveAdmin admin = policy.mAdminList.get(i);
2111 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
2112 && timeout > admin.passwordExpirationTimeout)) {
2113 timeout = admin.passwordExpirationTimeout;
2122 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
2123 final int userId = UserHandle.getCallingUserId();
2124 List<String> changedProviders = null;
2126 synchronized (this) {
2127 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2128 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2129 if (activeAdmin.crossProfileWidgetProviders == null) {
2130 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
2132 List<String> providers = activeAdmin.crossProfileWidgetProviders;
2133 if (!providers.contains(packageName)) {
2134 providers.add(packageName);
2135 changedProviders = new ArrayList<>(providers);
2136 saveSettingsLocked(userId);
2140 if (changedProviders != null) {
2141 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
2149 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
2150 final int userId = UserHandle.getCallingUserId();
2151 List<String> changedProviders = null;
2153 synchronized (this) {
2154 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2155 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2156 if (activeAdmin.crossProfileWidgetProviders == null) {
2159 List<String> providers = activeAdmin.crossProfileWidgetProviders;
2160 if (providers.remove(packageName)) {
2161 changedProviders = new ArrayList<>(providers);
2162 saveSettingsLocked(userId);
2166 if (changedProviders != null) {
2167 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
2175 public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
2176 synchronized (this) {
2177 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2178 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2179 if (activeAdmin.crossProfileWidgetProviders == null
2180 || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
2183 if (Binder.getCallingUid() == Process.myUid()) {
2184 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
2186 return activeAdmin.crossProfileWidgetProviders;
2192 * Return a single admin's expiration date/time, or the min (soonest) for all admins.
2193 * Returns 0 if not configured.
2195 private long getPasswordExpirationLocked(ComponentName who, int userHandle) {
2199 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2200 return admin != null ? admin.passwordExpirationDate : timeout;
2203 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2204 for (UserInfo userInfo : profiles) {
2205 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2206 final int N = policy.mAdminList.size();
2207 for (int i = 0; i < N; i++) {
2208 ActiveAdmin admin = policy.mAdminList.get(i);
2209 if (timeout == 0L || (admin.passwordExpirationDate != 0
2210 && timeout > admin.passwordExpirationDate)) {
2211 timeout = admin.passwordExpirationDate;
2218 public long getPasswordExpiration(ComponentName who, int userHandle) {
2222 enforceCrossUserPermission(userHandle);
2223 synchronized (this) {
2224 return getPasswordExpirationLocked(who, userHandle);
2228 public void setPasswordMinimumUpperCase(ComponentName who, int length, int userHandle) {
2232 enforceCrossUserPermission(userHandle);
2233 synchronized (this) {
2235 throw new NullPointerException("ComponentName is null");
2237 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2238 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2239 if (ap.minimumPasswordUpperCase != length) {
2240 ap.minimumPasswordUpperCase = length;
2241 saveSettingsLocked(userHandle);
2246 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle) {
2250 enforceCrossUserPermission(userHandle);
2251 synchronized (this) {
2255 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2256 return admin != null ? admin.minimumPasswordUpperCase : length;
2259 // Return strictest policy for this user and profiles that are visible from this user.
2260 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2261 for (UserInfo userInfo : profiles) {
2262 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2263 final int N = policy.mAdminList.size();
2264 for (int i=0; i<N; i++) {
2265 ActiveAdmin admin = policy.mAdminList.get(i);
2266 if (length < admin.minimumPasswordUpperCase) {
2267 length = admin.minimumPasswordUpperCase;
2275 public void setPasswordMinimumLowerCase(ComponentName who, int length, int userHandle) {
2276 enforceCrossUserPermission(userHandle);
2277 synchronized (this) {
2279 throw new NullPointerException("ComponentName is null");
2281 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2282 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2283 if (ap.minimumPasswordLowerCase != length) {
2284 ap.minimumPasswordLowerCase = length;
2285 saveSettingsLocked(userHandle);
2290 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle) {
2294 enforceCrossUserPermission(userHandle);
2295 synchronized (this) {
2299 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2300 return admin != null ? admin.minimumPasswordLowerCase : length;
2303 // Return strictest policy for this user and profiles that are visible from this user.
2304 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2305 for (UserInfo userInfo : profiles) {
2306 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2307 final int N = policy.mAdminList.size();
2308 for (int i=0; i<N; i++) {
2309 ActiveAdmin admin = policy.mAdminList.get(i);
2310 if (length < admin.minimumPasswordLowerCase) {
2311 length = admin.minimumPasswordLowerCase;
2319 public void setPasswordMinimumLetters(ComponentName who, int length, int userHandle) {
2323 enforceCrossUserPermission(userHandle);
2324 synchronized (this) {
2326 throw new NullPointerException("ComponentName is null");
2328 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2329 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2330 if (ap.minimumPasswordLetters != length) {
2331 ap.minimumPasswordLetters = length;
2332 saveSettingsLocked(userHandle);
2337 public int getPasswordMinimumLetters(ComponentName who, int userHandle) {
2341 enforceCrossUserPermission(userHandle);
2342 synchronized (this) {
2346 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2347 return admin != null ? admin.minimumPasswordLetters : length;
2350 // Return strictest policy for this user and profiles that are visible from this user.
2351 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2352 for (UserInfo userInfo : profiles) {
2353 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2354 final int N = policy.mAdminList.size();
2355 for (int i=0; i<N; i++) {
2356 ActiveAdmin admin = policy.mAdminList.get(i);
2357 if (length < admin.minimumPasswordLetters) {
2358 length = admin.minimumPasswordLetters;
2366 public void setPasswordMinimumNumeric(ComponentName who, int length, int userHandle) {
2370 enforceCrossUserPermission(userHandle);
2371 synchronized (this) {
2373 throw new NullPointerException("ComponentName is null");
2375 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2376 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2377 if (ap.minimumPasswordNumeric != length) {
2378 ap.minimumPasswordNumeric = length;
2379 saveSettingsLocked(userHandle);
2384 public int getPasswordMinimumNumeric(ComponentName who, int userHandle) {
2388 enforceCrossUserPermission(userHandle);
2389 synchronized (this) {
2393 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2394 return admin != null ? admin.minimumPasswordNumeric : length;
2397 // Return strictest policy for this user and profiles that are visible from this user.
2398 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2399 for (UserInfo userInfo : profiles) {
2400 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2401 final int N = policy.mAdminList.size();
2402 for (int i = 0; i < N; i++) {
2403 ActiveAdmin admin = policy.mAdminList.get(i);
2404 if (length < admin.minimumPasswordNumeric) {
2405 length = admin.minimumPasswordNumeric;
2413 public void setPasswordMinimumSymbols(ComponentName who, int length, int userHandle) {
2417 enforceCrossUserPermission(userHandle);
2418 synchronized (this) {
2420 throw new NullPointerException("ComponentName is null");
2422 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2423 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2424 if (ap.minimumPasswordSymbols != length) {
2425 ap.minimumPasswordSymbols = length;
2426 saveSettingsLocked(userHandle);
2431 public int getPasswordMinimumSymbols(ComponentName who, int userHandle) {
2435 enforceCrossUserPermission(userHandle);
2436 synchronized (this) {
2440 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2441 return admin != null ? admin.minimumPasswordSymbols : length;
2444 // Return strictest policy for this user and profiles that are visible from this user.
2445 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2446 for (UserInfo userInfo : profiles) {
2447 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2448 final int N = policy.mAdminList.size();
2449 for (int i=0; i<N; i++) {
2450 ActiveAdmin admin = policy.mAdminList.get(i);
2451 if (length < admin.minimumPasswordSymbols) {
2452 length = admin.minimumPasswordSymbols;
2460 public void setPasswordMinimumNonLetter(ComponentName who, int length, int userHandle) {
2464 enforceCrossUserPermission(userHandle);
2465 synchronized (this) {
2467 throw new NullPointerException("ComponentName is null");
2469 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2470 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2471 if (ap.minimumPasswordNonLetter != length) {
2472 ap.minimumPasswordNonLetter = length;
2473 saveSettingsLocked(userHandle);
2478 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle) {
2482 enforceCrossUserPermission(userHandle);
2483 synchronized (this) {
2487 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2488 return admin != null ? admin.minimumPasswordNonLetter : length;
2491 // Return strictest policy for this user and profiles that are visible from this user.
2492 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2493 for (UserInfo userInfo : profiles) {
2494 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2495 final int N = policy.mAdminList.size();
2496 for (int i=0; i<N; i++) {
2497 ActiveAdmin admin = policy.mAdminList.get(i);
2498 if (length < admin.minimumPasswordNonLetter) {
2499 length = admin.minimumPasswordNonLetter;
2507 public boolean isActivePasswordSufficient(int userHandle) {
2511 enforceCrossUserPermission(userHandle);
2513 synchronized (this) {
2515 // The active password is stored in the user that runs the launcher
2516 // If the user this is called from is part of a profile group, that is the parent
2518 UserInfo parent = getProfileParent(userHandle);
2519 int id = (parent == null) ? userHandle : parent.id;
2520 DevicePolicyData policy = getUserDataUnchecked(id);
2522 // This API can only be called by an active device admin,
2523 // so try to retrieve it to check that the caller is one.
2524 getActiveAdminForCallerLocked(null,
2525 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2526 if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle)
2527 || policy.mActivePasswordLength < getPasswordMinimumLength(null, userHandle)) {
2530 if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2533 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(null, userHandle)
2534 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(null, userHandle)
2535 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(null, userHandle)
2536 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(null, userHandle)
2537 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(null, userHandle)
2538 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(null, userHandle);
2542 public int getCurrentFailedPasswordAttempts(int userHandle) {
2543 synchronized (this) {
2544 // This API can only be called by an active device admin,
2545 // so try to retrieve it to check that the caller is one.
2546 getActiveAdminForCallerLocked(null,
2547 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2549 // The active password is stored in the parent.
2550 UserInfo parent = getProfileParent(userHandle);
2551 int id = (parent == null) ? userHandle : parent.id;
2552 DevicePolicyData policy = getUserDataUnchecked(id);
2554 return policy.mFailedPasswordAttempts;
2558 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, int userHandle) {
2562 enforceCrossUserPermission(userHandle);
2563 synchronized (this) {
2565 throw new NullPointerException("ComponentName is null");
2567 // This API can only be called by an active device admin,
2568 // so try to retrieve it to check that the caller is one.
2569 getActiveAdminForCallerLocked(who,
2570 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
2571 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2572 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2573 if (ap.maximumFailedPasswordsForWipe != num) {
2574 ap.maximumFailedPasswordsForWipe = num;
2575 saveSettingsLocked(userHandle);
2581 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle) {
2585 enforceCrossUserPermission(userHandle);
2586 synchronized (this) {
2587 ActiveAdmin admin = (who != null) ? getActiveAdminUncheckedLocked(who, userHandle)
2588 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
2589 return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
2594 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
2596 return UserHandle.USER_NULL;
2598 enforceCrossUserPermission(userHandle);
2599 synchronized (this) {
2600 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
2601 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
2606 * Returns the admin with the strictest policy on maximum failed passwords for this user and all
2607 * profiles that are visible from this user. If the policy for the primary and any other profile
2608 * are equal, it returns the admin for the primary profile.
2609 * Returns {@code null} if none of them have that policy set.
2611 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(int userHandle) {
2613 ActiveAdmin strictestAdmin = null;
2614 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
2615 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2616 for (ActiveAdmin admin : policy.mAdminList) {
2617 if (admin.maximumFailedPasswordsForWipe ==
2618 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
2619 continue; // No max number of failed passwords policy set for this profile.
2622 // We always favor the primary profile if several profiles have the same value set.
2624 count > admin.maximumFailedPasswordsForWipe ||
2625 (userInfo.isPrimary() && count >= admin.maximumFailedPasswordsForWipe)) {
2626 count = admin.maximumFailedPasswordsForWipe;
2627 strictestAdmin = admin;
2631 return strictestAdmin;
2634 public boolean resetPassword(String passwordOrNull, int flags, int userHandle) {
2638 enforceCrossUserPermission(userHandle);
2639 enforceNotManagedProfile(userHandle, "reset the password");
2641 String password = passwordOrNull != null ? passwordOrNull : "";
2644 synchronized (this) {
2645 // This api can only be called by an active device admin,
2646 // so try to retrieve it to check that the caller is one.
2647 getActiveAdminForCallerLocked(null,
2648 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
2649 quality = getPasswordQuality(null, userHandle);
2650 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
2651 int realQuality = LockPatternUtils.computePasswordQuality(password);
2652 if (realQuality < quality
2653 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2654 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
2655 + Integer.toHexString(realQuality)
2656 + " does not meet required quality 0x"
2657 + Integer.toHexString(quality));
2660 quality = Math.max(realQuality, quality);
2662 int length = getPasswordMinimumLength(null, userHandle);
2663 if (password.length() < length) {
2664 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
2665 + " does not meet required length " + length);
2668 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2675 for (int i = 0; i < password.length(); i++) {
2676 char c = password.charAt(i);
2677 if (c >= 'A' && c <= 'Z') {
2680 } else if (c >= 'a' && c <= 'z') {
2683 } else if (c >= '0' && c <= '9') {
2691 int neededLetters = getPasswordMinimumLetters(null, userHandle);
2692 if(letters < neededLetters) {
2693 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
2694 + " does not meet required number of letters " + neededLetters);
2697 int neededNumbers = getPasswordMinimumNumeric(null, userHandle);
2698 if (numbers < neededNumbers) {
2699 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
2700 + " does not meet required number of numerical digits "
2704 int neededLowerCase = getPasswordMinimumLowerCase(null, userHandle);
2705 if (lowercase < neededLowerCase) {
2706 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
2707 + " does not meet required number of lowercase letters "
2711 int neededUpperCase = getPasswordMinimumUpperCase(null, userHandle);
2712 if (uppercase < neededUpperCase) {
2713 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
2714 + " does not meet required number of uppercase letters "
2718 int neededSymbols = getPasswordMinimumSymbols(null, userHandle);
2719 if (symbols < neededSymbols) {
2720 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
2721 + " does not meet required number of special symbols " + neededSymbols);
2724 int neededNonLetter = getPasswordMinimumNonLetter(null, userHandle);
2725 if (nonletter < neededNonLetter) {
2726 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
2727 + " does not meet required number of non-letter characters "
2734 int callingUid = Binder.getCallingUid();
2735 DevicePolicyData policy = getUserData(userHandle);
2736 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
2737 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
2741 // Don't do this with the lock held, because it is going to call
2742 // back in to the service.
2743 long ident = Binder.clearCallingIdentity();
2745 LockPatternUtils utils = new LockPatternUtils(mContext);
2746 if (!TextUtils.isEmpty(password)) {
2747 utils.saveLockPassword(password, quality, false, userHandle);
2749 utils.clearLock(false, userHandle);
2751 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
2753 utils.requireCredentialEntry(UserHandle.USER_ALL);
2755 synchronized (this) {
2756 int newOwner = requireEntry ? callingUid : -1;
2757 if (policy.mPasswordOwner != newOwner) {
2758 policy.mPasswordOwner = newOwner;
2759 saveSettingsLocked(userHandle);
2763 Binder.restoreCallingIdentity(ident);
2769 public void setMaximumTimeToLock(ComponentName who, long timeMs, int userHandle) {
2773 enforceCrossUserPermission(userHandle);
2774 synchronized (this) {
2776 throw new NullPointerException("ComponentName is null");
2778 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2779 DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
2780 if (ap.maximumTimeToUnlock != timeMs) {
2781 ap.maximumTimeToUnlock = timeMs;
2782 saveSettingsLocked(userHandle);
2783 updateMaximumTimeToLockLocked(getUserData(userHandle));
2788 void updateMaximumTimeToLockLocked(DevicePolicyData policy) {
2789 long timeMs = getMaximumTimeToLock(null, policy.mUserHandle);
2790 if (policy.mLastMaximumTimeToLock == timeMs) {
2794 long ident = Binder.clearCallingIdentity();
2797 timeMs = Integer.MAX_VALUE;
2799 // Make sure KEEP_SCREEN_ON is disabled, since that
2800 // would allow bypassing of the maximum time to lock.
2801 Settings.Global.putInt(mContext.getContentResolver(),
2802 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
2805 policy.mLastMaximumTimeToLock = timeMs;
2806 mPowerManagerInternal.setMaximumScreenOffTimeoutFromDeviceAdmin((int)timeMs);
2808 Binder.restoreCallingIdentity(ident);
2812 public long getMaximumTimeToLock(ComponentName who, int userHandle) {
2816 enforceCrossUserPermission(userHandle);
2817 synchronized (this) {
2821 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2822 return admin != null ? admin.maximumTimeToUnlock : time;
2825 // Return strictest policy for this user and profiles that are visible from this user.
2826 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2827 for (UserInfo userInfo : profiles) {
2828 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2829 final int N = policy.mAdminList.size();
2830 for (int i=0; i<N; i++) {
2831 ActiveAdmin admin = policy.mAdminList.get(i);
2833 time = admin.maximumTimeToUnlock;
2834 } else if (admin.maximumTimeToUnlock != 0
2835 && time > admin.maximumTimeToUnlock) {
2836 time = admin.maximumTimeToUnlock;
2844 public void lockNow() {
2848 synchronized (this) {
2849 // This API can only be called by an active device admin,
2850 // so try to retrieve it to check that the caller is one.
2851 getActiveAdminForCallerLocked(null,
2852 DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
2857 private void lockNowUnchecked() {
2858 long ident = Binder.clearCallingIdentity();
2860 // Power off the display
2861 mPowerManager.goToSleep(SystemClock.uptimeMillis(),
2862 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
2863 // Ensure the device is locked
2864 new LockPatternUtils(mContext).requireCredentialEntry(UserHandle.USER_ALL);
2865 getWindowManager().lockNow(null);
2866 } catch (RemoteException e) {
2868 Binder.restoreCallingIdentity(ident);
2872 private boolean isExtStorageEncrypted() {
2873 String state = SystemProperties.get("vold.decrypt");
2874 return !"".equals(state);
2878 public void enforceCanManageCaCerts(ComponentName who) {
2880 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
2882 synchronized (this) {
2883 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2889 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
2890 enforceCanManageCaCerts(admin);
2894 X509Certificate cert = parseCert(certBuffer);
2895 pemCert = Credentials.convertToPem(cert);
2896 } catch (CertificateException ce) {
2897 Log.e(LOG_TAG, "Problem converting cert", ce);
2899 } catch (IOException ioe) {
2900 Log.e(LOG_TAG, "Problem reading cert", ioe);
2904 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
2905 final long id = Binder.clearCallingIdentity();
2907 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
2909 keyChainConnection.getService().installCaCertificate(pemCert);
2911 } catch (RemoteException e) {
2912 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
2914 keyChainConnection.close();
2916 } catch (InterruptedException e1) {
2917 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
2918 Thread.currentThread().interrupt();
2920 Binder.restoreCallingIdentity(id);
2925 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
2926 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
2927 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
2932 public void uninstallCaCert(ComponentName admin, String alias) {
2933 enforceCanManageCaCerts(admin);
2935 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
2936 final long id = Binder.clearCallingIdentity();
2938 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
2940 keyChainConnection.getService().deleteCaCertificate(alias);
2941 } catch (RemoteException e) {
2942 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
2944 keyChainConnection.close();
2946 } catch (InterruptedException ie) {
2947 Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
2948 Thread.currentThread().interrupt();
2950 Binder.restoreCallingIdentity(id);
2955 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, String alias) {
2957 throw new NullPointerException("ComponentName is null");
2959 synchronized (this) {
2960 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2962 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
2963 final long id = Binder.clearCallingIdentity();
2965 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
2967 IKeyChainService keyChain = keyChainConnection.getService();
2968 return keyChain.installKeyPair(privKey, cert, alias);
2969 } catch (RemoteException e) {
2970 Log.e(LOG_TAG, "Installing certificate", e);
2972 keyChainConnection.close();
2974 } catch (InterruptedException e) {
2975 Log.w(LOG_TAG, "Interrupted while installing certificate", e);
2976 Thread.currentThread().interrupt();
2978 Binder.restoreCallingIdentity(id);
2983 private void wipeDataLocked(boolean wipeExtRequested, String reason) {
2984 // If the SD card is encrypted and non-removable, we have to force a wipe.
2985 boolean forceExtWipe = !Environment.isExternalStorageRemovable() && isExtStorageEncrypted();
2987 // Note: we can only do the wipe via ExternalStorageFormatter if the volume is not emulated.
2988 if ((forceExtWipe || wipeExtRequested) && !Environment.isExternalStorageEmulated()) {
2989 Intent intent = new Intent(ExternalStorageFormatter.FORMAT_AND_FACTORY_RESET);
2990 intent.putExtra(ExternalStorageFormatter.EXTRA_ALWAYS_RESET, true);
2991 intent.putExtra(Intent.EXTRA_REASON, reason);
2992 intent.setComponent(ExternalStorageFormatter.COMPONENT_NAME);
2993 mWakeLock.acquire(10000);
2994 mContext.startService(intent);
2997 RecoverySystem.rebootWipeUserData(mContext, reason);
2998 } catch (IOException | SecurityException e) {
2999 Slog.w(LOG_TAG, "Failed requesting data wipe", e);
3005 public void wipeData(int flags, final int userHandle) {
3009 enforceCrossUserPermission(userHandle);
3010 synchronized (this) {
3011 // This API can only be called by an active device admin,
3012 // so try to retrieve it to check that the caller is one.
3013 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
3014 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
3016 final String source;
3017 final ComponentName cname = admin.info.getComponent();
3018 if (cname != null) {
3019 source = cname.flattenToShortString();
3021 source = admin.info.getPackageName();
3024 long ident = Binder.clearCallingIdentity();
3026 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
3027 if (userHandle != UserHandle.USER_OWNER
3028 || !isDeviceOwner(admin.info.getPackageName())) {
3029 throw new SecurityException(
3030 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
3032 PersistentDataBlockManager manager = (PersistentDataBlockManager)
3033 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
3036 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
3037 wipeDeviceOrUserLocked(wipeExtRequested, userHandle,
3038 "DevicePolicyManager.wipeData() from " + source);
3040 Binder.restoreCallingIdentity(ident);
3045 private void wipeDeviceOrUserLocked(boolean wipeExtRequested, final int userHandle, String reason) {
3046 if (userHandle == UserHandle.USER_OWNER) {
3047 wipeDataLocked(wipeExtRequested, reason);
3049 mHandler.post(new Runnable() {
3052 ActivityManagerNative.getDefault().switchUser(UserHandle.USER_OWNER);
3053 if (!mUserManager.removeUser(userHandle)) {
3054 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
3056 } catch (RemoteException re) {
3064 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
3068 enforceCrossUserPermission(userHandle);
3069 mContext.enforceCallingOrSelfPermission(
3070 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3072 synchronized (this) {
3073 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
3074 if (admin == null) {
3076 result.sendResult(null);
3077 } catch (RemoteException e) {
3081 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
3082 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3083 intent.setComponent(admin.info.getComponent());
3084 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
3085 null, new BroadcastReceiver() {
3087 public void onReceive(Context context, Intent intent) {
3089 result.sendResult(getResultExtras(false));
3090 } catch (RemoteException e) {
3093 }, null, Activity.RESULT_OK, null, null);
3097 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
3098 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
3102 enforceCrossUserPermission(userHandle);
3103 enforceNotManagedProfile(userHandle, "set the active password");
3105 mContext.enforceCallingOrSelfPermission(
3106 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3107 DevicePolicyData p = getUserData(userHandle);
3109 validateQualityConstant(quality);
3111 synchronized (this) {
3112 if (p.mActivePasswordQuality != quality || p.mActivePasswordLength != length
3113 || p.mFailedPasswordAttempts != 0 || p.mActivePasswordLetters != letters
3114 || p.mActivePasswordUpperCase != uppercase
3115 || p.mActivePasswordLowerCase != lowercase
3116 || p.mActivePasswordNumeric != numbers
3117 || p.mActivePasswordSymbols != symbols
3118 || p.mActivePasswordNonLetter != nonletter) {
3119 long ident = Binder.clearCallingIdentity();
3121 p.mActivePasswordQuality = quality;
3122 p.mActivePasswordLength = length;
3123 p.mActivePasswordLetters = letters;
3124 p.mActivePasswordLowerCase = lowercase;
3125 p.mActivePasswordUpperCase = uppercase;
3126 p.mActivePasswordNumeric = numbers;
3127 p.mActivePasswordSymbols = symbols;
3128 p.mActivePasswordNonLetter = nonletter;
3129 p.mFailedPasswordAttempts = 0;
3130 saveSettingsLocked(userHandle);
3131 updatePasswordExpirationsLocked(userHandle);
3132 setExpirationAlarmCheckLocked(mContext, p);
3133 sendAdminCommandToSelfAndProfilesLocked(
3134 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
3135 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
3137 Binder.restoreCallingIdentity(ident);
3144 * Called any time the device password is updated. Resets all password expiration clocks.
3146 private void updatePasswordExpirationsLocked(int userHandle) {
3147 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3148 for (UserInfo userInfo : profiles) {
3149 int profileId = userInfo.id;
3150 DevicePolicyData policy = getUserDataUnchecked(profileId);
3151 final int N = policy.mAdminList.size();
3153 for (int i=0; i<N; i++) {
3154 ActiveAdmin admin = policy.mAdminList.get(i);
3155 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
3156 long timeout = admin.passwordExpirationTimeout;
3157 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3158 admin.passwordExpirationDate = expiration;
3162 saveSettingsLocked(profileId);
3166 public void reportFailedPasswordAttempt(int userHandle) {
3167 enforceCrossUserPermission(userHandle);
3168 enforceNotManagedProfile(userHandle, "report failed password attempt");
3169 mContext.enforceCallingOrSelfPermission(
3170 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3172 long ident = Binder.clearCallingIdentity();
3174 boolean wipeData = false;
3176 synchronized (this) {
3177 DevicePolicyData policy = getUserData(userHandle);
3178 policy.mFailedPasswordAttempts++;
3179 saveSettingsLocked(userHandle);
3181 ActiveAdmin strictestAdmin =
3182 getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
3183 int max = strictestAdmin != null
3184 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
3185 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
3186 // Wipe the user/profile associated with the policy that was violated. This
3187 // is not necessarily calling user: if the policy that fired was from a
3188 // managed profile rather than the main user profile, we wipe former only.
3190 identifier = strictestAdmin.getUserHandle().getIdentifier();
3192 sendAdminCommandToSelfAndProfilesLocked(
3193 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
3194 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3198 // Call without holding lock.
3199 wipeDeviceOrUserLocked(false, identifier,
3200 "reportFailedPasswordAttempt()");
3203 Binder.restoreCallingIdentity(ident);
3207 public void reportSuccessfulPasswordAttempt(int userHandle) {
3208 enforceCrossUserPermission(userHandle);
3209 mContext.enforceCallingOrSelfPermission(
3210 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3212 synchronized (this) {
3213 DevicePolicyData policy = getUserData(userHandle);
3214 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
3215 long ident = Binder.clearCallingIdentity();
3217 policy.mFailedPasswordAttempts = 0;
3218 policy.mPasswordOwner = -1;
3219 saveSettingsLocked(userHandle);
3221 sendAdminCommandToSelfAndProfilesLocked(
3222 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
3223 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3226 Binder.restoreCallingIdentity(ident);
3232 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
3233 String exclusionList, int userHandle) {
3237 enforceCrossUserPermission(userHandle);
3238 synchronized(this) {
3240 throw new NullPointerException("ComponentName is null");
3243 // Only check if owner has set global proxy. We don't allow other users to set it.
3244 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3245 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3246 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
3248 // Scan through active admins and find if anyone has already
3249 // set the global proxy.
3250 Set<ComponentName> compSet = policy.mAdminMap.keySet();
3251 for (ComponentName component : compSet) {
3252 ActiveAdmin ap = policy.mAdminMap.get(component);
3253 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
3254 // Another admin already sets the global proxy
3255 // Return it to the caller.
3260 // If the user is not the owner, don't set the global proxy. Fail silently.
3261 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3262 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
3263 + userHandle + " is not permitted.");
3266 if (proxySpec == null) {
3267 admin.specifiesGlobalProxy = false;
3268 admin.globalProxySpec = null;
3269 admin.globalProxyExclusionList = null;
3272 admin.specifiesGlobalProxy = true;
3273 admin.globalProxySpec = proxySpec;
3274 admin.globalProxyExclusionList = exclusionList;
3277 // Reset the global proxy accordingly
3278 // Do this using system permissions, as apps cannot write to secure settings
3279 long origId = Binder.clearCallingIdentity();
3281 resetGlobalProxyLocked(policy);
3283 Binder.restoreCallingIdentity(origId);
3289 public ComponentName getGlobalProxyAdmin(int userHandle) {
3293 enforceCrossUserPermission(userHandle);
3294 synchronized(this) {
3295 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3296 // Scan through active admins and find if anyone has already
3297 // set the global proxy.
3298 final int N = policy.mAdminList.size();
3299 for (int i = 0; i < N; i++) {
3300 ActiveAdmin ap = policy.mAdminList.get(i);
3301 if (ap.specifiesGlobalProxy) {
3302 // Device admin sets the global proxy
3303 // Return it to the caller.
3304 return ap.info.getComponent();
3308 // No device admin sets the global proxy.
3312 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
3313 synchronized (this) {
3314 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3316 long token = Binder.clearCallingIdentity();
3318 ConnectivityManager connectivityManager = (ConnectivityManager)
3319 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
3320 connectivityManager.setGlobalProxy(proxyInfo);
3322 Binder.restoreCallingIdentity(token);
3326 private void resetGlobalProxyLocked(DevicePolicyData policy) {
3327 final int N = policy.mAdminList.size();
3328 for (int i = 0; i < N; i++) {
3329 ActiveAdmin ap = policy.mAdminList.get(i);
3330 if (ap.specifiesGlobalProxy) {
3331 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
3335 // No device admins defining global proxies - reset global proxy settings to none
3336 saveGlobalProxyLocked(null, null);
3339 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
3340 if (exclusionList == null) {
3343 if (proxySpec == null) {
3346 // Remove white spaces
3347 proxySpec = proxySpec.trim();
3348 String data[] = proxySpec.split(":");
3349 int proxyPort = 8080;
3350 if (data.length > 1) {
3352 proxyPort = Integer.parseInt(data[1]);
3353 } catch (NumberFormatException e) {}
3355 exclusionList = exclusionList.trim();
3356 ContentResolver res = mContext.getContentResolver();
3358 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
3359 if (!proxyProperties.isValid()) {
3360 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
3363 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
3364 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
3365 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3370 * Set the storage encryption request for a single admin. Returns the new total request
3371 * status (for all admins).
3373 public int setStorageEncryption(ComponentName who, boolean encrypt, int userHandle) {
3375 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3377 enforceCrossUserPermission(userHandle);
3378 synchronized (this) {
3379 // Check for permissions
3381 throw new NullPointerException("ComponentName is null");
3383 // Only owner can set storage encryption
3384 if (userHandle != UserHandle.USER_OWNER
3385 || UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3386 Slog.w(LOG_TAG, "Only owner is allowed to set storage encryption. User "
3387 + UserHandle.getCallingUserId() + " is not permitted.");
3391 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3392 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
3394 // Quick exit: If the filesystem does not support encryption, we can exit early.
3395 if (!isEncryptionSupported()) {
3396 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3399 // (1) Record the value for the admin so it's sticky
3400 if (ap.encryptionRequested != encrypt) {
3401 ap.encryptionRequested = encrypt;
3402 saveSettingsLocked(userHandle);
3405 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3406 // (2) Compute "max" for all admins
3407 boolean newRequested = false;
3408 final int N = policy.mAdminList.size();
3409 for (int i = 0; i < N; i++) {
3410 newRequested |= policy.mAdminList.get(i).encryptionRequested;
3413 // Notify OS of new request
3414 setEncryptionRequested(newRequested);
3416 // Return the new global request status
3418 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3419 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3424 * Get the current storage encryption request status for a given admin, or aggregate of all
3427 public boolean getStorageEncryption(ComponentName who, int userHandle) {
3431 enforceCrossUserPermission(userHandle);
3432 synchronized (this) {
3433 // Check for permissions if a particular caller is specified
3435 // When checking for a single caller, status is based on caller's request
3436 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
3437 return ap != null ? ap.encryptionRequested : false;
3440 // If no particular caller is specified, return the aggregate set of requests.
3441 // This is short circuited by returning true on the first hit.
3442 DevicePolicyData policy = getUserData(userHandle);
3443 final int N = policy.mAdminList.size();
3444 for (int i = 0; i < N; i++) {
3445 if (policy.mAdminList.get(i).encryptionRequested) {
3454 * Get the current encryption status of the device.
3456 public int getStorageEncryptionStatus(int userHandle) {
3458 // Ok to return current status.
3460 enforceCrossUserPermission(userHandle);
3461 return getEncryptionStatus();
3465 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
3467 private boolean isEncryptionSupported() {
3468 // Note, this can be implemented as
3469 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3470 // But is provided as a separate internal method if there's a faster way to do a
3471 // simple check for supported-or-not.
3472 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3476 * Hook to low-levels: Reporting the current status of encryption.
3477 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} or
3478 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE} or
3479 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
3481 private int getEncryptionStatus() {
3482 String status = SystemProperties.get("ro.crypto.state", "unsupported");
3483 if ("encrypted".equalsIgnoreCase(status)) {
3484 final long token = Binder.clearCallingIdentity();
3486 return LockPatternUtils.isDeviceEncrypted()
3487 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3488 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3490 Binder.restoreCallingIdentity(token);
3492 } else if ("unencrypted".equalsIgnoreCase(status)) {
3493 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3495 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3500 * Hook to low-levels: If needed, record the new admin setting for encryption.
3502 private void setEncryptionRequested(boolean encrypt) {
3507 * Set whether the screen capture is disabled for the user managed by the specified admin.
3509 public void setScreenCaptureDisabled(ComponentName who, int userHandle, boolean disabled) {
3513 enforceCrossUserPermission(userHandle);
3514 synchronized (this) {
3516 throw new NullPointerException("ComponentName is null");
3518 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3519 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3520 if (ap.disableScreenCapture != disabled) {
3521 ap.disableScreenCapture = disabled;
3522 saveSettingsLocked(userHandle);
3523 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
3529 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
3530 * active admin (if given admin is null).
3532 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
3536 synchronized (this) {
3538 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3539 return (admin != null) ? admin.disableScreenCapture : false;
3542 DevicePolicyData policy = getUserData(userHandle);
3543 final int N = policy.mAdminList.size();
3544 for (int i = 0; i < N; i++) {
3545 ActiveAdmin admin = policy.mAdminList.get(i);
3546 if (admin.disableScreenCapture) {
3554 private void updateScreenCaptureDisabledInWindowManager(int userHandle, boolean disabled) {
3555 long ident = Binder.clearCallingIdentity();
3557 getWindowManager().setScreenCaptureDisabled(userHandle, disabled);
3558 } catch (RemoteException e) {
3559 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
3561 Binder.restoreCallingIdentity(ident);
3566 * Set whether auto time is required by the specified admin (must be device owner).
3568 public void setAutoTimeRequired(ComponentName who, int userHandle, boolean required) {
3572 enforceCrossUserPermission(userHandle);
3573 synchronized (this) {
3575 throw new NullPointerException("ComponentName is null");
3577 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3578 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3579 if (admin.requireAutoTime != required) {
3580 admin.requireAutoTime = required;
3581 saveSettingsLocked(userHandle);
3585 // Turn AUTO_TIME on in settings if it is required
3587 long ident = Binder.clearCallingIdentity();
3589 Settings.Global.putInt(mContext.getContentResolver(),
3590 Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
3592 Binder.restoreCallingIdentity(ident);
3598 * Returns whether or not auto time is required by the device owner.
3600 public boolean getAutoTimeRequired() {
3604 synchronized (this) {
3605 ActiveAdmin deviceOwner = getDeviceOwnerAdmin();
3606 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
3611 * The system property used to share the state of the camera. The native camera service
3612 * is expected to read this property and act accordingly.
3614 public static final String SYSTEM_PROP_DISABLE_CAMERA = "sys.secpolicy.camera.disabled";
3617 * Disables all device cameras according to the specified admin.
3619 public void setCameraDisabled(ComponentName who, boolean disabled, int userHandle) {
3623 enforceCrossUserPermission(userHandle);
3624 synchronized (this) {
3626 throw new NullPointerException("ComponentName is null");
3628 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3629 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
3630 if (ap.disableCamera != disabled) {
3631 ap.disableCamera = disabled;
3632 saveSettingsLocked(userHandle);
3634 syncDeviceCapabilitiesLocked(getUserData(userHandle));
3639 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
3642 public boolean getCameraDisabled(ComponentName who, int userHandle) {
3646 synchronized (this) {
3648 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3649 return (admin != null) ? admin.disableCamera : false;
3652 DevicePolicyData policy = getUserData(userHandle);
3653 // Determine whether or not the device camera is disabled for any active admins.
3654 final int N = policy.mAdminList.size();
3655 for (int i = 0; i < N; i++) {
3656 ActiveAdmin admin = policy.mAdminList.get(i);
3657 if (admin.disableCamera) {
3666 * Selectively disable keyguard features.
3668 public void setKeyguardDisabledFeatures(ComponentName who, int which, int userHandle) {
3672 enforceCrossUserPermission(userHandle);
3673 enforceNotManagedProfile(userHandle, "disable keyguard features");
3674 synchronized (this) {
3676 throw new NullPointerException("ComponentName is null");
3678 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3679 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
3680 if (ap.disabledKeyguardFeatures != which) {
3681 ap.disabledKeyguardFeatures = which;
3682 saveSettingsLocked(userHandle);
3684 syncDeviceCapabilitiesLocked(getUserData(userHandle));
3689 * Gets the disabled state for features in keyguard for the given admin,
3690 * or the aggregate of all active admins if who is null.
3692 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle) {
3696 enforceCrossUserPermission(userHandle);
3697 synchronized (this) {
3699 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3700 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
3703 // Determine which keyguard features are disabled for any active admins.
3704 DevicePolicyData policy = getUserData(userHandle);
3705 final int N = policy.mAdminList.size();
3707 for (int i = 0; i < N; i++) {
3708 ActiveAdmin admin = policy.mAdminList.get(i);
3709 which |= admin.disabledKeyguardFeatures;
3716 public boolean setDeviceOwner(String packageName, String ownerName) {
3720 if (packageName == null
3721 || !DeviceOwner.isInstalled(packageName, mContext.getPackageManager())) {
3722 throw new IllegalArgumentException("Invalid package name " + packageName
3723 + " for device owner");
3725 synchronized (this) {
3726 if (!allowedToSetDeviceOwnerOnDevice()) {
3727 throw new IllegalStateException(
3728 "Trying to set device owner but device is already provisioned.");
3731 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
3732 throw new IllegalStateException(
3733 "Trying to set device owner but device owner is already set.");
3736 // Shutting down backup manager service permanently.
3737 long ident = Binder.clearCallingIdentity();
3739 IBackupManager ibm = IBackupManager.Stub.asInterface(
3740 ServiceManager.getService(Context.BACKUP_SERVICE));
3741 ibm.setBackupServiceActive(UserHandle.USER_OWNER, false);
3742 } catch (RemoteException e) {
3743 throw new IllegalStateException("Failed deactivating backup service.", e);
3745 Binder.restoreCallingIdentity(ident);
3748 if (mDeviceOwner == null) {
3749 // Device owner is not set and does not exist, set it.
3750 mDeviceOwner = DeviceOwner.createWithDeviceOwner(packageName, ownerName);
3751 mDeviceOwner.writeOwnerFile();
3754 // Device owner is not set but a profile owner exists, update Device owner state.
3755 mDeviceOwner.setDeviceOwner(packageName, ownerName);
3756 mDeviceOwner.writeOwnerFile();
3763 public boolean isDeviceOwner(String packageName) {
3767 synchronized (this) {
3768 return mDeviceOwner != null
3769 && mDeviceOwner.hasDeviceOwner()
3770 && mDeviceOwner.getDeviceOwnerPackageName().equals(packageName);
3775 public String getDeviceOwner() {
3779 synchronized (this) {
3780 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
3781 return mDeviceOwner.getDeviceOwnerPackageName();
3788 public String getDeviceOwnerName() {
3792 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
3793 synchronized (this) {
3794 if (mDeviceOwner != null) {
3795 return mDeviceOwner.getDeviceOwnerName();
3801 // Returns the active device owner or null if there is no device owner.
3802 private ActiveAdmin getDeviceOwnerAdmin() {
3803 String deviceOwnerPackageName = getDeviceOwner();
3804 if (deviceOwnerPackageName == null) {
3808 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3809 final int n = policy.mAdminList.size();
3810 for (int i = 0; i < n; i++) {
3811 ActiveAdmin admin = policy.mAdminList.get(i);
3812 if (deviceOwnerPackageName.equals(admin.info.getPackageName())) {
3820 public void clearDeviceOwner(String packageName) {
3821 if (packageName == null) {
3822 throw new NullPointerException("packageName is null");
3825 int uid = mContext.getPackageManager().getPackageUid(packageName, 0);
3826 if (uid != Binder.getCallingUid()) {
3827 throw new SecurityException("Invalid packageName");
3829 } catch (NameNotFoundException e) {
3830 throw new SecurityException(e);
3832 if (!isDeviceOwner(packageName)) {
3833 throw new SecurityException("clearDeviceOwner can only be called by the device owner");
3835 synchronized (this) {
3836 long ident = Binder.clearCallingIdentity();
3838 clearUserRestrictions(new UserHandle(UserHandle.USER_OWNER));
3839 if (mDeviceOwner != null) {
3840 mDeviceOwner.clearDeviceOwner();
3841 mDeviceOwner.writeOwnerFile();
3844 Binder.restoreCallingIdentity(ident);
3850 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
3854 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
3856 UserInfo info = mUserManager.getUserInfo(userHandle);
3858 // User doesn't exist.
3859 throw new IllegalArgumentException(
3860 "Attempted to set profile owner for invalid userId: " + userHandle);
3862 if (info.isGuest()) {
3863 throw new IllegalStateException("Cannot set a profile owner on a guest");
3867 || !DeviceOwner.isInstalledForUser(who.getPackageName(), userHandle)) {
3868 throw new IllegalArgumentException("Component " + who
3869 + " not installed for userId:" + userHandle);
3871 synchronized (this) {
3872 // Only SYSTEM_UID can override the userSetupComplete
3873 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID
3874 && hasUserSetupCompleted(userHandle)) {
3875 throw new IllegalStateException(
3876 "Trying to set profile owner but user is already set-up.");
3879 if (mDeviceOwner == null) {
3880 // Device owner state does not exist, create it.
3881 mDeviceOwner = DeviceOwner.createWithProfileOwner(who, ownerName,
3883 mDeviceOwner.writeOwnerFile();
3886 // Device owner already exists, update it.
3887 mDeviceOwner.setProfileOwner(who, ownerName, userHandle);
3888 mDeviceOwner.writeOwnerFile();
3895 public void clearProfileOwner(ComponentName who) {
3899 UserHandle callingUser = Binder.getCallingUserHandle();
3900 // Check if this is the profile owner who is calling
3901 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3902 synchronized (this) {
3903 long ident = Binder.clearCallingIdentity();
3905 clearUserRestrictions(callingUser);
3906 if (mDeviceOwner != null) {
3907 mDeviceOwner.removeProfileOwner(callingUser.getIdentifier());
3908 mDeviceOwner.writeOwnerFile();
3911 Binder.restoreCallingIdentity(ident);
3916 private void clearUserRestrictions(UserHandle userHandle) {
3917 AudioManager audioManager =
3918 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
3919 Bundle userRestrictions = mUserManager.getUserRestrictions();
3920 mUserManager.setUserRestrictions(new Bundle(), userHandle);
3921 if (userRestrictions.getBoolean(UserManager.DISALLOW_ADJUST_VOLUME)) {
3922 audioManager.setMasterMute(false);
3924 if (userRestrictions.getBoolean(UserManager.DISALLOW_UNMUTE_MICROPHONE)) {
3925 audioManager.setMicrophoneMute(false);
3930 public boolean hasUserSetupCompleted() {
3931 return hasUserSetupCompleted(UserHandle.getCallingUserId());
3934 private boolean hasUserSetupCompleted(int userHandle) {
3938 DevicePolicyData policy = getUserData(userHandle);
3939 // If policy is null, return true, else check if the setup has completed.
3940 return policy == null || policy.mUserSetupComplete;
3944 public void setProfileEnabled(ComponentName who) {
3948 final int userHandle = UserHandle.getCallingUserId();
3949 synchronized (this) {
3950 // Check for permissions
3952 throw new NullPointerException("ComponentName is null");
3954 // Check if this is the profile owner who is calling
3955 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3956 int userId = UserHandle.getCallingUserId();
3958 long id = Binder.clearCallingIdentity();
3960 mUserManager.setUserEnabled(userId);
3961 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
3962 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle));
3963 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3964 Intent.FLAG_RECEIVER_FOREGROUND);
3965 // TODO This should send to parent of profile (which is always owner at the moment).
3966 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
3968 restoreCallingIdentity(id);
3974 public void setProfileName(ComponentName who, String profileName) {
3975 int userId = UserHandle.getCallingUserId();
3978 throw new NullPointerException("ComponentName is null");
3981 // Check if this is the profile owner (includes device owner).
3982 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3984 long id = Binder.clearCallingIdentity();
3986 mUserManager.setUserName(userId, profileName);
3988 restoreCallingIdentity(id);
3993 public ComponentName getProfileOwner(int userHandle) {
3998 synchronized (this) {
3999 if (mDeviceOwner != null) {
4000 return mDeviceOwner.getProfileOwnerComponent(userHandle);
4006 // Returns the active profile owner for this user or null if the current user has no
4008 private ActiveAdmin getProfileOwnerAdmin(int userHandle) {
4009 ComponentName profileOwner =
4010 mDeviceOwner != null ? mDeviceOwner.getProfileOwnerComponent(userHandle) : null;
4011 if (profileOwner == null) {
4015 DevicePolicyData policy = getUserData(userHandle);
4016 final int n = policy.mAdminList.size();
4017 for (int i = 0; i < n; i++) {
4018 ActiveAdmin admin = policy.mAdminList.get(i);
4019 if (profileOwner.equals(admin.info.getComponent())) {
4027 public String getProfileOwnerName(int userHandle) {
4031 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
4033 synchronized (this) {
4034 if (mDeviceOwner != null) {
4035 return mDeviceOwner.getProfileOwnerName(userHandle);
4042 * Device owner can only be set on an unprovisioned device, unless it was initiated by "adb", in
4043 * which case we allow it if no account is associated with the device.
4045 private boolean allowedToSetDeviceOwnerOnDevice() {
4046 int callingId = Binder.getCallingUid();
4047 if (callingId == Process.SHELL_UID || callingId == Process.ROOT_UID) {
4048 return AccountManager.get(mContext).getAccounts().length == 0;
4050 return !hasUserSetupCompleted(UserHandle.USER_OWNER);
4054 private void enforceCrossUserPermission(int userHandle) {
4055 if (userHandle < 0) {
4056 throw new IllegalArgumentException("Invalid userId " + userHandle);
4058 final int callingUid = Binder.getCallingUid();
4059 if (userHandle == UserHandle.getUserId(callingUid)) return;
4060 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4061 mContext.enforceCallingOrSelfPermission(
4062 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have"
4063 + " INTERACT_ACROSS_USERS_FULL permission");
4067 private void enforceSystemProcess(String message) {
4068 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4069 throw new SecurityException(message);
4073 private void enforceNotManagedProfile(int userHandle, String message) {
4074 if(isManagedProfile(userHandle)) {
4075 throw new SecurityException("You can not " + message + " for a managed profile. ");
4079 private UserInfo getProfileParent(int userHandle) {
4080 long ident = Binder.clearCallingIdentity();
4082 return mUserManager.getProfileParent(userHandle);
4084 Binder.restoreCallingIdentity(ident);
4088 private boolean isManagedProfile(int userHandle) {
4089 long ident = Binder.clearCallingIdentity();
4091 return mUserManager.getUserInfo(userHandle).isManagedProfile();
4093 Binder.restoreCallingIdentity(ident);
4097 private void enableIfNecessary(String packageName, int userId) {
4099 IPackageManager ipm = AppGlobals.getPackageManager();
4100 ApplicationInfo ai = ipm.getApplicationInfo(packageName,
4101 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
4103 if (ai.enabledSetting
4104 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
4105 ipm.setApplicationEnabledSetting(packageName,
4106 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
4107 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
4109 } catch (RemoteException e) {
4114 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4115 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4116 != PackageManager.PERMISSION_GRANTED) {
4118 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
4119 + Binder.getCallingPid()
4120 + ", uid=" + Binder.getCallingUid());
4124 final Printer p = new PrintWriterPrinter(pw);
4126 synchronized (this) {
4127 p.println("Current Device Policy Manager state:");
4129 int userCount = mUserData.size();
4130 for (int u = 0; u < userCount; u++) {
4131 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
4132 p.println(" Enabled Device Admins (User " + policy.mUserHandle + "):");
4133 final int N = policy.mAdminList.size();
4134 for (int i=0; i<N; i++) {
4135 ActiveAdmin ap = policy.mAdminList.get(i);
4137 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
4142 if (!policy.mRemovingAdmins.isEmpty()) {
4143 p.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
4144 + policy.mRemovingAdmins);
4148 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
4154 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
4155 ComponentName activity) {
4156 final int userHandle = UserHandle.getCallingUserId();
4158 synchronized (this) {
4160 throw new NullPointerException("ComponentName is null");
4162 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4164 IPackageManager pm = AppGlobals.getPackageManager();
4165 long id = Binder.clearCallingIdentity();
4167 pm.addPersistentPreferredActivity(filter, activity, userHandle);
4168 } catch (RemoteException re) {
4171 restoreCallingIdentity(id);
4177 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
4178 final int userHandle = UserHandle.getCallingUserId();
4180 synchronized (this) {
4182 throw new NullPointerException("ComponentName is null");
4184 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4186 IPackageManager pm = AppGlobals.getPackageManager();
4187 long id = Binder.clearCallingIdentity();
4189 pm.clearPackagePersistentPreferredActivities(packageName, userHandle);
4190 } catch (RemoteException re) {
4193 restoreCallingIdentity(id);
4199 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
4200 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4202 synchronized (this) {
4204 throw new NullPointerException("ComponentName is null");
4206 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4208 long id = Binder.clearCallingIdentity();
4210 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
4212 restoreCallingIdentity(id);
4217 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
4218 PersistableBundle args, int userHandle) {
4222 enforceCrossUserPermission(userHandle);
4223 enforceNotManagedProfile(userHandle, "set trust agent configuration");
4224 synchronized (this) {
4225 if (admin == null) {
4226 throw new NullPointerException("admin is null");
4228 if (agent == null) {
4229 throw new NullPointerException("agent is null");
4231 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
4232 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
4233 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
4234 saveSettingsLocked(userHandle);
4235 syncDeviceCapabilitiesLocked(getUserData(userHandle));
4239 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
4240 ComponentName agent, int userHandle) {
4244 enforceCrossUserPermission(userHandle);
4245 if (agent == null) {
4246 throw new NullPointerException("agent is null");
4249 synchronized (this) {
4250 final String componentName = agent.flattenToString();
4251 if (admin != null) {
4252 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle);
4253 if (ap == null) return null;
4254 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
4255 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
4256 List<PersistableBundle> result = new ArrayList<PersistableBundle>();
4257 result.add(trustAgentInfo.options);
4261 // Return strictest policy for this user and profiles that are visible from this user.
4262 final List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
4263 List<PersistableBundle> result = null;
4265 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
4266 // of the options. If any admin doesn't have options, discard options for the rest
4268 boolean allAdminsHaveOptions = true;
4269 for (UserInfo userInfo : profiles) {
4270 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4271 final int N = policy.mAdminList.size();
4272 for (int i=0; i < N; i++) {
4273 final ActiveAdmin active = policy.mAdminList.get(i);
4274 final boolean disablesTrust = (active.disabledKeyguardFeatures
4275 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
4276 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
4277 if (info != null && info.options != null && !info.options.isEmpty()) {
4278 if (disablesTrust) {
4279 if (result == null) {
4280 result = new ArrayList<PersistableBundle>();
4282 result.add(info.options);
4284 Log.w(LOG_TAG, "Ignoring admin " + active.info
4285 + " because it has trust options but doesn't declare "
4286 + "KEYGUARD_DISABLE_TRUST_AGENTS");
4288 } else if (disablesTrust) {
4289 allAdminsHaveOptions = false;
4294 return allAdminsHaveOptions ? result : null;
4299 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
4300 synchronized (this) {
4302 throw new NullPointerException("ComponentName is null");
4304 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4306 int userHandle = UserHandle.getCallingUserId();
4307 DevicePolicyData userData = getUserData(userHandle);
4308 userData.mRestrictionsProvider = permissionProvider;
4309 saveSettingsLocked(userHandle);
4314 public ComponentName getRestrictionsProvider(int userHandle) {
4315 synchronized (this) {
4316 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4317 throw new SecurityException("Only the system can query the permission provider");
4319 DevicePolicyData userData = getUserData(userHandle);
4320 return userData != null ? userData.mRestrictionsProvider : null;
4324 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
4325 int callingUserId = UserHandle.getCallingUserId();
4326 synchronized (this) {
4328 throw new NullPointerException("ComponentName is null");
4330 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4332 IPackageManager pm = AppGlobals.getPackageManager();
4333 long id = Binder.clearCallingIdentity();
4335 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
4336 pm.addCrossProfileIntentFilter(filter, who.getPackageName(),
4337 mContext.getUserId(), callingUserId, UserHandle.USER_OWNER, 0);
4339 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
4340 pm.addCrossProfileIntentFilter(filter, who.getPackageName(),
4341 mContext.getUserId(), UserHandle.USER_OWNER, callingUserId, 0);
4343 } catch (RemoteException re) {
4346 restoreCallingIdentity(id);
4351 public void clearCrossProfileIntentFilters(ComponentName who) {
4352 int callingUserId = UserHandle.getCallingUserId();
4353 synchronized (this) {
4355 throw new NullPointerException("ComponentName is null");
4357 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4358 IPackageManager pm = AppGlobals.getPackageManager();
4359 long id = Binder.clearCallingIdentity();
4361 pm.clearCrossProfileIntentFilters(callingUserId, who.getPackageName(),
4363 // If we want to support multiple managed profiles, we will have to only remove
4364 // those that have callingUserId as their target.
4365 pm.clearCrossProfileIntentFilters(UserHandle.USER_OWNER, who.getPackageName(),
4367 } catch (RemoteException re) {
4370 restoreCallingIdentity(id);
4376 * @return true if all packages in enabledPackages are either in the list
4377 * permittedList or are a system app.
4379 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
4380 List<String> permittedList) {
4381 int userIdToCheck = UserHandle.getCallingUserId();
4382 long id = Binder.clearCallingIdentity();
4384 // If we have an enabled packages list for a managed profile the packages
4385 // we should check are installed for the parent user.
4386 UserInfo user = mUserManager.getUserInfo(userIdToCheck);
4387 if (user.isManagedProfile()) {
4388 userIdToCheck = user.profileGroupId;
4391 IPackageManager pm = AppGlobals.getPackageManager();
4392 for (String enabledPackage : enabledPackages) {
4393 boolean systemService = false;
4395 ApplicationInfo applicationInfo = pm.getApplicationInfo(enabledPackage,
4396 PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
4397 systemService = (applicationInfo.flags
4398 & ApplicationInfo.FLAG_SYSTEM) != 0;
4399 } catch (RemoteException e) {
4400 Log.i(LOG_TAG, "Can't talk to package managed", e);
4402 if (!systemService && !permittedList.contains(enabledPackage)) {
4407 restoreCallingIdentity(id);
4412 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
4413 // Not using AccessibilityManager.getInstance because that guesses
4414 // at the user you require based on callingUid and caches for a given
4416 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
4417 IAccessibilityManager service = iBinder == null
4418 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
4419 return new AccessibilityManager(mContext, service, userId);
4423 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
4428 throw new NullPointerException("ComponentName is null");
4431 if (packageList != null) {
4432 int userId = UserHandle.getCallingUserId();
4433 List<AccessibilityServiceInfo> enabledServices = null;
4434 long id = Binder.clearCallingIdentity();
4436 UserInfo user = mUserManager.getUserInfo(userId);
4437 if (user.isManagedProfile()) {
4438 userId = user.profileGroupId;
4440 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
4441 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
4442 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
4444 restoreCallingIdentity(id);
4447 if (enabledServices != null) {
4448 List<String> enabledPackages = new ArrayList<String>();
4449 for (AccessibilityServiceInfo service : enabledServices) {
4450 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
4452 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
4453 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
4454 + "because it contains already enabled accesibility services.");
4460 synchronized (this) {
4461 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4462 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4463 admin.permittedAccessiblityServices = packageList;
4464 saveSettingsLocked(UserHandle.getCallingUserId());
4470 public List getPermittedAccessibilityServices(ComponentName who) {
4476 throw new NullPointerException("ComponentName is null");
4479 synchronized (this) {
4480 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4481 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4482 return admin.permittedAccessiblityServices;
4487 public List getPermittedAccessibilityServicesForUser(int userId) {
4491 synchronized (this) {
4492 List<String> result = null;
4493 // If we have multiple profiles we return the intersection of the
4494 // permitted lists. This can happen in cases where we have a device
4495 // and profile owner.
4496 List<UserInfo> profiles = mUserManager.getProfiles(userId);
4497 final int PROFILES_SIZE = profiles.size();
4498 for (int i = 0; i < PROFILES_SIZE; ++i) {
4499 // Just loop though all admins, only device or profiles
4500 // owners can have permitted lists set.
4501 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
4502 final int N = policy.mAdminList.size();
4503 for (int j = 0; j < N; j++) {
4504 ActiveAdmin admin = policy.mAdminList.get(j);
4505 List<String> fromAdmin = admin.permittedAccessiblityServices;
4506 if (fromAdmin != null) {
4507 if (result == null) {
4508 result = new ArrayList<String>(fromAdmin);
4510 result.retainAll(fromAdmin);
4516 // If we have a permitted list add all system accessibility services.
4517 if (result != null) {
4518 long id = Binder.clearCallingIdentity();
4520 UserInfo user = mUserManager.getUserInfo(userId);
4521 if (user.isManagedProfile()) {
4522 userId = user.profileGroupId;
4524 AccessibilityManager accessibilityManager =
4525 getAccessibilityManagerForUser(userId);
4526 List<AccessibilityServiceInfo> installedServices =
4527 accessibilityManager.getInstalledAccessibilityServiceList();
4529 IPackageManager pm = AppGlobals.getPackageManager();
4530 if (installedServices != null) {
4531 for (AccessibilityServiceInfo service : installedServices) {
4532 String packageName = service.getResolveInfo().serviceInfo.packageName;
4534 ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName,
4535 PackageManager.GET_UNINSTALLED_PACKAGES, userId);
4536 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4537 result.add(packageName);
4539 } catch (RemoteException e) {
4540 Log.i(LOG_TAG, "Accessibility service in missing package", e);
4545 restoreCallingIdentity(id);
4553 private boolean checkCallerIsCurrentUserOrProfile() {
4554 int callingUserId = UserHandle.getCallingUserId();
4555 long token = Binder.clearCallingIdentity();
4557 UserInfo currentUser;
4558 UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
4560 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
4561 } catch (RemoteException e) {
4562 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
4566 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
4567 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
4568 + "of a user that isn't the foreground user.");
4571 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
4572 Slog.e(LOG_TAG, "Cannot set permitted input methods "
4573 + "of a user that isn't the foreground user.");
4577 Binder.restoreCallingIdentity(token);
4583 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
4588 throw new NullPointerException("ComponentName is null");
4591 // TODO When InputMethodManager supports per user calls remove
4592 // this restriction.
4593 if (!checkCallerIsCurrentUserOrProfile()) {
4597 if (packageList != null) {
4598 // InputMethodManager fetches input methods for current user.
4599 // So this can only be set when calling user is the current user
4600 // or parent is current user in case of managed profiles.
4601 InputMethodManager inputMethodManager = (InputMethodManager) mContext
4602 .getSystemService(Context.INPUT_METHOD_SERVICE);
4603 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
4605 if (enabledImes != null) {
4606 List<String> enabledPackages = new ArrayList<String>();
4607 for (InputMethodInfo ime : enabledImes) {
4608 enabledPackages.add(ime.getPackageName());
4610 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
4611 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
4612 + "because it contains already enabled input method.");
4618 synchronized (this) {
4619 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4620 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4621 admin.permittedInputMethods = packageList;
4622 saveSettingsLocked(UserHandle.getCallingUserId());
4628 public List getPermittedInputMethods(ComponentName who) {
4634 throw new NullPointerException("ComponentName is null");
4637 synchronized (this) {
4638 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4639 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4640 return admin.permittedInputMethods;
4645 public List getPermittedInputMethodsForCurrentUser() {
4646 UserInfo currentUser;
4648 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
4649 } catch (RemoteException e) {
4650 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
4651 // Activity managed is dead, just allow all IMEs
4655 int userId = currentUser.id;
4656 synchronized (this) {
4657 List<String> result = null;
4658 // If we have multiple profiles we return the intersection of the
4659 // permitted lists. This can happen in cases where we have a device
4660 // and profile owner.
4661 List<UserInfo> profiles = mUserManager.getProfiles(userId);
4662 final int PROFILES_SIZE = profiles.size();
4663 for (int i = 0; i < PROFILES_SIZE; ++i) {
4664 // Just loop though all admins, only device or profiles
4665 // owners can have permitted lists set.
4666 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
4667 final int N = policy.mAdminList.size();
4668 for (int j = 0; j < N; j++) {
4669 ActiveAdmin admin = policy.mAdminList.get(j);
4670 List<String> fromAdmin = admin.permittedInputMethods;
4671 if (fromAdmin != null) {
4672 if (result == null) {
4673 result = new ArrayList<String>(fromAdmin);
4675 result.retainAll(fromAdmin);
4681 // If we have a permitted list add all system input methods.
4682 if (result != null) {
4683 InputMethodManager inputMethodManager = (InputMethodManager) mContext
4684 .getSystemService(Context.INPUT_METHOD_SERVICE);
4685 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
4686 long id = Binder.clearCallingIdentity();
4688 IPackageManager pm = AppGlobals.getPackageManager();
4690 for (InputMethodInfo ime : imes) {
4691 String packageName = ime.getPackageName();
4693 ApplicationInfo applicationInfo = pm.getApplicationInfo(
4694 packageName, PackageManager.GET_UNINSTALLED_PACKAGES,
4696 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4697 result.add(packageName);
4699 } catch (RemoteException e) {
4700 Log.i(LOG_TAG, "Input method for missing package", e);
4705 restoreCallingIdentity(id);
4713 public UserHandle createUser(ComponentName who, String name) {
4714 synchronized (this) {
4716 throw new NullPointerException("ComponentName is null");
4718 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4720 long id = Binder.clearCallingIdentity();
4722 UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */);
4723 if (userInfo != null) {
4724 return userInfo.getUserHandle();
4728 restoreCallingIdentity(id);
4734 public UserHandle createAndInitializeUser(ComponentName who, String name,
4735 String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) {
4736 UserHandle user = createUser(who, name);
4740 long id = Binder.clearCallingIdentity();
4742 String profileOwnerPkg = profileOwnerComponent.getPackageName();
4743 final IPackageManager ipm = AppGlobals.getPackageManager();
4744 IActivityManager activityManager = ActivityManagerNative.getDefault();
4747 // Install the profile owner if not present.
4748 if (!ipm.isPackageAvailable(profileOwnerPkg, user.getIdentifier())) {
4749 ipm.installExistingPackageAsUser(profileOwnerPkg, user.getIdentifier());
4752 // Start user in background.
4753 activityManager.startUserInBackground(user.getIdentifier());
4754 } catch (RemoteException e) {
4755 Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e);
4758 setActiveAdmin(profileOwnerComponent, true, user.getIdentifier(), adminExtras);
4759 setProfileOwner(profileOwnerComponent, ownerName, user.getIdentifier());
4762 restoreCallingIdentity(id);
4767 public boolean removeUser(ComponentName who, UserHandle userHandle) {
4768 synchronized (this) {
4770 throw new NullPointerException("ComponentName is null");
4772 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4774 long id = Binder.clearCallingIdentity();
4776 return mUserManager.removeUser(userHandle.getIdentifier());
4778 restoreCallingIdentity(id);
4784 public boolean switchUser(ComponentName who, UserHandle userHandle) {
4785 synchronized (this) {
4787 throw new NullPointerException("ComponentName is null");
4789 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4791 long id = Binder.clearCallingIdentity();
4793 int userId = UserHandle.USER_OWNER;
4794 if (userHandle != null) {
4795 userId = userHandle.getIdentifier();
4797 return ActivityManagerNative.getDefault().switchUser(userId);
4798 } catch (RemoteException e) {
4799 Log.e(LOG_TAG, "Couldn't switch user", e);
4802 restoreCallingIdentity(id);
4808 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
4809 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4811 synchronized (this) {
4813 throw new NullPointerException("ComponentName is null");
4815 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4817 long id = Binder.clearCallingIdentity();
4819 return mUserManager.getApplicationRestrictions(packageName, userHandle);
4821 restoreCallingIdentity(id);
4827 public void setUserRestriction(ComponentName who, String key, boolean enabled) {
4828 final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
4829 final int userHandle = user.getIdentifier();
4830 synchronized (this) {
4832 throw new NullPointerException("ComponentName is null");
4834 ActiveAdmin activeAdmin =
4835 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4836 boolean isDeviceOwner = isDeviceOwner(activeAdmin.info.getPackageName());
4837 if (!isDeviceOwner && userHandle != UserHandle.USER_OWNER
4838 && DEVICE_OWNER_USER_RESTRICTIONS.contains(key)) {
4839 throw new SecurityException("Profile owners cannot set user restriction " + key);
4841 boolean alreadyRestricted = mUserManager.hasUserRestriction(key, user);
4843 IAudioService iAudioService = null;
4844 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)
4845 || UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
4846 iAudioService = IAudioService.Stub.asInterface(
4847 ServiceManager.getService(Context.AUDIO_SERVICE));
4850 if (enabled && !alreadyRestricted) {
4852 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
4853 iAudioService.setMicrophoneMute(true, who.getPackageName());
4854 } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
4855 iAudioService.setMasterMute(true, 0, who.getPackageName(), null);
4857 } catch (RemoteException re) {
4858 Slog.e(LOG_TAG, "Failed to talk to AudioService.", re);
4861 long id = Binder.clearCallingIdentity();
4863 if (enabled && !alreadyRestricted) {
4864 if (UserManager.DISALLOW_CONFIG_WIFI.equals(key)) {
4865 Settings.Secure.putIntForUser(mContext.getContentResolver(),
4866 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0,
4868 } else if (UserManager.DISALLOW_USB_FILE_TRANSFER.equals(key)) {
4869 UsbManager manager =
4870 (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
4871 manager.setCurrentFunction("none", false);
4872 } else if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
4873 Settings.Secure.putIntForUser(mContext.getContentResolver(),
4874 Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF,
4876 Settings.Secure.putStringForUser(mContext.getContentResolver(),
4877 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, "",
4879 } else if (UserManager.DISALLOW_DEBUGGING_FEATURES.equals(key)) {
4880 // Only disable adb if changing for primary user, since it is global
4881 if (userHandle == UserHandle.USER_OWNER) {
4882 Settings.Global.putStringForUser(mContext.getContentResolver(),
4883 Settings.Global.ADB_ENABLED, "0", userHandle);
4885 } else if (UserManager.ENSURE_VERIFY_APPS.equals(key)) {
4886 Settings.Global.putStringForUser(mContext.getContentResolver(),
4887 Settings.Global.PACKAGE_VERIFIER_ENABLE, "1",
4889 Settings.Global.putStringForUser(mContext.getContentResolver(),
4890 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1",
4892 } else if (UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES.equals(key)) {
4893 Settings.Secure.putIntForUser(mContext.getContentResolver(),
4894 Settings.Secure.INSTALL_NON_MARKET_APPS, 0,
4898 mUserManager.setUserRestriction(key, enabled, user);
4900 restoreCallingIdentity(id);
4902 if (!enabled && alreadyRestricted) {
4904 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
4905 iAudioService.setMicrophoneMute(false, who.getPackageName());
4906 } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
4907 iAudioService.setMasterMute(false, 0, who.getPackageName(), null);
4909 } catch (RemoteException re) {
4910 Slog.e(LOG_TAG, "Failed to talk to AudioService.", re);
4913 sendChangedNotification(userHandle);
4918 public boolean setApplicationHidden(ComponentName who, String packageName,
4920 int callingUserId = UserHandle.getCallingUserId();
4921 synchronized (this) {
4923 throw new NullPointerException("ComponentName is null");
4925 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4927 long id = Binder.clearCallingIdentity();
4929 IPackageManager pm = AppGlobals.getPackageManager();
4930 return pm.setApplicationHiddenSettingAsUser(packageName, hidden, callingUserId);
4931 } catch (RemoteException re) {
4933 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
4935 restoreCallingIdentity(id);
4942 public boolean isApplicationHidden(ComponentName who, String packageName) {
4943 int callingUserId = UserHandle.getCallingUserId();
4944 synchronized (this) {
4946 throw new NullPointerException("ComponentName is null");
4948 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4950 long id = Binder.clearCallingIdentity();
4952 IPackageManager pm = AppGlobals.getPackageManager();
4953 return pm.getApplicationHiddenSettingAsUser(packageName, callingUserId);
4954 } catch (RemoteException re) {
4956 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
4958 restoreCallingIdentity(id);
4965 public void enableSystemApp(ComponentName who, String packageName) {
4966 synchronized (this) {
4968 throw new NullPointerException("ComponentName is null");
4971 // This API can only be called by an active device admin,
4972 // so try to retrieve it to check that the caller is one.
4973 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4975 int userId = UserHandle.getCallingUserId();
4976 long id = Binder.clearCallingIdentity();
4980 Slog.v(LOG_TAG, "installing " + packageName + " for "
4984 UserManager um = UserManager.get(mContext);
4985 UserInfo primaryUser = um.getProfileParent(userId);
4987 // Call did not come from a managed profile
4988 if (primaryUser == null) {
4989 primaryUser = um.getUserInfo(userId);
4992 IPackageManager pm = AppGlobals.getPackageManager();
4993 if (!isSystemApp(pm, packageName, primaryUser.id)) {
4994 throw new IllegalArgumentException("Only system apps can be enabled this way.");
4998 pm.installExistingPackageAsUser(packageName, userId);
5000 } catch (RemoteException re) {
5002 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
5004 restoreCallingIdentity(id);
5010 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
5011 synchronized (this) {
5013 throw new NullPointerException("ComponentName is null");
5016 // This API can only be called by an active device admin,
5017 // so try to retrieve it to check that the caller is one.
5018 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5020 int userId = UserHandle.getCallingUserId();
5021 long id = Binder.clearCallingIdentity();
5024 UserManager um = UserManager.get(mContext);
5025 UserInfo primaryUser = um.getProfileParent(userId);
5027 // Call did not come from a managed profile.
5028 if (primaryUser == null) {
5029 primaryUser = um.getUserInfo(userId);
5032 IPackageManager pm = AppGlobals.getPackageManager();
5033 List<ResolveInfo> activitiesToEnable = pm.queryIntentActivities(intent,
5034 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5038 if (DBG) Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
5039 int numberOfAppsInstalled = 0;
5040 if (activitiesToEnable != null) {
5041 for (ResolveInfo info : activitiesToEnable) {
5042 if (info.activityInfo != null) {
5044 if (!isSystemApp(pm, info.activityInfo.packageName, primaryUser.id)) {
5045 throw new IllegalArgumentException(
5046 "Only system apps can be enabled this way.");
5050 numberOfAppsInstalled++;
5051 pm.installExistingPackageAsUser(info.activityInfo.packageName, userId);
5055 return numberOfAppsInstalled;
5056 } catch (RemoteException e) {
5058 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
5061 restoreCallingIdentity(id);
5066 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
5067 throws RemoteException {
5068 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
5070 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0;
5074 public void setAccountManagementDisabled(ComponentName who, String accountType,
5079 synchronized (this) {
5081 throw new NullPointerException("ComponentName is null");
5083 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5084 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5086 ap.accountTypesWithManagementDisabled.add(accountType);
5088 ap.accountTypesWithManagementDisabled.remove(accountType);
5090 saveSettingsLocked(UserHandle.getCallingUserId());
5095 public String[] getAccountTypesWithManagementDisabled() {
5096 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
5100 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
5101 enforceCrossUserPermission(userId);
5105 synchronized (this) {
5106 DevicePolicyData policy = getUserData(userId);
5107 final int N = policy.mAdminList.size();
5108 HashSet<String> resultSet = new HashSet<String>();
5109 for (int i = 0; i < N; i++) {
5110 ActiveAdmin admin = policy.mAdminList.get(i);
5111 resultSet.addAll(admin.accountTypesWithManagementDisabled);
5113 return resultSet.toArray(new String[resultSet.size()]);
5118 public void setUninstallBlocked(ComponentName who, String packageName,
5119 boolean uninstallBlocked) {
5120 final int userId = UserHandle.getCallingUserId();
5122 synchronized (this) {
5124 throw new NullPointerException("ComponentName is null");
5126 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5128 long id = Binder.clearCallingIdentity();
5130 IPackageManager pm = AppGlobals.getPackageManager();
5131 pm.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
5132 } catch (RemoteException re) {
5133 // Shouldn't happen.
5134 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
5136 restoreCallingIdentity(id);
5142 public boolean isUninstallBlocked(ComponentName who, String packageName) {
5143 // This function should return true if and only if the package is blocked by
5144 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
5145 // when the package is a system app, or when it is an active device admin.
5146 final int userId = UserHandle.getCallingUserId();
5148 synchronized (this) {
5150 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5153 long id = Binder.clearCallingIdentity();
5155 IPackageManager pm = AppGlobals.getPackageManager();
5156 return pm.getBlockUninstallForUser(packageName, userId);
5157 } catch (RemoteException re) {
5158 // Shouldn't happen.
5159 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
5161 restoreCallingIdentity(id);
5168 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
5172 synchronized (this) {
5174 throw new NullPointerException("ComponentName is null");
5176 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5177 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5178 if (admin.disableCallerId != disabled) {
5179 admin.disableCallerId = disabled;
5180 saveSettingsLocked(UserHandle.getCallingUserId());
5186 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
5191 synchronized (this) {
5193 throw new NullPointerException("ComponentName is null");
5196 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5197 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5198 return admin.disableCallerId;
5203 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
5204 // TODO: Should there be a check to make sure this relationship is within a profile group?
5205 //enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5206 synchronized (this) {
5207 ActiveAdmin admin = getProfileOwnerAdmin(userId);
5208 return (admin != null) ? admin.disableCallerId : false;
5213 * Sets which packages may enter lock task mode.
5215 * This function can only be called by the device owner.
5216 * @param components The list of components allowed to enter lock task mode.
5218 public void setLockTaskPackages(ComponentName who, String[] packages) throws SecurityException {
5219 synchronized (this) {
5221 throw new NullPointerException("ComponentName is null");
5223 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5225 int userHandle = Binder.getCallingUserHandle().getIdentifier();
5226 DevicePolicyData policy = getUserData(userHandle);
5227 policy.mLockTaskPackages.clear();
5228 if (packages != null) {
5229 for (int j = 0; j < packages.length; j++) {
5230 String pkg = packages[j];
5231 policy.mLockTaskPackages.add(pkg);
5235 // Store the settings persistently.
5236 saveSettingsLocked(userHandle);
5241 * This function returns the list of components allowed to start the task lock mode.
5243 public String[] getLockTaskPackages(ComponentName who) {
5244 synchronized (this) {
5246 throw new NullPointerException("ComponentName is null");
5248 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5250 int userHandle = Binder.getCallingUserHandle().getIdentifier();
5251 DevicePolicyData policy = getUserData(userHandle);
5252 return policy.mLockTaskPackages.toArray(new String[0]);
5257 * This function lets the caller know whether the given package is allowed to start the
5259 * @param pkg The package to check
5261 public boolean isLockTaskPermitted(String pkg) {
5262 // Get current user's devicepolicy
5263 int uid = Binder.getCallingUid();
5264 int userHandle = UserHandle.getUserId(uid);
5265 DevicePolicyData policy = getUserData(userHandle);
5266 synchronized (this) {
5267 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
5268 String lockTaskPackage = policy.mLockTaskPackages.get(i);
5270 // If the given package equals one of the packages stored our list,
5271 // we allow this package to start lock task mode.
5272 if (lockTaskPackage.equals(pkg)) {
5281 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
5282 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
5283 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
5285 synchronized (this) {
5286 final DevicePolicyData policy = getUserData(userHandle);
5287 Bundle adminExtras = new Bundle();
5288 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
5289 for (ActiveAdmin admin : policy.mAdminList) {
5290 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
5291 boolean ownsProfile = (getProfileOwner(userHandle) != null
5292 && getProfileOwner(userHandle).equals(admin.info.getPackageName()));
5293 if (ownsDevice || ownsProfile) {
5295 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
5298 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
5306 public void setGlobalSetting(ComponentName who, String setting, String value) {
5307 final ContentResolver contentResolver = mContext.getContentResolver();
5309 synchronized (this) {
5311 throw new NullPointerException("ComponentName is null");
5313 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5315 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
5316 throw new SecurityException(String.format(
5317 "Permission denial: device owners cannot update %1$s", setting));
5320 long id = Binder.clearCallingIdentity();
5322 Settings.Global.putString(contentResolver, setting, value);
5324 restoreCallingIdentity(id);
5330 public void setSecureSetting(ComponentName who, String setting, String value) {
5331 int callingUserId = UserHandle.getCallingUserId();
5332 final ContentResolver contentResolver = mContext.getContentResolver();
5334 synchronized (this) {
5336 throw new NullPointerException("ComponentName is null");
5338 ActiveAdmin activeAdmin =
5339 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5341 if (isDeviceOwner(activeAdmin.info.getPackageName())) {
5342 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
5343 throw new SecurityException(String.format(
5344 "Permission denial: Device owners cannot update %1$s", setting));
5346 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
5347 throw new SecurityException(String.format(
5348 "Permission denial: Profile owners cannot update %1$s", setting));
5351 long id = Binder.clearCallingIdentity();
5353 Settings.Secure.putStringForUser(contentResolver, setting, value, callingUserId);
5355 restoreCallingIdentity(id);
5361 public void setMasterVolumeMuted(ComponentName who, boolean on) {
5362 final ContentResolver contentResolver = mContext.getContentResolver();
5364 synchronized (this) {
5366 throw new NullPointerException("ComponentName is null");
5368 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5370 IAudioService iAudioService = IAudioService.Stub.asInterface(
5371 ServiceManager.getService(Context.AUDIO_SERVICE));
5373 iAudioService.setMasterMute(on, 0, who.getPackageName(), null);
5374 } catch (RemoteException re) {
5375 Slog.e(LOG_TAG, "Failed to setMasterMute", re);
5381 public boolean isMasterVolumeMuted(ComponentName who) {
5382 final ContentResolver contentResolver = mContext.getContentResolver();
5384 synchronized (this) {
5386 throw new NullPointerException("ComponentName is null");
5388 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5390 AudioManager audioManager =
5391 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
5392 return audioManager.isMasterMute();
5397 * We need to update the internal state of whether a user has completed setup once. After
5398 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
5399 * as we don't trust any apps that might try to reset it.
5401 * Unfortunately, we don't know which user's setup state was changed, so we write all of
5404 void updateUserSetupComplete() {
5405 List<UserInfo> users = mUserManager.getUsers(true);
5406 ContentResolver resolver = mContext.getContentResolver();
5407 final int N = users.size();
5408 for (int i = 0; i < N; i++) {
5409 int userHandle = users.get(i).id;
5410 if (Settings.Secure.getIntForUser(resolver, Settings.Secure.USER_SETUP_COMPLETE, 0,
5412 DevicePolicyData policy = getUserData(userHandle);
5413 if (!policy.mUserSetupComplete) {
5414 policy.mUserSetupComplete = true;
5415 synchronized (this) {
5416 saveSettingsLocked(userHandle);
5423 private class SetupContentObserver extends ContentObserver {
5425 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
5426 Settings.Secure.USER_SETUP_COMPLETE);
5428 public SetupContentObserver(Handler handler) {
5432 void register(ContentResolver resolver) {
5433 resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
5437 public void onChange(boolean selfChange, Uri uri) {
5438 if (mUserSetupComplete.equals(uri)) {
5439 updateUserSetupComplete();
5444 private final class LocalService extends DevicePolicyManagerInternal {
5445 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
5448 public List<String> getCrossProfileWidgetProviders(int profileId) {
5449 synchronized (DevicePolicyManagerService.this) {
5450 if (mDeviceOwner == null) {
5451 return Collections.emptyList();
5453 ComponentName ownerComponent = mDeviceOwner.getProfileOwnerComponent(profileId);
5454 if (ownerComponent == null) {
5455 return Collections.emptyList();
5458 DevicePolicyData policy = getUserDataUnchecked(profileId);
5459 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
5461 if (admin == null || admin.crossProfileWidgetProviders == null
5462 || admin.crossProfileWidgetProviders.isEmpty()) {
5463 return Collections.emptyList();
5466 return admin.crossProfileWidgetProviders;
5471 public void addOnCrossProfileWidgetProvidersChangeListener(
5472 OnCrossProfileWidgetProvidersChangeListener listener) {
5473 synchronized (DevicePolicyManagerService.this) {
5474 if (mWidgetProviderListeners == null) {
5475 mWidgetProviderListeners = new ArrayList<>();
5477 if (!mWidgetProviderListeners.contains(listener)) {
5478 mWidgetProviderListeners.add(listener);
5483 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
5484 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
5485 synchronized (DevicePolicyManagerService.this) {
5486 listeners = new ArrayList<>(mWidgetProviderListeners);
5488 final int listenerCount = listeners.size();
5489 for (int i = 0; i < listenerCount; i++) {
5490 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
5491 listener.onCrossProfileWidgetProvidersChanged(userId, packages);