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 wipeDataNoLock(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 final String source;
3011 synchronized (this) {
3012 // This API can only be called by an active device admin,
3013 // so try to retrieve it to check that the caller is one.
3014 final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
3015 DeviceAdminInfo.USES_POLICY_WIPE_DATA);
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);
3034 if (manager != null) {
3039 Binder.restoreCallingIdentity(ident);
3042 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
3043 wipeDeviceNoLock(wipeExtRequested, userHandle,
3044 "DevicePolicyManager.wipeData() from " + source);
3047 private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
3048 final long iden = Binder.clearCallingIdentity();
3050 if (userHandle == UserHandle.USER_OWNER) {
3051 wipeDataNoLock(wipeExtRequested, reason);
3053 mHandler.post(new Runnable() {
3056 IActivityManager am = ActivityManagerNative.getDefault();
3057 if (am.getCurrentUser().id == userHandle) {
3058 am.switchUser(UserHandle.USER_OWNER);
3060 if (!mUserManager.removeUser(userHandle)) {
3061 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
3063 } catch (RemoteException re) {
3070 Binder.restoreCallingIdentity(iden);
3074 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
3078 enforceCrossUserPermission(userHandle);
3079 mContext.enforceCallingOrSelfPermission(
3080 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3082 synchronized (this) {
3083 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
3084 if (admin == null) {
3086 result.sendResult(null);
3087 } catch (RemoteException e) {
3091 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
3092 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3093 intent.setComponent(admin.info.getComponent());
3094 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
3095 null, new BroadcastReceiver() {
3097 public void onReceive(Context context, Intent intent) {
3099 result.sendResult(getResultExtras(false));
3100 } catch (RemoteException e) {
3103 }, null, Activity.RESULT_OK, null, null);
3107 public void setActivePasswordState(int quality, int length, int letters, int uppercase,
3108 int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
3112 enforceCrossUserPermission(userHandle);
3113 enforceNotManagedProfile(userHandle, "set the active password");
3115 mContext.enforceCallingOrSelfPermission(
3116 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3117 DevicePolicyData p = getUserData(userHandle);
3119 validateQualityConstant(quality);
3121 synchronized (this) {
3122 if (p.mActivePasswordQuality != quality || p.mActivePasswordLength != length
3123 || p.mFailedPasswordAttempts != 0 || p.mActivePasswordLetters != letters
3124 || p.mActivePasswordUpperCase != uppercase
3125 || p.mActivePasswordLowerCase != lowercase
3126 || p.mActivePasswordNumeric != numbers
3127 || p.mActivePasswordSymbols != symbols
3128 || p.mActivePasswordNonLetter != nonletter) {
3129 long ident = Binder.clearCallingIdentity();
3131 p.mActivePasswordQuality = quality;
3132 p.mActivePasswordLength = length;
3133 p.mActivePasswordLetters = letters;
3134 p.mActivePasswordLowerCase = lowercase;
3135 p.mActivePasswordUpperCase = uppercase;
3136 p.mActivePasswordNumeric = numbers;
3137 p.mActivePasswordSymbols = symbols;
3138 p.mActivePasswordNonLetter = nonletter;
3139 p.mFailedPasswordAttempts = 0;
3140 saveSettingsLocked(userHandle);
3141 updatePasswordExpirationsLocked(userHandle);
3142 setExpirationAlarmCheckLocked(mContext, p);
3143 sendAdminCommandToSelfAndProfilesLocked(
3144 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
3145 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
3147 Binder.restoreCallingIdentity(ident);
3154 * Called any time the device password is updated. Resets all password expiration clocks.
3156 private void updatePasswordExpirationsLocked(int userHandle) {
3157 List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3158 for (UserInfo userInfo : profiles) {
3159 int profileId = userInfo.id;
3160 DevicePolicyData policy = getUserDataUnchecked(profileId);
3161 final int N = policy.mAdminList.size();
3163 for (int i=0; i<N; i++) {
3164 ActiveAdmin admin = policy.mAdminList.get(i);
3165 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
3166 long timeout = admin.passwordExpirationTimeout;
3167 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3168 admin.passwordExpirationDate = expiration;
3172 saveSettingsLocked(profileId);
3176 public void reportFailedPasswordAttempt(int userHandle) {
3177 enforceCrossUserPermission(userHandle);
3178 enforceNotManagedProfile(userHandle, "report failed password attempt");
3179 mContext.enforceCallingOrSelfPermission(
3180 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3182 long ident = Binder.clearCallingIdentity();
3184 boolean wipeData = false;
3186 synchronized (this) {
3187 DevicePolicyData policy = getUserData(userHandle);
3188 policy.mFailedPasswordAttempts++;
3189 saveSettingsLocked(userHandle);
3191 ActiveAdmin strictestAdmin =
3192 getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
3193 int max = strictestAdmin != null
3194 ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
3195 if (max > 0 && policy.mFailedPasswordAttempts >= max) {
3196 // Wipe the user/profile associated with the policy that was violated. This
3197 // is not necessarily calling user: if the policy that fired was from a
3198 // managed profile rather than the main user profile, we wipe former only.
3200 identifier = strictestAdmin.getUserHandle().getIdentifier();
3202 sendAdminCommandToSelfAndProfilesLocked(
3203 DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
3204 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3208 // Call without holding lock.
3209 wipeDeviceNoLock(false, identifier,
3210 "reportFailedPasswordAttempt()");
3213 Binder.restoreCallingIdentity(ident);
3217 public void reportSuccessfulPasswordAttempt(int userHandle) {
3218 enforceCrossUserPermission(userHandle);
3219 mContext.enforceCallingOrSelfPermission(
3220 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3222 synchronized (this) {
3223 DevicePolicyData policy = getUserData(userHandle);
3224 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
3225 long ident = Binder.clearCallingIdentity();
3227 policy.mFailedPasswordAttempts = 0;
3228 policy.mPasswordOwner = -1;
3229 saveSettingsLocked(userHandle);
3231 sendAdminCommandToSelfAndProfilesLocked(
3232 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
3233 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3236 Binder.restoreCallingIdentity(ident);
3242 public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
3243 String exclusionList, int userHandle) {
3247 enforceCrossUserPermission(userHandle);
3248 synchronized(this) {
3250 throw new NullPointerException("ComponentName is null");
3253 // Only check if owner has set global proxy. We don't allow other users to set it.
3254 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3255 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3256 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
3258 // Scan through active admins and find if anyone has already
3259 // set the global proxy.
3260 Set<ComponentName> compSet = policy.mAdminMap.keySet();
3261 for (ComponentName component : compSet) {
3262 ActiveAdmin ap = policy.mAdminMap.get(component);
3263 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
3264 // Another admin already sets the global proxy
3265 // Return it to the caller.
3270 // If the user is not the owner, don't set the global proxy. Fail silently.
3271 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3272 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
3273 + userHandle + " is not permitted.");
3276 if (proxySpec == null) {
3277 admin.specifiesGlobalProxy = false;
3278 admin.globalProxySpec = null;
3279 admin.globalProxyExclusionList = null;
3282 admin.specifiesGlobalProxy = true;
3283 admin.globalProxySpec = proxySpec;
3284 admin.globalProxyExclusionList = exclusionList;
3287 // Reset the global proxy accordingly
3288 // Do this using system permissions, as apps cannot write to secure settings
3289 long origId = Binder.clearCallingIdentity();
3291 resetGlobalProxyLocked(policy);
3293 Binder.restoreCallingIdentity(origId);
3299 public ComponentName getGlobalProxyAdmin(int userHandle) {
3303 enforceCrossUserPermission(userHandle);
3304 synchronized(this) {
3305 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3306 // Scan through active admins and find if anyone has already
3307 // set the global proxy.
3308 final int N = policy.mAdminList.size();
3309 for (int i = 0; i < N; i++) {
3310 ActiveAdmin ap = policy.mAdminList.get(i);
3311 if (ap.specifiesGlobalProxy) {
3312 // Device admin sets the global proxy
3313 // Return it to the caller.
3314 return ap.info.getComponent();
3318 // No device admin sets the global proxy.
3322 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
3323 synchronized (this) {
3324 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3326 long token = Binder.clearCallingIdentity();
3328 ConnectivityManager connectivityManager = (ConnectivityManager)
3329 mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
3330 connectivityManager.setGlobalProxy(proxyInfo);
3332 Binder.restoreCallingIdentity(token);
3336 private void resetGlobalProxyLocked(DevicePolicyData policy) {
3337 final int N = policy.mAdminList.size();
3338 for (int i = 0; i < N; i++) {
3339 ActiveAdmin ap = policy.mAdminList.get(i);
3340 if (ap.specifiesGlobalProxy) {
3341 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
3345 // No device admins defining global proxies - reset global proxy settings to none
3346 saveGlobalProxyLocked(null, null);
3349 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
3350 if (exclusionList == null) {
3353 if (proxySpec == null) {
3356 // Remove white spaces
3357 proxySpec = proxySpec.trim();
3358 String data[] = proxySpec.split(":");
3359 int proxyPort = 8080;
3360 if (data.length > 1) {
3362 proxyPort = Integer.parseInt(data[1]);
3363 } catch (NumberFormatException e) {}
3365 exclusionList = exclusionList.trim();
3366 ContentResolver res = mContext.getContentResolver();
3368 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
3369 if (!proxyProperties.isValid()) {
3370 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
3373 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
3374 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
3375 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3380 * Set the storage encryption request for a single admin. Returns the new total request
3381 * status (for all admins).
3383 public int setStorageEncryption(ComponentName who, boolean encrypt, int userHandle) {
3385 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3387 enforceCrossUserPermission(userHandle);
3388 synchronized (this) {
3389 // Check for permissions
3391 throw new NullPointerException("ComponentName is null");
3393 // Only owner can set storage encryption
3394 if (userHandle != UserHandle.USER_OWNER
3395 || UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3396 Slog.w(LOG_TAG, "Only owner is allowed to set storage encryption. User "
3397 + UserHandle.getCallingUserId() + " is not permitted.");
3401 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3402 DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
3404 // Quick exit: If the filesystem does not support encryption, we can exit early.
3405 if (!isEncryptionSupported()) {
3406 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3409 // (1) Record the value for the admin so it's sticky
3410 if (ap.encryptionRequested != encrypt) {
3411 ap.encryptionRequested = encrypt;
3412 saveSettingsLocked(userHandle);
3415 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3416 // (2) Compute "max" for all admins
3417 boolean newRequested = false;
3418 final int N = policy.mAdminList.size();
3419 for (int i = 0; i < N; i++) {
3420 newRequested |= policy.mAdminList.get(i).encryptionRequested;
3423 // Notify OS of new request
3424 setEncryptionRequested(newRequested);
3426 // Return the new global request status
3428 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3429 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3434 * Get the current storage encryption request status for a given admin, or aggregate of all
3437 public boolean getStorageEncryption(ComponentName who, int userHandle) {
3441 enforceCrossUserPermission(userHandle);
3442 synchronized (this) {
3443 // Check for permissions if a particular caller is specified
3445 // When checking for a single caller, status is based on caller's request
3446 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
3447 return ap != null ? ap.encryptionRequested : false;
3450 // If no particular caller is specified, return the aggregate set of requests.
3451 // This is short circuited by returning true on the first hit.
3452 DevicePolicyData policy = getUserData(userHandle);
3453 final int N = policy.mAdminList.size();
3454 for (int i = 0; i < N; i++) {
3455 if (policy.mAdminList.get(i).encryptionRequested) {
3464 * Get the current encryption status of the device.
3466 public int getStorageEncryptionStatus(int userHandle) {
3468 // Ok to return current status.
3470 enforceCrossUserPermission(userHandle);
3471 return getEncryptionStatus();
3475 * Hook to low-levels: This should report if the filesystem supports encrypted storage.
3477 private boolean isEncryptionSupported() {
3478 // Note, this can be implemented as
3479 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3480 // But is provided as a separate internal method if there's a faster way to do a
3481 // simple check for supported-or-not.
3482 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3486 * Hook to low-levels: Reporting the current status of encryption.
3487 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} or
3488 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE} or
3489 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
3491 private int getEncryptionStatus() {
3492 String status = SystemProperties.get("ro.crypto.state", "unsupported");
3493 if ("encrypted".equalsIgnoreCase(status)) {
3494 final long token = Binder.clearCallingIdentity();
3496 return LockPatternUtils.isDeviceEncrypted()
3497 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3498 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3500 Binder.restoreCallingIdentity(token);
3502 } else if ("unencrypted".equalsIgnoreCase(status)) {
3503 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3505 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3510 * Hook to low-levels: If needed, record the new admin setting for encryption.
3512 private void setEncryptionRequested(boolean encrypt) {
3517 * Set whether the screen capture is disabled for the user managed by the specified admin.
3519 public void setScreenCaptureDisabled(ComponentName who, int userHandle, boolean disabled) {
3523 enforceCrossUserPermission(userHandle);
3524 synchronized (this) {
3526 throw new NullPointerException("ComponentName is null");
3528 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3529 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3530 if (ap.disableScreenCapture != disabled) {
3531 ap.disableScreenCapture = disabled;
3532 saveSettingsLocked(userHandle);
3533 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
3539 * Returns whether or not screen capture is disabled for a given admin, or disabled for any
3540 * active admin (if given admin is null).
3542 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
3546 synchronized (this) {
3548 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3549 return (admin != null) ? admin.disableScreenCapture : false;
3552 DevicePolicyData policy = getUserData(userHandle);
3553 final int N = policy.mAdminList.size();
3554 for (int i = 0; i < N; i++) {
3555 ActiveAdmin admin = policy.mAdminList.get(i);
3556 if (admin.disableScreenCapture) {
3564 private void updateScreenCaptureDisabledInWindowManager(int userHandle, boolean disabled) {
3565 long ident = Binder.clearCallingIdentity();
3567 getWindowManager().setScreenCaptureDisabled(userHandle, disabled);
3568 } catch (RemoteException e) {
3569 Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
3571 Binder.restoreCallingIdentity(ident);
3576 * Set whether auto time is required by the specified admin (must be device owner).
3578 public void setAutoTimeRequired(ComponentName who, int userHandle, boolean required) {
3582 enforceCrossUserPermission(userHandle);
3583 synchronized (this) {
3585 throw new NullPointerException("ComponentName is null");
3587 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3588 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3589 if (admin.requireAutoTime != required) {
3590 admin.requireAutoTime = required;
3591 saveSettingsLocked(userHandle);
3595 // Turn AUTO_TIME on in settings if it is required
3597 long ident = Binder.clearCallingIdentity();
3599 Settings.Global.putInt(mContext.getContentResolver(),
3600 Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
3602 Binder.restoreCallingIdentity(ident);
3608 * Returns whether or not auto time is required by the device owner.
3610 public boolean getAutoTimeRequired() {
3614 synchronized (this) {
3615 ActiveAdmin deviceOwner = getDeviceOwnerAdmin();
3616 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
3621 * The system property used to share the state of the camera. The native camera service
3622 * is expected to read this property and act accordingly.
3624 public static final String SYSTEM_PROP_DISABLE_CAMERA = "sys.secpolicy.camera.disabled";
3627 * Disables all device cameras according to the specified admin.
3629 public void setCameraDisabled(ComponentName who, boolean disabled, int userHandle) {
3633 enforceCrossUserPermission(userHandle);
3634 synchronized (this) {
3636 throw new NullPointerException("ComponentName is null");
3638 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3639 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
3640 if (ap.disableCamera != disabled) {
3641 ap.disableCamera = disabled;
3642 saveSettingsLocked(userHandle);
3644 syncDeviceCapabilitiesLocked(getUserData(userHandle));
3649 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
3652 public boolean getCameraDisabled(ComponentName who, int userHandle) {
3656 synchronized (this) {
3658 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3659 return (admin != null) ? admin.disableCamera : false;
3662 DevicePolicyData policy = getUserData(userHandle);
3663 // Determine whether or not the device camera is disabled for any active admins.
3664 final int N = policy.mAdminList.size();
3665 for (int i = 0; i < N; i++) {
3666 ActiveAdmin admin = policy.mAdminList.get(i);
3667 if (admin.disableCamera) {
3676 * Selectively disable keyguard features.
3678 public void setKeyguardDisabledFeatures(ComponentName who, int which, int userHandle) {
3682 enforceCrossUserPermission(userHandle);
3683 enforceNotManagedProfile(userHandle, "disable keyguard features");
3684 synchronized (this) {
3686 throw new NullPointerException("ComponentName is null");
3688 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3689 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
3690 if (ap.disabledKeyguardFeatures != which) {
3691 ap.disabledKeyguardFeatures = which;
3692 saveSettingsLocked(userHandle);
3694 syncDeviceCapabilitiesLocked(getUserData(userHandle));
3699 * Gets the disabled state for features in keyguard for the given admin,
3700 * or the aggregate of all active admins if who is null.
3702 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle) {
3706 enforceCrossUserPermission(userHandle);
3707 synchronized (this) {
3709 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3710 return (admin != null) ? admin.disabledKeyguardFeatures : 0;
3713 // Determine which keyguard features are disabled for any active admins.
3714 DevicePolicyData policy = getUserData(userHandle);
3715 final int N = policy.mAdminList.size();
3717 for (int i = 0; i < N; i++) {
3718 ActiveAdmin admin = policy.mAdminList.get(i);
3719 which |= admin.disabledKeyguardFeatures;
3726 public boolean setDeviceOwner(String packageName, String ownerName) {
3730 if (packageName == null
3731 || !DeviceOwner.isInstalled(packageName, mContext.getPackageManager())) {
3732 throw new IllegalArgumentException("Invalid package name " + packageName
3733 + " for device owner");
3735 synchronized (this) {
3736 if (!allowedToSetDeviceOwnerOnDevice()) {
3737 throw new IllegalStateException(
3738 "Trying to set device owner but device is already provisioned.");
3741 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
3742 throw new IllegalStateException(
3743 "Trying to set device owner but device owner is already set.");
3746 // Shutting down backup manager service permanently.
3747 long ident = Binder.clearCallingIdentity();
3749 IBackupManager ibm = IBackupManager.Stub.asInterface(
3750 ServiceManager.getService(Context.BACKUP_SERVICE));
3751 ibm.setBackupServiceActive(UserHandle.USER_OWNER, false);
3752 } catch (RemoteException e) {
3753 throw new IllegalStateException("Failed deactivating backup service.", e);
3755 Binder.restoreCallingIdentity(ident);
3758 if (mDeviceOwner == null) {
3759 // Device owner is not set and does not exist, set it.
3760 mDeviceOwner = DeviceOwner.createWithDeviceOwner(packageName, ownerName);
3761 mDeviceOwner.writeOwnerFile();
3764 // Device owner is not set but a profile owner exists, update Device owner state.
3765 mDeviceOwner.setDeviceOwner(packageName, ownerName);
3766 mDeviceOwner.writeOwnerFile();
3773 public boolean isDeviceOwner(String packageName) {
3777 synchronized (this) {
3778 return mDeviceOwner != null
3779 && mDeviceOwner.hasDeviceOwner()
3780 && mDeviceOwner.getDeviceOwnerPackageName().equals(packageName);
3785 public String getDeviceOwner() {
3789 synchronized (this) {
3790 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
3791 return mDeviceOwner.getDeviceOwnerPackageName();
3798 public String getDeviceOwnerName() {
3802 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
3803 synchronized (this) {
3804 if (mDeviceOwner != null) {
3805 return mDeviceOwner.getDeviceOwnerName();
3811 // Returns the active device owner or null if there is no device owner.
3812 private ActiveAdmin getDeviceOwnerAdmin() {
3813 String deviceOwnerPackageName = getDeviceOwner();
3814 if (deviceOwnerPackageName == null) {
3818 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3819 final int n = policy.mAdminList.size();
3820 for (int i = 0; i < n; i++) {
3821 ActiveAdmin admin = policy.mAdminList.get(i);
3822 if (deviceOwnerPackageName.equals(admin.info.getPackageName())) {
3830 public void clearDeviceOwner(String packageName) {
3831 if (packageName == null) {
3832 throw new NullPointerException("packageName is null");
3835 int uid = mContext.getPackageManager().getPackageUid(packageName, 0);
3836 if (uid != Binder.getCallingUid()) {
3837 throw new SecurityException("Invalid packageName");
3839 } catch (NameNotFoundException e) {
3840 throw new SecurityException(e);
3842 if (!isDeviceOwner(packageName)) {
3843 throw new SecurityException("clearDeviceOwner can only be called by the device owner");
3845 synchronized (this) {
3846 long ident = Binder.clearCallingIdentity();
3848 clearUserRestrictions(new UserHandle(UserHandle.USER_OWNER));
3849 if (mDeviceOwner != null) {
3850 mDeviceOwner.clearDeviceOwner();
3851 mDeviceOwner.writeOwnerFile();
3854 Binder.restoreCallingIdentity(ident);
3860 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
3864 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
3866 UserInfo info = mUserManager.getUserInfo(userHandle);
3868 // User doesn't exist.
3869 throw new IllegalArgumentException(
3870 "Attempted to set profile owner for invalid userId: " + userHandle);
3872 if (info.isGuest()) {
3873 throw new IllegalStateException("Cannot set a profile owner on a guest");
3877 || !DeviceOwner.isInstalledForUser(who.getPackageName(), userHandle)) {
3878 throw new IllegalArgumentException("Component " + who
3879 + " not installed for userId:" + userHandle);
3881 synchronized (this) {
3882 // Only SYSTEM_UID can override the userSetupComplete
3883 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID
3884 && hasUserSetupCompleted(userHandle)) {
3885 throw new IllegalStateException(
3886 "Trying to set profile owner but user is already set-up.");
3889 if (mDeviceOwner == null) {
3890 // Device owner state does not exist, create it.
3891 mDeviceOwner = DeviceOwner.createWithProfileOwner(who, ownerName,
3893 mDeviceOwner.writeOwnerFile();
3896 // Device owner already exists, update it.
3897 mDeviceOwner.setProfileOwner(who, ownerName, userHandle);
3898 mDeviceOwner.writeOwnerFile();
3905 public void clearProfileOwner(ComponentName who) {
3909 UserHandle callingUser = Binder.getCallingUserHandle();
3910 // Check if this is the profile owner who is calling
3911 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3912 synchronized (this) {
3913 long ident = Binder.clearCallingIdentity();
3915 clearUserRestrictions(callingUser);
3916 if (mDeviceOwner != null) {
3917 mDeviceOwner.removeProfileOwner(callingUser.getIdentifier());
3918 mDeviceOwner.writeOwnerFile();
3921 Binder.restoreCallingIdentity(ident);
3926 private void clearUserRestrictions(UserHandle userHandle) {
3927 AudioManager audioManager =
3928 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
3929 Bundle userRestrictions = mUserManager.getUserRestrictions();
3930 mUserManager.setUserRestrictions(new Bundle(), userHandle);
3931 if (userRestrictions.getBoolean(UserManager.DISALLOW_ADJUST_VOLUME)) {
3932 audioManager.setMasterMute(false);
3934 if (userRestrictions.getBoolean(UserManager.DISALLOW_UNMUTE_MICROPHONE)) {
3935 audioManager.setMicrophoneMute(false);
3940 public boolean hasUserSetupCompleted() {
3941 return hasUserSetupCompleted(UserHandle.getCallingUserId());
3944 private boolean hasUserSetupCompleted(int userHandle) {
3948 DevicePolicyData policy = getUserData(userHandle);
3949 // If policy is null, return true, else check if the setup has completed.
3950 return policy == null || policy.mUserSetupComplete;
3954 public void setProfileEnabled(ComponentName who) {
3958 final int userHandle = UserHandle.getCallingUserId();
3959 synchronized (this) {
3960 // Check for permissions
3962 throw new NullPointerException("ComponentName is null");
3964 // Check if this is the profile owner who is calling
3965 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3966 int userId = UserHandle.getCallingUserId();
3968 long id = Binder.clearCallingIdentity();
3970 mUserManager.setUserEnabled(userId);
3971 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
3972 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle));
3973 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3974 Intent.FLAG_RECEIVER_FOREGROUND);
3975 // TODO This should send to parent of profile (which is always owner at the moment).
3976 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
3978 restoreCallingIdentity(id);
3984 public void setProfileName(ComponentName who, String profileName) {
3985 int userId = UserHandle.getCallingUserId();
3988 throw new NullPointerException("ComponentName is null");
3991 // Check if this is the profile owner (includes device owner).
3992 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3994 long id = Binder.clearCallingIdentity();
3996 mUserManager.setUserName(userId, profileName);
3998 restoreCallingIdentity(id);
4003 public ComponentName getProfileOwner(int userHandle) {
4008 synchronized (this) {
4009 if (mDeviceOwner != null) {
4010 return mDeviceOwner.getProfileOwnerComponent(userHandle);
4016 // Returns the active profile owner for this user or null if the current user has no
4018 private ActiveAdmin getProfileOwnerAdmin(int userHandle) {
4019 ComponentName profileOwner =
4020 mDeviceOwner != null ? mDeviceOwner.getProfileOwnerComponent(userHandle) : null;
4021 if (profileOwner == null) {
4025 DevicePolicyData policy = getUserData(userHandle);
4026 final int n = policy.mAdminList.size();
4027 for (int i = 0; i < n; i++) {
4028 ActiveAdmin admin = policy.mAdminList.get(i);
4029 if (profileOwner.equals(admin.info.getComponent())) {
4037 public String getProfileOwnerName(int userHandle) {
4041 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
4043 synchronized (this) {
4044 if (mDeviceOwner != null) {
4045 return mDeviceOwner.getProfileOwnerName(userHandle);
4052 * Device owner can only be set on an unprovisioned device, unless it was initiated by "adb", in
4053 * which case we allow it if no account is associated with the device.
4055 private boolean allowedToSetDeviceOwnerOnDevice() {
4056 int callingId = Binder.getCallingUid();
4057 if (callingId == Process.SHELL_UID || callingId == Process.ROOT_UID) {
4058 return AccountManager.get(mContext).getAccounts().length == 0;
4060 return !hasUserSetupCompleted(UserHandle.USER_OWNER);
4064 private void enforceCrossUserPermission(int userHandle) {
4065 if (userHandle < 0) {
4066 throw new IllegalArgumentException("Invalid userId " + userHandle);
4068 final int callingUid = Binder.getCallingUid();
4069 if (userHandle == UserHandle.getUserId(callingUid)) return;
4070 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4071 mContext.enforceCallingOrSelfPermission(
4072 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have"
4073 + " INTERACT_ACROSS_USERS_FULL permission");
4077 private void enforceSystemProcess(String message) {
4078 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4079 throw new SecurityException(message);
4083 private void enforceNotManagedProfile(int userHandle, String message) {
4084 if(isManagedProfile(userHandle)) {
4085 throw new SecurityException("You can not " + message + " for a managed profile. ");
4089 private UserInfo getProfileParent(int userHandle) {
4090 long ident = Binder.clearCallingIdentity();
4092 return mUserManager.getProfileParent(userHandle);
4094 Binder.restoreCallingIdentity(ident);
4098 private boolean isManagedProfile(int userHandle) {
4099 long ident = Binder.clearCallingIdentity();
4101 return mUserManager.getUserInfo(userHandle).isManagedProfile();
4103 Binder.restoreCallingIdentity(ident);
4107 private void enableIfNecessary(String packageName, int userId) {
4109 IPackageManager ipm = AppGlobals.getPackageManager();
4110 ApplicationInfo ai = ipm.getApplicationInfo(packageName,
4111 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
4113 if (ai.enabledSetting
4114 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
4115 ipm.setApplicationEnabledSetting(packageName,
4116 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
4117 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
4119 } catch (RemoteException e) {
4124 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4125 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4126 != PackageManager.PERMISSION_GRANTED) {
4128 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
4129 + Binder.getCallingPid()
4130 + ", uid=" + Binder.getCallingUid());
4134 final Printer p = new PrintWriterPrinter(pw);
4136 synchronized (this) {
4137 p.println("Current Device Policy Manager state:");
4139 int userCount = mUserData.size();
4140 for (int u = 0; u < userCount; u++) {
4141 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
4142 p.println(" Enabled Device Admins (User " + policy.mUserHandle + "):");
4143 final int N = policy.mAdminList.size();
4144 for (int i=0; i<N; i++) {
4145 ActiveAdmin ap = policy.mAdminList.get(i);
4147 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString());
4152 if (!policy.mRemovingAdmins.isEmpty()) {
4153 p.println(" Removing Device Admins (User " + policy.mUserHandle + "): "
4154 + policy.mRemovingAdmins);
4158 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner);
4164 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
4165 ComponentName activity) {
4166 final int userHandle = UserHandle.getCallingUserId();
4168 synchronized (this) {
4170 throw new NullPointerException("ComponentName is null");
4172 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4174 IPackageManager pm = AppGlobals.getPackageManager();
4175 long id = Binder.clearCallingIdentity();
4177 pm.addPersistentPreferredActivity(filter, activity, userHandle);
4178 } catch (RemoteException re) {
4181 restoreCallingIdentity(id);
4187 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
4188 final int userHandle = UserHandle.getCallingUserId();
4190 synchronized (this) {
4192 throw new NullPointerException("ComponentName is null");
4194 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4196 IPackageManager pm = AppGlobals.getPackageManager();
4197 long id = Binder.clearCallingIdentity();
4199 pm.clearPackagePersistentPreferredActivities(packageName, userHandle);
4200 } catch (RemoteException re) {
4203 restoreCallingIdentity(id);
4209 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
4210 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4212 synchronized (this) {
4214 throw new NullPointerException("ComponentName is null");
4216 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4218 long id = Binder.clearCallingIdentity();
4220 mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
4222 restoreCallingIdentity(id);
4227 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
4228 PersistableBundle args, int userHandle) {
4232 enforceCrossUserPermission(userHandle);
4233 enforceNotManagedProfile(userHandle, "set trust agent configuration");
4234 synchronized (this) {
4235 if (admin == null) {
4236 throw new NullPointerException("admin is null");
4238 if (agent == null) {
4239 throw new NullPointerException("agent is null");
4241 ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
4242 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
4243 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
4244 saveSettingsLocked(userHandle);
4245 syncDeviceCapabilitiesLocked(getUserData(userHandle));
4249 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
4250 ComponentName agent, int userHandle) {
4254 enforceCrossUserPermission(userHandle);
4255 if (agent == null) {
4256 throw new NullPointerException("agent is null");
4259 synchronized (this) {
4260 final String componentName = agent.flattenToString();
4261 if (admin != null) {
4262 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle);
4263 if (ap == null) return null;
4264 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
4265 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
4266 List<PersistableBundle> result = new ArrayList<PersistableBundle>();
4267 result.add(trustAgentInfo.options);
4271 // Return strictest policy for this user and profiles that are visible from this user.
4272 final List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
4273 List<PersistableBundle> result = null;
4275 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
4276 // of the options. If any admin doesn't have options, discard options for the rest
4278 boolean allAdminsHaveOptions = true;
4279 for (UserInfo userInfo : profiles) {
4280 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4281 final int N = policy.mAdminList.size();
4282 for (int i=0; i < N; i++) {
4283 final ActiveAdmin active = policy.mAdminList.get(i);
4284 final boolean disablesTrust = (active.disabledKeyguardFeatures
4285 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
4286 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
4287 if (info != null && info.options != null && !info.options.isEmpty()) {
4288 if (disablesTrust) {
4289 if (result == null) {
4290 result = new ArrayList<PersistableBundle>();
4292 result.add(info.options);
4294 Log.w(LOG_TAG, "Ignoring admin " + active.info
4295 + " because it has trust options but doesn't declare "
4296 + "KEYGUARD_DISABLE_TRUST_AGENTS");
4298 } else if (disablesTrust) {
4299 allAdminsHaveOptions = false;
4304 return allAdminsHaveOptions ? result : null;
4309 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
4310 synchronized (this) {
4312 throw new NullPointerException("ComponentName is null");
4314 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4316 int userHandle = UserHandle.getCallingUserId();
4317 DevicePolicyData userData = getUserData(userHandle);
4318 userData.mRestrictionsProvider = permissionProvider;
4319 saveSettingsLocked(userHandle);
4324 public ComponentName getRestrictionsProvider(int userHandle) {
4325 synchronized (this) {
4326 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4327 throw new SecurityException("Only the system can query the permission provider");
4329 DevicePolicyData userData = getUserData(userHandle);
4330 return userData != null ? userData.mRestrictionsProvider : null;
4334 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
4335 int callingUserId = UserHandle.getCallingUserId();
4336 synchronized (this) {
4338 throw new NullPointerException("ComponentName is null");
4340 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4342 IPackageManager pm = AppGlobals.getPackageManager();
4343 long id = Binder.clearCallingIdentity();
4345 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
4346 pm.addCrossProfileIntentFilter(filter, who.getPackageName(),
4347 mContext.getUserId(), callingUserId, UserHandle.USER_OWNER, 0);
4349 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
4350 pm.addCrossProfileIntentFilter(filter, who.getPackageName(),
4351 mContext.getUserId(), UserHandle.USER_OWNER, callingUserId, 0);
4353 } catch (RemoteException re) {
4356 restoreCallingIdentity(id);
4361 public void clearCrossProfileIntentFilters(ComponentName who) {
4362 int callingUserId = UserHandle.getCallingUserId();
4363 synchronized (this) {
4365 throw new NullPointerException("ComponentName is null");
4367 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4368 IPackageManager pm = AppGlobals.getPackageManager();
4369 long id = Binder.clearCallingIdentity();
4371 pm.clearCrossProfileIntentFilters(callingUserId, who.getPackageName(),
4373 // If we want to support multiple managed profiles, we will have to only remove
4374 // those that have callingUserId as their target.
4375 pm.clearCrossProfileIntentFilters(UserHandle.USER_OWNER, who.getPackageName(),
4377 } catch (RemoteException re) {
4380 restoreCallingIdentity(id);
4386 * @return true if all packages in enabledPackages are either in the list
4387 * permittedList or are a system app.
4389 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
4390 List<String> permittedList) {
4391 int userIdToCheck = UserHandle.getCallingUserId();
4392 long id = Binder.clearCallingIdentity();
4394 // If we have an enabled packages list for a managed profile the packages
4395 // we should check are installed for the parent user.
4396 UserInfo user = mUserManager.getUserInfo(userIdToCheck);
4397 if (user.isManagedProfile()) {
4398 userIdToCheck = user.profileGroupId;
4401 IPackageManager pm = AppGlobals.getPackageManager();
4402 for (String enabledPackage : enabledPackages) {
4403 boolean systemService = false;
4405 ApplicationInfo applicationInfo = pm.getApplicationInfo(enabledPackage,
4406 PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
4407 systemService = (applicationInfo.flags
4408 & ApplicationInfo.FLAG_SYSTEM) != 0;
4409 } catch (RemoteException e) {
4410 Log.i(LOG_TAG, "Can't talk to package managed", e);
4412 if (!systemService && !permittedList.contains(enabledPackage)) {
4417 restoreCallingIdentity(id);
4422 private AccessibilityManager getAccessibilityManagerForUser(int userId) {
4423 // Not using AccessibilityManager.getInstance because that guesses
4424 // at the user you require based on callingUid and caches for a given
4426 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
4427 IAccessibilityManager service = iBinder == null
4428 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
4429 return new AccessibilityManager(mContext, service, userId);
4433 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
4438 throw new NullPointerException("ComponentName is null");
4441 if (packageList != null) {
4442 int userId = UserHandle.getCallingUserId();
4443 List<AccessibilityServiceInfo> enabledServices = null;
4444 long id = Binder.clearCallingIdentity();
4446 UserInfo user = mUserManager.getUserInfo(userId);
4447 if (user.isManagedProfile()) {
4448 userId = user.profileGroupId;
4450 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
4451 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
4452 AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
4454 restoreCallingIdentity(id);
4457 if (enabledServices != null) {
4458 List<String> enabledPackages = new ArrayList<String>();
4459 for (AccessibilityServiceInfo service : enabledServices) {
4460 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
4462 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
4463 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
4464 + "because it contains already enabled accesibility services.");
4470 synchronized (this) {
4471 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4472 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4473 admin.permittedAccessiblityServices = packageList;
4474 saveSettingsLocked(UserHandle.getCallingUserId());
4480 public List getPermittedAccessibilityServices(ComponentName who) {
4486 throw new NullPointerException("ComponentName is null");
4489 synchronized (this) {
4490 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4491 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4492 return admin.permittedAccessiblityServices;
4497 public List getPermittedAccessibilityServicesForUser(int userId) {
4501 synchronized (this) {
4502 List<String> result = null;
4503 // If we have multiple profiles we return the intersection of the
4504 // permitted lists. This can happen in cases where we have a device
4505 // and profile owner.
4506 List<UserInfo> profiles = mUserManager.getProfiles(userId);
4507 final int PROFILES_SIZE = profiles.size();
4508 for (int i = 0; i < PROFILES_SIZE; ++i) {
4509 // Just loop though all admins, only device or profiles
4510 // owners can have permitted lists set.
4511 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
4512 final int N = policy.mAdminList.size();
4513 for (int j = 0; j < N; j++) {
4514 ActiveAdmin admin = policy.mAdminList.get(j);
4515 List<String> fromAdmin = admin.permittedAccessiblityServices;
4516 if (fromAdmin != null) {
4517 if (result == null) {
4518 result = new ArrayList<String>(fromAdmin);
4520 result.retainAll(fromAdmin);
4526 // If we have a permitted list add all system accessibility services.
4527 if (result != null) {
4528 long id = Binder.clearCallingIdentity();
4530 UserInfo user = mUserManager.getUserInfo(userId);
4531 if (user.isManagedProfile()) {
4532 userId = user.profileGroupId;
4534 AccessibilityManager accessibilityManager =
4535 getAccessibilityManagerForUser(userId);
4536 List<AccessibilityServiceInfo> installedServices =
4537 accessibilityManager.getInstalledAccessibilityServiceList();
4539 IPackageManager pm = AppGlobals.getPackageManager();
4540 if (installedServices != null) {
4541 for (AccessibilityServiceInfo service : installedServices) {
4542 String packageName = service.getResolveInfo().serviceInfo.packageName;
4544 ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName,
4545 PackageManager.GET_UNINSTALLED_PACKAGES, userId);
4546 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4547 result.add(packageName);
4549 } catch (RemoteException e) {
4550 Log.i(LOG_TAG, "Accessibility service in missing package", e);
4555 restoreCallingIdentity(id);
4563 private boolean checkCallerIsCurrentUserOrProfile() {
4564 int callingUserId = UserHandle.getCallingUserId();
4565 long token = Binder.clearCallingIdentity();
4567 UserInfo currentUser;
4568 UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
4570 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
4571 } catch (RemoteException e) {
4572 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
4576 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
4577 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
4578 + "of a user that isn't the foreground user.");
4581 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
4582 Slog.e(LOG_TAG, "Cannot set permitted input methods "
4583 + "of a user that isn't the foreground user.");
4587 Binder.restoreCallingIdentity(token);
4593 public boolean setPermittedInputMethods(ComponentName who, List packageList) {
4598 throw new NullPointerException("ComponentName is null");
4601 // TODO When InputMethodManager supports per user calls remove
4602 // this restriction.
4603 if (!checkCallerIsCurrentUserOrProfile()) {
4607 if (packageList != null) {
4608 // InputMethodManager fetches input methods for current user.
4609 // So this can only be set when calling user is the current user
4610 // or parent is current user in case of managed profiles.
4611 InputMethodManager inputMethodManager = (InputMethodManager) mContext
4612 .getSystemService(Context.INPUT_METHOD_SERVICE);
4613 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
4615 if (enabledImes != null) {
4616 List<String> enabledPackages = new ArrayList<String>();
4617 for (InputMethodInfo ime : enabledImes) {
4618 enabledPackages.add(ime.getPackageName());
4620 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
4621 Slog.e(LOG_TAG, "Cannot set permitted input methods, "
4622 + "because it contains already enabled input method.");
4628 synchronized (this) {
4629 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4630 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4631 admin.permittedInputMethods = packageList;
4632 saveSettingsLocked(UserHandle.getCallingUserId());
4638 public List getPermittedInputMethods(ComponentName who) {
4644 throw new NullPointerException("ComponentName is null");
4647 synchronized (this) {
4648 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4649 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4650 return admin.permittedInputMethods;
4655 public List getPermittedInputMethodsForCurrentUser() {
4656 UserInfo currentUser;
4658 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
4659 } catch (RemoteException e) {
4660 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
4661 // Activity managed is dead, just allow all IMEs
4665 int userId = currentUser.id;
4666 synchronized (this) {
4667 List<String> result = null;
4668 // If we have multiple profiles we return the intersection of the
4669 // permitted lists. This can happen in cases where we have a device
4670 // and profile owner.
4671 List<UserInfo> profiles = mUserManager.getProfiles(userId);
4672 final int PROFILES_SIZE = profiles.size();
4673 for (int i = 0; i < PROFILES_SIZE; ++i) {
4674 // Just loop though all admins, only device or profiles
4675 // owners can have permitted lists set.
4676 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
4677 final int N = policy.mAdminList.size();
4678 for (int j = 0; j < N; j++) {
4679 ActiveAdmin admin = policy.mAdminList.get(j);
4680 List<String> fromAdmin = admin.permittedInputMethods;
4681 if (fromAdmin != null) {
4682 if (result == null) {
4683 result = new ArrayList<String>(fromAdmin);
4685 result.retainAll(fromAdmin);
4691 // If we have a permitted list add all system input methods.
4692 if (result != null) {
4693 InputMethodManager inputMethodManager = (InputMethodManager) mContext
4694 .getSystemService(Context.INPUT_METHOD_SERVICE);
4695 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
4696 long id = Binder.clearCallingIdentity();
4698 IPackageManager pm = AppGlobals.getPackageManager();
4700 for (InputMethodInfo ime : imes) {
4701 String packageName = ime.getPackageName();
4703 ApplicationInfo applicationInfo = pm.getApplicationInfo(
4704 packageName, PackageManager.GET_UNINSTALLED_PACKAGES,
4706 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4707 result.add(packageName);
4709 } catch (RemoteException e) {
4710 Log.i(LOG_TAG, "Input method for missing package", e);
4715 restoreCallingIdentity(id);
4723 public UserHandle createUser(ComponentName who, String name) {
4724 synchronized (this) {
4726 throw new NullPointerException("ComponentName is null");
4728 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4730 long id = Binder.clearCallingIdentity();
4732 UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */);
4733 if (userInfo != null) {
4734 return userInfo.getUserHandle();
4738 restoreCallingIdentity(id);
4744 public UserHandle createAndInitializeUser(ComponentName who, String name,
4745 String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) {
4746 UserHandle user = createUser(who, name);
4750 long id = Binder.clearCallingIdentity();
4752 String profileOwnerPkg = profileOwnerComponent.getPackageName();
4753 final IPackageManager ipm = AppGlobals.getPackageManager();
4754 IActivityManager activityManager = ActivityManagerNative.getDefault();
4757 // Install the profile owner if not present.
4758 if (!ipm.isPackageAvailable(profileOwnerPkg, user.getIdentifier())) {
4759 ipm.installExistingPackageAsUser(profileOwnerPkg, user.getIdentifier());
4762 // Start user in background.
4763 activityManager.startUserInBackground(user.getIdentifier());
4764 } catch (RemoteException e) {
4765 Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e);
4768 setActiveAdmin(profileOwnerComponent, true, user.getIdentifier(), adminExtras);
4769 setProfileOwner(profileOwnerComponent, ownerName, user.getIdentifier());
4772 restoreCallingIdentity(id);
4777 public boolean removeUser(ComponentName who, UserHandle userHandle) {
4778 synchronized (this) {
4780 throw new NullPointerException("ComponentName is null");
4782 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4784 long id = Binder.clearCallingIdentity();
4786 return mUserManager.removeUser(userHandle.getIdentifier());
4788 restoreCallingIdentity(id);
4794 public boolean switchUser(ComponentName who, UserHandle userHandle) {
4795 synchronized (this) {
4797 throw new NullPointerException("ComponentName is null");
4799 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4801 long id = Binder.clearCallingIdentity();
4803 int userId = UserHandle.USER_OWNER;
4804 if (userHandle != null) {
4805 userId = userHandle.getIdentifier();
4807 return ActivityManagerNative.getDefault().switchUser(userId);
4808 } catch (RemoteException e) {
4809 Log.e(LOG_TAG, "Couldn't switch user", e);
4812 restoreCallingIdentity(id);
4818 public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
4819 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4821 synchronized (this) {
4823 throw new NullPointerException("ComponentName is null");
4825 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4827 long id = Binder.clearCallingIdentity();
4829 return mUserManager.getApplicationRestrictions(packageName, userHandle);
4831 restoreCallingIdentity(id);
4837 public void setUserRestriction(ComponentName who, String key, boolean enabled) {
4838 final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
4839 final int userHandle = user.getIdentifier();
4840 synchronized (this) {
4842 throw new NullPointerException("ComponentName is null");
4844 ActiveAdmin activeAdmin =
4845 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4846 boolean isDeviceOwner = isDeviceOwner(activeAdmin.info.getPackageName());
4847 if (!isDeviceOwner && userHandle != UserHandle.USER_OWNER
4848 && DEVICE_OWNER_USER_RESTRICTIONS.contains(key)) {
4849 throw new SecurityException("Profile owners cannot set user restriction " + key);
4851 boolean alreadyRestricted = mUserManager.hasUserRestriction(key, user);
4853 IAudioService iAudioService = null;
4854 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)
4855 || UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
4856 iAudioService = IAudioService.Stub.asInterface(
4857 ServiceManager.getService(Context.AUDIO_SERVICE));
4860 if (enabled && !alreadyRestricted) {
4862 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
4863 iAudioService.setMicrophoneMute(true, who.getPackageName());
4864 } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
4865 iAudioService.setMasterMute(true, 0, who.getPackageName(), null);
4867 } catch (RemoteException re) {
4868 Slog.e(LOG_TAG, "Failed to talk to AudioService.", re);
4871 long id = Binder.clearCallingIdentity();
4873 if (enabled && !alreadyRestricted) {
4874 if (UserManager.DISALLOW_CONFIG_WIFI.equals(key)) {
4875 Settings.Secure.putIntForUser(mContext.getContentResolver(),
4876 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0,
4878 } else if (UserManager.DISALLOW_USB_FILE_TRANSFER.equals(key)) {
4879 UsbManager manager =
4880 (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
4881 manager.setCurrentFunction("none", false);
4882 } else if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
4883 Settings.Secure.putIntForUser(mContext.getContentResolver(),
4884 Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF,
4886 Settings.Secure.putStringForUser(mContext.getContentResolver(),
4887 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, "",
4889 } else if (UserManager.DISALLOW_DEBUGGING_FEATURES.equals(key)) {
4890 // Only disable adb if changing for primary user, since it is global
4891 if (userHandle == UserHandle.USER_OWNER) {
4892 Settings.Global.putStringForUser(mContext.getContentResolver(),
4893 Settings.Global.ADB_ENABLED, "0", userHandle);
4895 } else if (UserManager.ENSURE_VERIFY_APPS.equals(key)) {
4896 Settings.Global.putStringForUser(mContext.getContentResolver(),
4897 Settings.Global.PACKAGE_VERIFIER_ENABLE, "1",
4899 Settings.Global.putStringForUser(mContext.getContentResolver(),
4900 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1",
4902 } else if (UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES.equals(key)) {
4903 Settings.Secure.putIntForUser(mContext.getContentResolver(),
4904 Settings.Secure.INSTALL_NON_MARKET_APPS, 0,
4908 mUserManager.setUserRestriction(key, enabled, user);
4909 if (enabled != alreadyRestricted) {
4910 if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
4911 // Send out notifications however as some clients may want to reread the
4912 // value which actually changed due to a restriction having been applied.
4913 final String property = Settings.Secure.SYS_PROP_SETTING_VERSION;
4914 long version = SystemProperties.getLong(property, 0) + 1;
4915 SystemProperties.set(property, Long.toString(version));
4917 final String name = Settings.Secure.LOCATION_PROVIDERS_ALLOWED;
4918 Uri url = Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
4919 mContext.getContentResolver().notifyChange(url, null, true, userHandle);
4923 restoreCallingIdentity(id);
4925 if (!enabled && alreadyRestricted) {
4927 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
4928 iAudioService.setMicrophoneMute(false, who.getPackageName());
4929 } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
4930 iAudioService.setMasterMute(false, 0, who.getPackageName(), null);
4932 } catch (RemoteException re) {
4933 Slog.e(LOG_TAG, "Failed to talk to AudioService.", re);
4936 sendChangedNotification(userHandle);
4941 public boolean setApplicationHidden(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.setApplicationHiddenSettingAsUser(packageName, hidden, callingUserId);
4954 } catch (RemoteException re) {
4956 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
4958 restoreCallingIdentity(id);
4965 public boolean isApplicationHidden(ComponentName who, String packageName) {
4966 int callingUserId = UserHandle.getCallingUserId();
4967 synchronized (this) {
4969 throw new NullPointerException("ComponentName is null");
4971 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4973 long id = Binder.clearCallingIdentity();
4975 IPackageManager pm = AppGlobals.getPackageManager();
4976 return pm.getApplicationHiddenSettingAsUser(packageName, callingUserId);
4977 } catch (RemoteException re) {
4979 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
4981 restoreCallingIdentity(id);
4988 public void enableSystemApp(ComponentName who, String packageName) {
4989 synchronized (this) {
4991 throw new NullPointerException("ComponentName is null");
4994 // This API can only be called by an active device admin,
4995 // so try to retrieve it to check that the caller is one.
4996 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4998 int userId = UserHandle.getCallingUserId();
4999 long id = Binder.clearCallingIdentity();
5003 Slog.v(LOG_TAG, "installing " + packageName + " for "
5007 UserManager um = UserManager.get(mContext);
5008 UserInfo primaryUser = um.getProfileParent(userId);
5010 // Call did not come from a managed profile
5011 if (primaryUser == null) {
5012 primaryUser = um.getUserInfo(userId);
5015 IPackageManager pm = AppGlobals.getPackageManager();
5016 if (!isSystemApp(pm, packageName, primaryUser.id)) {
5017 throw new IllegalArgumentException("Only system apps can be enabled this way.");
5021 pm.installExistingPackageAsUser(packageName, userId);
5023 } catch (RemoteException re) {
5025 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
5027 restoreCallingIdentity(id);
5033 public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
5034 synchronized (this) {
5036 throw new NullPointerException("ComponentName is null");
5039 // This API can only be called by an active device admin,
5040 // so try to retrieve it to check that the caller is one.
5041 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5043 int userId = UserHandle.getCallingUserId();
5044 long id = Binder.clearCallingIdentity();
5047 UserManager um = UserManager.get(mContext);
5048 UserInfo primaryUser = um.getProfileParent(userId);
5050 // Call did not come from a managed profile.
5051 if (primaryUser == null) {
5052 primaryUser = um.getUserInfo(userId);
5055 IPackageManager pm = AppGlobals.getPackageManager();
5056 List<ResolveInfo> activitiesToEnable = pm.queryIntentActivities(intent,
5057 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5061 if (DBG) Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
5062 int numberOfAppsInstalled = 0;
5063 if (activitiesToEnable != null) {
5064 for (ResolveInfo info : activitiesToEnable) {
5065 if (info.activityInfo != null) {
5067 if (!isSystemApp(pm, info.activityInfo.packageName, primaryUser.id)) {
5068 throw new IllegalArgumentException(
5069 "Only system apps can be enabled this way.");
5073 numberOfAppsInstalled++;
5074 pm.installExistingPackageAsUser(info.activityInfo.packageName, userId);
5078 return numberOfAppsInstalled;
5079 } catch (RemoteException e) {
5081 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
5084 restoreCallingIdentity(id);
5089 private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
5090 throws RemoteException {
5091 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
5093 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0;
5097 public void setAccountManagementDisabled(ComponentName who, String accountType,
5102 synchronized (this) {
5104 throw new NullPointerException("ComponentName is null");
5106 ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5107 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5109 ap.accountTypesWithManagementDisabled.add(accountType);
5111 ap.accountTypesWithManagementDisabled.remove(accountType);
5113 saveSettingsLocked(UserHandle.getCallingUserId());
5118 public String[] getAccountTypesWithManagementDisabled() {
5119 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
5123 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
5124 enforceCrossUserPermission(userId);
5128 synchronized (this) {
5129 DevicePolicyData policy = getUserData(userId);
5130 final int N = policy.mAdminList.size();
5131 HashSet<String> resultSet = new HashSet<String>();
5132 for (int i = 0; i < N; i++) {
5133 ActiveAdmin admin = policy.mAdminList.get(i);
5134 resultSet.addAll(admin.accountTypesWithManagementDisabled);
5136 return resultSet.toArray(new String[resultSet.size()]);
5141 public void setUninstallBlocked(ComponentName who, String packageName,
5142 boolean uninstallBlocked) {
5143 final int userId = UserHandle.getCallingUserId();
5145 synchronized (this) {
5147 throw new NullPointerException("ComponentName is null");
5149 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5151 long id = Binder.clearCallingIdentity();
5153 IPackageManager pm = AppGlobals.getPackageManager();
5154 pm.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
5155 } catch (RemoteException re) {
5156 // Shouldn't happen.
5157 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
5159 restoreCallingIdentity(id);
5165 public boolean isUninstallBlocked(ComponentName who, String packageName) {
5166 // This function should return true if and only if the package is blocked by
5167 // setUninstallBlocked(). It should still return false for other cases of blocks, such as
5168 // when the package is a system app, or when it is an active device admin.
5169 final int userId = UserHandle.getCallingUserId();
5171 synchronized (this) {
5173 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5176 long id = Binder.clearCallingIdentity();
5178 IPackageManager pm = AppGlobals.getPackageManager();
5179 return pm.getBlockUninstallForUser(packageName, userId);
5180 } catch (RemoteException re) {
5181 // Shouldn't happen.
5182 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
5184 restoreCallingIdentity(id);
5191 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
5195 synchronized (this) {
5197 throw new NullPointerException("ComponentName is null");
5199 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5200 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5201 if (admin.disableCallerId != disabled) {
5202 admin.disableCallerId = disabled;
5203 saveSettingsLocked(UserHandle.getCallingUserId());
5209 public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
5214 synchronized (this) {
5216 throw new NullPointerException("ComponentName is null");
5219 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5220 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5221 return admin.disableCallerId;
5226 public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
5227 // TODO: Should there be a check to make sure this relationship is within a profile group?
5228 //enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5229 synchronized (this) {
5230 ActiveAdmin admin = getProfileOwnerAdmin(userId);
5231 return (admin != null) ? admin.disableCallerId : false;
5236 * Sets which packages may enter lock task mode.
5238 * This function can only be called by the device owner.
5239 * @param components The list of components allowed to enter lock task mode.
5241 public void setLockTaskPackages(ComponentName who, String[] packages) throws SecurityException {
5242 synchronized (this) {
5244 throw new NullPointerException("ComponentName is null");
5246 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5248 int userHandle = Binder.getCallingUserHandle().getIdentifier();
5249 DevicePolicyData policy = getUserData(userHandle);
5250 policy.mLockTaskPackages.clear();
5251 if (packages != null) {
5252 for (int j = 0; j < packages.length; j++) {
5253 String pkg = packages[j];
5254 policy.mLockTaskPackages.add(pkg);
5258 // Store the settings persistently.
5259 saveSettingsLocked(userHandle);
5264 * This function returns the list of components allowed to start the task lock mode.
5266 public String[] getLockTaskPackages(ComponentName who) {
5267 synchronized (this) {
5269 throw new NullPointerException("ComponentName is null");
5271 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5273 int userHandle = Binder.getCallingUserHandle().getIdentifier();
5274 DevicePolicyData policy = getUserData(userHandle);
5275 return policy.mLockTaskPackages.toArray(new String[0]);
5280 * This function lets the caller know whether the given package is allowed to start the
5282 * @param pkg The package to check
5284 public boolean isLockTaskPermitted(String pkg) {
5285 // Get current user's devicepolicy
5286 int uid = Binder.getCallingUid();
5287 int userHandle = UserHandle.getUserId(uid);
5288 DevicePolicyData policy = getUserData(userHandle);
5289 synchronized (this) {
5290 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
5291 String lockTaskPackage = policy.mLockTaskPackages.get(i);
5293 // If the given package equals one of the packages stored our list,
5294 // we allow this package to start lock task mode.
5295 if (lockTaskPackage.equals(pkg)) {
5304 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
5305 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
5306 throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
5308 synchronized (this) {
5309 final DevicePolicyData policy = getUserData(userHandle);
5310 Bundle adminExtras = new Bundle();
5311 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
5312 for (ActiveAdmin admin : policy.mAdminList) {
5313 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
5314 boolean ownsProfile = (getProfileOwner(userHandle) != null
5315 && getProfileOwner(userHandle).equals(admin.info.getPackageName()));
5316 if (ownsDevice || ownsProfile) {
5318 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
5321 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
5329 public void setGlobalSetting(ComponentName who, String setting, String value) {
5330 final ContentResolver contentResolver = mContext.getContentResolver();
5332 synchronized (this) {
5334 throw new NullPointerException("ComponentName is null");
5336 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5338 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
5339 throw new SecurityException(String.format(
5340 "Permission denial: device owners cannot update %1$s", setting));
5343 long id = Binder.clearCallingIdentity();
5345 Settings.Global.putString(contentResolver, setting, value);
5347 restoreCallingIdentity(id);
5353 public void setSecureSetting(ComponentName who, String setting, String value) {
5354 int callingUserId = UserHandle.getCallingUserId();
5355 final ContentResolver contentResolver = mContext.getContentResolver();
5357 synchronized (this) {
5359 throw new NullPointerException("ComponentName is null");
5361 ActiveAdmin activeAdmin =
5362 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5364 if (isDeviceOwner(activeAdmin.info.getPackageName())) {
5365 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
5366 throw new SecurityException(String.format(
5367 "Permission denial: Device owners cannot update %1$s", setting));
5369 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
5370 throw new SecurityException(String.format(
5371 "Permission denial: Profile owners cannot update %1$s", setting));
5374 long id = Binder.clearCallingIdentity();
5376 Settings.Secure.putStringForUser(contentResolver, setting, value, callingUserId);
5378 restoreCallingIdentity(id);
5384 public void setMasterVolumeMuted(ComponentName who, boolean on) {
5385 final ContentResolver contentResolver = mContext.getContentResolver();
5387 synchronized (this) {
5389 throw new NullPointerException("ComponentName is null");
5391 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5393 IAudioService iAudioService = IAudioService.Stub.asInterface(
5394 ServiceManager.getService(Context.AUDIO_SERVICE));
5396 iAudioService.setMasterMute(on, 0, who.getPackageName(), null);
5397 } catch (RemoteException re) {
5398 Slog.e(LOG_TAG, "Failed to setMasterMute", re);
5404 public boolean isMasterVolumeMuted(ComponentName who) {
5405 final ContentResolver contentResolver = mContext.getContentResolver();
5407 synchronized (this) {
5409 throw new NullPointerException("ComponentName is null");
5411 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5413 AudioManager audioManager =
5414 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
5415 return audioManager.isMasterMute();
5420 * We need to update the internal state of whether a user has completed setup once. After
5421 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
5422 * as we don't trust any apps that might try to reset it.
5424 * Unfortunately, we don't know which user's setup state was changed, so we write all of
5427 void updateUserSetupComplete() {
5428 List<UserInfo> users = mUserManager.getUsers(true);
5429 ContentResolver resolver = mContext.getContentResolver();
5430 final int N = users.size();
5431 for (int i = 0; i < N; i++) {
5432 int userHandle = users.get(i).id;
5433 if (Settings.Secure.getIntForUser(resolver, Settings.Secure.USER_SETUP_COMPLETE, 0,
5435 DevicePolicyData policy = getUserData(userHandle);
5436 if (!policy.mUserSetupComplete) {
5437 policy.mUserSetupComplete = true;
5438 synchronized (this) {
5439 saveSettingsLocked(userHandle);
5446 private class SetupContentObserver extends ContentObserver {
5448 private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
5449 Settings.Secure.USER_SETUP_COMPLETE);
5451 public SetupContentObserver(Handler handler) {
5455 void register(ContentResolver resolver) {
5456 resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
5460 public void onChange(boolean selfChange, Uri uri) {
5461 if (mUserSetupComplete.equals(uri)) {
5462 updateUserSetupComplete();
5467 private final class LocalService extends DevicePolicyManagerInternal {
5468 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
5471 public List<String> getCrossProfileWidgetProviders(int profileId) {
5472 synchronized (DevicePolicyManagerService.this) {
5473 if (mDeviceOwner == null) {
5474 return Collections.emptyList();
5476 ComponentName ownerComponent = mDeviceOwner.getProfileOwnerComponent(profileId);
5477 if (ownerComponent == null) {
5478 return Collections.emptyList();
5481 DevicePolicyData policy = getUserDataUnchecked(profileId);
5482 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
5484 if (admin == null || admin.crossProfileWidgetProviders == null
5485 || admin.crossProfileWidgetProviders.isEmpty()) {
5486 return Collections.emptyList();
5489 return admin.crossProfileWidgetProviders;
5494 public void addOnCrossProfileWidgetProvidersChangeListener(
5495 OnCrossProfileWidgetProvidersChangeListener listener) {
5496 synchronized (DevicePolicyManagerService.this) {
5497 if (mWidgetProviderListeners == null) {
5498 mWidgetProviderListeners = new ArrayList<>();
5500 if (!mWidgetProviderListeners.contains(listener)) {
5501 mWidgetProviderListeners.add(listener);
5506 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
5507 final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
5508 synchronized (DevicePolicyManagerService.this) {
5509 listeners = new ArrayList<>(mWidgetProviderListeners);
5511 final int listenerCount = listeners.size();
5512 for (int i = 0; i < listenerCount; i++) {
5513 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
5514 listener.onCrossProfileWidgetProvidersChanged(userId, packages);