DevicePolicyManagerService.java revision 917c4e4d453f9f36fb6945cf1e3e11f45314d602
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17package com.android.server.devicepolicy; 18 19import static android.Manifest.permission.MANAGE_CA_CERTIFICATES; 20import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; 21import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE; 22import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA; 23import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES; 24 25import android.Manifest.permission; 26import android.accessibilityservice.AccessibilityServiceInfo; 27import android.accounts.AccountManager; 28import android.app.Activity; 29import android.app.ActivityManagerNative; 30import android.app.AlarmManager; 31import android.app.AppGlobals; 32import android.app.IActivityManager; 33import android.app.Notification; 34import android.app.NotificationManager; 35import android.app.PendingIntent; 36import android.app.StatusBarManager; 37import android.app.admin.DeviceAdminInfo; 38import android.app.admin.DeviceAdminReceiver; 39import android.app.admin.DevicePolicyManager; 40import android.app.admin.DevicePolicyManagerInternal; 41import android.app.admin.IDevicePolicyManager; 42import android.app.backup.IBackupManager; 43import android.content.BroadcastReceiver; 44import android.content.ComponentName; 45import android.content.ContentResolver; 46import android.content.Context; 47import android.content.Intent; 48import android.content.IntentFilter; 49import android.content.pm.ActivityInfo; 50import android.content.pm.ApplicationInfo; 51import android.content.pm.IPackageManager; 52import android.content.pm.PackageManager; 53import android.content.pm.PackageManager.NameNotFoundException; 54import android.content.pm.ResolveInfo; 55import android.content.pm.ServiceInfo; 56import android.content.pm.UserInfo; 57import android.database.ContentObserver; 58import android.graphics.Bitmap; 59import android.hardware.usb.UsbManager; 60import android.media.AudioManager; 61import android.media.IAudioService; 62import android.net.ConnectivityManager; 63import android.net.ProxyInfo; 64import android.net.Uri; 65import android.os.AsyncTask; 66import android.os.Binder; 67import android.os.Bundle; 68import android.os.Environment; 69import android.os.FileUtils; 70import android.os.Handler; 71import android.os.IBinder; 72import android.os.PersistableBundle; 73import android.os.PowerManager; 74import android.os.PowerManagerInternal; 75import android.os.Process; 76import android.os.RecoverySystem; 77import android.os.RemoteCallback; 78import android.os.RemoteException; 79import android.os.ServiceManager; 80import android.os.SystemClock; 81import android.os.SystemProperties; 82import android.os.UserHandle; 83import android.os.UserManager; 84import android.provider.ContactsContract.QuickContact; 85import android.provider.ContactsInternal; 86import android.provider.Settings; 87import android.security.Credentials; 88import android.security.IKeyChainAliasCallback; 89import android.security.IKeyChainService; 90import android.security.KeyChain; 91import android.security.KeyChain.KeyChainConnection; 92import android.text.TextUtils; 93import android.service.persistentdata.PersistentDataBlockManager; 94import android.util.Log; 95import android.util.PrintWriterPrinter; 96import android.util.Printer; 97import android.util.Slog; 98import android.util.SparseArray; 99import android.util.Xml; 100import android.view.accessibility.AccessibilityManager; 101import android.view.accessibility.IAccessibilityManager; 102import android.view.inputmethod.InputMethodInfo; 103import android.view.inputmethod.InputMethodManager; 104import android.view.IWindowManager; 105 106import com.android.internal.R; 107import com.android.internal.os.storage.ExternalStorageFormatter; 108import com.android.internal.statusbar.IStatusBarService; 109import com.android.internal.util.FastXmlSerializer; 110import com.android.internal.util.JournaledFile; 111import com.android.internal.util.Preconditions; 112import com.android.internal.util.XmlUtils; 113import com.android.internal.widget.LockPatternUtils; 114import com.android.server.LocalServices; 115import com.android.server.SystemService; 116import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo; 117 118import org.xmlpull.v1.XmlPullParser; 119 120import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; 121import static org.xmlpull.v1.XmlPullParser.END_TAG; 122import static org.xmlpull.v1.XmlPullParser.TEXT; 123 124import org.xmlpull.v1.XmlPullParserException; 125import org.xmlpull.v1.XmlSerializer; 126 127import java.io.ByteArrayInputStream; 128import java.io.File; 129import java.io.FileDescriptor; 130import java.io.FileInputStream; 131import java.io.FileNotFoundException; 132import java.io.FileOutputStream; 133import java.io.IOException; 134import java.io.PrintWriter; 135import java.security.cert.CertificateException; 136import java.security.cert.CertificateFactory; 137import java.security.cert.X509Certificate; 138import java.text.DateFormat; 139import java.util.ArrayList; 140import java.util.Arrays; 141import java.util.Collections; 142import java.util.Date; 143import java.util.HashMap; 144import java.util.HashSet; 145import java.util.List; 146import java.util.Map.Entry; 147import java.util.Set; 148 149/** 150 * Implementation of the device policy APIs. 151 */ 152public class DevicePolicyManagerService extends IDevicePolicyManager.Stub { 153 154 private static final String LOG_TAG = "DevicePolicyManagerService"; 155 156 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE 157 158 private static final String DEVICE_POLICIES_XML = "device_policies.xml"; 159 160 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component"; 161 162 private static final String TAG_STATUS_BAR = "statusbar"; 163 164 private static final String ATTR_ENABLED = "enabled"; 165 166 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML = 167 "do-not-ask-credentials-on-boot"; 168 169 private static final int REQUEST_EXPIRE_PASSWORD = 5571; 170 171 private static final long MS_PER_DAY = 86400 * 1000; 172 173 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms 174 175 protected static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION 176 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION"; 177 178 private static final int MONITORING_CERT_NOTIFICATION_ID = R.string.ssl_ca_cert_warning; 179 180 private static final boolean DBG = false; 181 182 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider"; 183 private static final String ATTR_SETUP_COMPLETE = "setup-complete"; 184 185 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer"; 186 187 private static final int STATUS_BAR_DISABLE_MASK = 188 StatusBarManager.DISABLE_EXPAND | 189 StatusBarManager.DISABLE_NOTIFICATION_ICONS | 190 StatusBarManager.DISABLE_NOTIFICATION_ALERTS | 191 StatusBarManager.DISABLE_SEARCH; 192 193 private static final Set<String> DEVICE_OWNER_USER_RESTRICTIONS; 194 static { 195 DEVICE_OWNER_USER_RESTRICTIONS = new HashSet(); 196 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_USB_FILE_TRANSFER); 197 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_TETHERING); 198 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_FACTORY_RESET); 199 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADD_USER); 200 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_CELL_BROADCASTS); 201 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS); 202 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA); 203 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_UNMUTE_MICROPHONE); 204 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADJUST_VOLUME); 205 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SMS); 206 DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SAFE_BOOT); 207 } 208 209 // The following user restrictions cannot be changed by any active admin, including device 210 // owner and profile owner. 211 private static final Set<String> IMMUTABLE_USER_RESTRICTIONS; 212 static { 213 IMMUTABLE_USER_RESTRICTIONS = new HashSet(); 214 IMMUTABLE_USER_RESTRICTIONS.add(UserManager.DISALLOW_WALLPAPER); 215 } 216 217 private static final Set<String> SECURE_SETTINGS_WHITELIST; 218 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST; 219 private static final Set<String> GLOBAL_SETTINGS_WHITELIST; 220 static { 221 SECURE_SETTINGS_WHITELIST = new HashSet(); 222 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD); 223 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS); 224 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS); 225 226 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new HashSet(); 227 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST); 228 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE); 229 230 GLOBAL_SETTINGS_WHITELIST = new HashSet(); 231 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED); 232 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME); 233 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE); 234 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING); 235 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED); 236 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.MODE_RINGER); 237 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.NETWORK_PREFERENCE); 238 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED); 239 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY); 240 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN); 241 } 242 243 final Context mContext; 244 final UserManager mUserManager; 245 final PowerManager.WakeLock mWakeLock; 246 247 final LocalService mLocalService; 248 249 final PowerManager mPowerManager; 250 final PowerManagerInternal mPowerManagerInternal; 251 252 IWindowManager mIWindowManager; 253 NotificationManager mNotificationManager; 254 255 // Stores and loads state on device and profile owners. 256 private DeviceOwner mDeviceOwner; 257 258 private final Binder mToken = new Binder(); 259 260 /** 261 * Whether or not device admin feature is supported. If it isn't return defaults for all 262 * public methods. 263 */ 264 private boolean mHasFeature; 265 266 public static final class Lifecycle extends SystemService { 267 private DevicePolicyManagerService mService; 268 269 public Lifecycle(Context context) { 270 super(context); 271 mService = new DevicePolicyManagerService(context); 272 } 273 274 @Override 275 public void onStart() { 276 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService); 277 } 278 279 @Override 280 public void onBootPhase(int phase) { 281 if (phase == PHASE_LOCK_SETTINGS_READY) { 282 mService.systemReady(); 283 } 284 } 285 } 286 287 public static class DevicePolicyData { 288 int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 289 int mActivePasswordLength = 0; 290 int mActivePasswordUpperCase = 0; 291 int mActivePasswordLowerCase = 0; 292 int mActivePasswordLetters = 0; 293 int mActivePasswordNumeric = 0; 294 int mActivePasswordSymbols = 0; 295 int mActivePasswordNonLetter = 0; 296 int mFailedPasswordAttempts = 0; 297 298 int mUserHandle; 299 int mPasswordOwner = -1; 300 long mLastMaximumTimeToLock = -1; 301 boolean mUserSetupComplete = false; 302 303 final HashMap<ComponentName, ActiveAdmin> mAdminMap = new HashMap<>(); 304 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>(); 305 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>(); 306 307 // This is the list of component allowed to start lock task mode. 308 List<String> mLockTaskPackages = new ArrayList<>(); 309 310 boolean mStatusBarEnabledState = true; 311 312 ComponentName mRestrictionsProvider; 313 314 String mDelegatedCertInstallerPackage; 315 316 boolean doNotAskCredentialsOnBoot = false; 317 318 public DevicePolicyData(int userHandle) { 319 mUserHandle = userHandle; 320 } 321 } 322 323 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>(); 324 325 Handler mHandler = new Handler(); 326 327 BroadcastReceiver mReceiver = new BroadcastReceiver() { 328 @Override 329 public void onReceive(Context context, Intent intent) { 330 final String action = intent.getAction(); 331 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 332 getSendingUserId()); 333 if (Intent.ACTION_BOOT_COMPLETED.equals(action) 334 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) { 335 if (DBG) Slog.v(LOG_TAG, "Sending password expiration notifications for action " 336 + action + " for user " + userHandle); 337 mHandler.post(new Runnable() { 338 public void run() { 339 handlePasswordExpirationNotification(userHandle); 340 } 341 }); 342 } 343 if (Intent.ACTION_BOOT_COMPLETED.equals(action) 344 || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) { 345 new MonitoringCertNotificationTask().execute(intent); 346 } 347 if (Intent.ACTION_USER_REMOVED.equals(action)) { 348 removeUserData(userHandle); 349 } else if (Intent.ACTION_USER_STARTED.equals(action) 350 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { 351 352 if (Intent.ACTION_USER_STARTED.equals(action)) { 353 // Reset the policy data 354 synchronized (DevicePolicyManagerService.this) { 355 mUserData.remove(userHandle); 356 } 357 } 358 handlePackagesChanged(null /* check all admins */, userHandle); 359 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action) 360 || (Intent.ACTION_PACKAGE_ADDED.equals(action) 361 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) { 362 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 363 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action) 364 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 365 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 366 } 367 } 368 }; 369 370 static class ActiveAdmin { 371 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features"; 372 private static final String TAG_DISABLE_CAMERA = "disable-camera"; 373 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id"; 374 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING 375 = "disable-bt-contacts-sharing"; 376 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture"; 377 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management"; 378 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time"; 379 private static final String TAG_ACCOUNT_TYPE = "account-type"; 380 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES 381 = "permitted-accessiblity-services"; 382 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested"; 383 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features"; 384 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options"; 385 private static final String TAG_TRUST_AGENT_COMPONENT = "component"; 386 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date"; 387 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout"; 388 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list"; 389 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec"; 390 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy"; 391 private static final String TAG_PERMITTED_IMES = "permitted-imes"; 392 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe"; 393 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock"; 394 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter"; 395 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols"; 396 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric"; 397 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters"; 398 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase"; 399 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase"; 400 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length"; 401 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length"; 402 private static final String ATTR_VALUE = "value"; 403 private static final String TAG_PASSWORD_QUALITY = "password-quality"; 404 private static final String TAG_POLICIES = "policies"; 405 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS = 406 "cross-profile-widget-providers"; 407 private static final String TAG_PROVIDER = "provider"; 408 private static final String TAG_PACKAGE_LIST_ITEM = "item"; 409 410 final DeviceAdminInfo info; 411 412 int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 413 414 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0; 415 int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH; 416 417 static final int DEF_PASSWORD_HISTORY_LENGTH = 0; 418 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH; 419 420 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0; 421 int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE; 422 423 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0; 424 int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE; 425 426 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1; 427 int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS; 428 429 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1; 430 int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC; 431 432 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1; 433 int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS; 434 435 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0; 436 int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER; 437 438 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0; 439 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK; 440 441 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0; 442 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE; 443 444 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0; 445 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT; 446 447 static final long DEF_PASSWORD_EXPIRATION_DATE = 0; 448 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE; 449 450 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none 451 452 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED; 453 454 boolean encryptionRequested = false; 455 boolean disableCamera = false; 456 boolean disableCallerId = false; 457 boolean disableBluetoothContactSharing = true; 458 boolean disableScreenCapture = false; // Can only be set by a device/profile owner. 459 boolean requireAutoTime = false; // Can only be set by a device owner. 460 461 static class TrustAgentInfo { 462 public PersistableBundle options; 463 TrustAgentInfo(PersistableBundle bundle) { 464 options = bundle; 465 } 466 } 467 468 Set<String> accountTypesWithManagementDisabled = new HashSet<String>(); 469 470 // The list of permitted accessibility services package namesas set by a profile 471 // or device owner. Null means all accessibility services are allowed, empty means 472 // none except system services are allowed. 473 List<String> permittedAccessiblityServices; 474 475 // The list of permitted input methods package names as set by a profile or device owner. 476 // Null means all input methods are allowed, empty means none except system imes are 477 // allowed. 478 List<String> permittedInputMethods; 479 480 // TODO: review implementation decisions with frameworks team 481 boolean specifiesGlobalProxy = false; 482 String globalProxySpec = null; 483 String globalProxyExclusionList = null; 484 485 HashMap<String, TrustAgentInfo> trustAgentInfos = new HashMap<String, TrustAgentInfo>(); 486 487 List<String> crossProfileWidgetProviders; 488 489 ActiveAdmin(DeviceAdminInfo _info) { 490 info = _info; 491 } 492 493 int getUid() { return info.getActivityInfo().applicationInfo.uid; } 494 495 public UserHandle getUserHandle() { 496 return new UserHandle(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid)); 497 } 498 499 void writeToXml(XmlSerializer out) 500 throws IllegalArgumentException, IllegalStateException, IOException { 501 out.startTag(null, TAG_POLICIES); 502 info.writePoliciesToXml(out); 503 out.endTag(null, TAG_POLICIES); 504 if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { 505 out.startTag(null, TAG_PASSWORD_QUALITY); 506 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality)); 507 out.endTag(null, TAG_PASSWORD_QUALITY); 508 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) { 509 out.startTag(null, TAG_MIN_PASSWORD_LENGTH); 510 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength)); 511 out.endTag(null, TAG_MIN_PASSWORD_LENGTH); 512 } 513 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) { 514 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH); 515 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength)); 516 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH); 517 } 518 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) { 519 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE); 520 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase)); 521 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE); 522 } 523 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) { 524 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE); 525 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase)); 526 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE); 527 } 528 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) { 529 out.startTag(null, TAG_MIN_PASSWORD_LETTERS); 530 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters)); 531 out.endTag(null, TAG_MIN_PASSWORD_LETTERS); 532 } 533 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) { 534 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC); 535 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric)); 536 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC); 537 } 538 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) { 539 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS); 540 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols)); 541 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS); 542 } 543 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) { 544 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER); 545 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter)); 546 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER); 547 } 548 } 549 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) { 550 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK); 551 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock)); 552 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK); 553 } 554 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 555 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE); 556 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe)); 557 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE); 558 } 559 if (specifiesGlobalProxy) { 560 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY); 561 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy)); 562 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY); 563 if (globalProxySpec != null) { 564 out.startTag(null, TAG_GLOBAL_PROXY_SPEC); 565 out.attribute(null, ATTR_VALUE, globalProxySpec); 566 out.endTag(null, TAG_GLOBAL_PROXY_SPEC); 567 } 568 if (globalProxyExclusionList != null) { 569 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST); 570 out.attribute(null, ATTR_VALUE, globalProxyExclusionList); 571 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST); 572 } 573 } 574 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) { 575 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT); 576 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout)); 577 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT); 578 } 579 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) { 580 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE); 581 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate)); 582 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE); 583 } 584 if (encryptionRequested) { 585 out.startTag(null, TAG_ENCRYPTION_REQUESTED); 586 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested)); 587 out.endTag(null, TAG_ENCRYPTION_REQUESTED); 588 } 589 if (disableCamera) { 590 out.startTag(null, TAG_DISABLE_CAMERA); 591 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera)); 592 out.endTag(null, TAG_DISABLE_CAMERA); 593 } 594 if (disableCallerId) { 595 out.startTag(null, TAG_DISABLE_CALLER_ID); 596 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId)); 597 out.endTag(null, TAG_DISABLE_CALLER_ID); 598 } 599 if (disableBluetoothContactSharing) { 600 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING); 601 out.attribute(null, ATTR_VALUE, 602 Boolean.toString(disableBluetoothContactSharing)); 603 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING); 604 } 605 if (disableScreenCapture) { 606 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE); 607 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture)); 608 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE); 609 } 610 if (requireAutoTime) { 611 out.startTag(null, TAG_REQUIRE_AUTO_TIME); 612 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime)); 613 out.endTag(null, TAG_REQUIRE_AUTO_TIME); 614 } 615 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) { 616 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES); 617 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures)); 618 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES); 619 } 620 if (!accountTypesWithManagementDisabled.isEmpty()) { 621 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT); 622 for (String ac : accountTypesWithManagementDisabled) { 623 out.startTag(null, TAG_ACCOUNT_TYPE); 624 out.attribute(null, ATTR_VALUE, ac); 625 out.endTag(null, TAG_ACCOUNT_TYPE); 626 } 627 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT); 628 } 629 if (!trustAgentInfos.isEmpty()) { 630 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet(); 631 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES); 632 for (Entry<String, TrustAgentInfo> entry : set) { 633 TrustAgentInfo trustAgentInfo = entry.getValue(); 634 out.startTag(null, TAG_TRUST_AGENT_COMPONENT); 635 out.attribute(null, ATTR_VALUE, entry.getKey()); 636 if (trustAgentInfo.options != null) { 637 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS); 638 try { 639 trustAgentInfo.options.saveToXml(out); 640 } catch (XmlPullParserException e) { 641 Log.e(LOG_TAG, "Failed to save TrustAgent options", e); 642 } 643 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS); 644 } 645 out.endTag(null, TAG_TRUST_AGENT_COMPONENT); 646 } 647 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES); 648 } 649 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) { 650 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS); 651 final int providerCount = crossProfileWidgetProviders.size(); 652 for (int i = 0; i < providerCount; i++) { 653 String provider = crossProfileWidgetProviders.get(i); 654 out.startTag(null, TAG_PROVIDER); 655 out.attribute(null, ATTR_VALUE, provider); 656 out.endTag(null, TAG_PROVIDER); 657 } 658 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS); 659 } 660 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES, 661 permittedAccessiblityServices); 662 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods); 663 } 664 665 void writePackageListToXml(XmlSerializer out, String outerTag, 666 List<String> packageList) 667 throws IllegalArgumentException, IllegalStateException, IOException { 668 if (packageList == null) { 669 return; 670 } 671 672 out.startTag(null, outerTag); 673 for (String packageName : packageList) { 674 out.startTag(null, TAG_PACKAGE_LIST_ITEM); 675 out.attribute(null, ATTR_VALUE, packageName); 676 out.endTag(null, TAG_PACKAGE_LIST_ITEM); 677 } 678 out.endTag(null, outerTag); 679 } 680 681 void readFromXml(XmlPullParser parser) 682 throws XmlPullParserException, IOException { 683 int outerDepth = parser.getDepth(); 684 int type; 685 while ((type=parser.next()) != END_DOCUMENT 686 && (type != END_TAG || parser.getDepth() > outerDepth)) { 687 if (type == END_TAG || type == TEXT) { 688 continue; 689 } 690 String tag = parser.getName(); 691 if (TAG_POLICIES.equals(tag)) { 692 info.readPoliciesFromXml(parser); 693 } else if (TAG_PASSWORD_QUALITY.equals(tag)) { 694 passwordQuality = Integer.parseInt( 695 parser.getAttributeValue(null, ATTR_VALUE)); 696 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) { 697 minimumPasswordLength = Integer.parseInt( 698 parser.getAttributeValue(null, ATTR_VALUE)); 699 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) { 700 passwordHistoryLength = Integer.parseInt( 701 parser.getAttributeValue(null, ATTR_VALUE)); 702 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) { 703 minimumPasswordUpperCase = Integer.parseInt( 704 parser.getAttributeValue(null, ATTR_VALUE)); 705 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) { 706 minimumPasswordLowerCase = Integer.parseInt( 707 parser.getAttributeValue(null, ATTR_VALUE)); 708 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) { 709 minimumPasswordLetters = Integer.parseInt( 710 parser.getAttributeValue(null, ATTR_VALUE)); 711 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) { 712 minimumPasswordNumeric = Integer.parseInt( 713 parser.getAttributeValue(null, ATTR_VALUE)); 714 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) { 715 minimumPasswordSymbols = Integer.parseInt( 716 parser.getAttributeValue(null, ATTR_VALUE)); 717 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) { 718 minimumPasswordNonLetter = Integer.parseInt( 719 parser.getAttributeValue(null, ATTR_VALUE)); 720 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) { 721 maximumTimeToUnlock = Long.parseLong( 722 parser.getAttributeValue(null, ATTR_VALUE)); 723 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) { 724 maximumFailedPasswordsForWipe = Integer.parseInt( 725 parser.getAttributeValue(null, ATTR_VALUE)); 726 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) { 727 specifiesGlobalProxy = Boolean.parseBoolean( 728 parser.getAttributeValue(null, ATTR_VALUE)); 729 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) { 730 globalProxySpec = 731 parser.getAttributeValue(null, ATTR_VALUE); 732 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) { 733 globalProxyExclusionList = 734 parser.getAttributeValue(null, ATTR_VALUE); 735 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) { 736 passwordExpirationTimeout = Long.parseLong( 737 parser.getAttributeValue(null, ATTR_VALUE)); 738 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) { 739 passwordExpirationDate = Long.parseLong( 740 parser.getAttributeValue(null, ATTR_VALUE)); 741 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) { 742 encryptionRequested = Boolean.parseBoolean( 743 parser.getAttributeValue(null, ATTR_VALUE)); 744 } else if (TAG_DISABLE_CAMERA.equals(tag)) { 745 disableCamera = Boolean.parseBoolean( 746 parser.getAttributeValue(null, ATTR_VALUE)); 747 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) { 748 disableCallerId = Boolean.parseBoolean( 749 parser.getAttributeValue(null, ATTR_VALUE)); 750 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) { 751 disableBluetoothContactSharing = Boolean.parseBoolean(parser 752 .getAttributeValue(null, ATTR_VALUE)); 753 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) { 754 disableScreenCapture = Boolean.parseBoolean( 755 parser.getAttributeValue(null, ATTR_VALUE)); 756 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) { 757 requireAutoTime= Boolean.parseBoolean( 758 parser.getAttributeValue(null, ATTR_VALUE)); 759 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) { 760 disabledKeyguardFeatures = Integer.parseInt( 761 parser.getAttributeValue(null, ATTR_VALUE)); 762 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) { 763 accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag); 764 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) { 765 trustAgentInfos = getAllTrustAgentInfos(parser, tag); 766 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) { 767 crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag); 768 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) { 769 permittedAccessiblityServices = readPackageList(parser, tag); 770 } else if (TAG_PERMITTED_IMES.equals(tag)) { 771 permittedInputMethods = readPackageList(parser, tag); 772 } else { 773 Slog.w(LOG_TAG, "Unknown admin tag: " + tag); 774 } 775 XmlUtils.skipCurrentTag(parser); 776 } 777 } 778 779 private List<String> readPackageList(XmlPullParser parser, 780 String tag) throws XmlPullParserException, IOException { 781 List<String> result = new ArrayList<String>(); 782 int outerDepth = parser.getDepth(); 783 int outerType; 784 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT 785 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 786 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) { 787 continue; 788 } 789 String outerTag = parser.getName(); 790 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) { 791 String packageName = parser.getAttributeValue(null, ATTR_VALUE); 792 if (packageName != null) { 793 result.add(packageName); 794 } else { 795 Slog.w(LOG_TAG, "Package name missing under " + outerTag); 796 } 797 } else { 798 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag); 799 } 800 } 801 return result; 802 } 803 804 private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag) 805 throws XmlPullParserException, IOException { 806 int outerDepthDAM = parser.getDepth(); 807 int typeDAM; 808 Set<String> result = new HashSet<String>(); 809 while ((typeDAM=parser.next()) != END_DOCUMENT 810 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 811 if (typeDAM == END_TAG || typeDAM == TEXT) { 812 continue; 813 } 814 String tagDAM = parser.getName(); 815 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) { 816 result.add(parser.getAttributeValue(null, ATTR_VALUE)); 817 } else { 818 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM); 819 } 820 } 821 return result; 822 } 823 824 private HashMap<String, TrustAgentInfo> getAllTrustAgentInfos( 825 XmlPullParser parser, String tag) throws XmlPullParserException, IOException { 826 int outerDepthDAM = parser.getDepth(); 827 int typeDAM; 828 HashMap<String, TrustAgentInfo> result = new HashMap<String, TrustAgentInfo>(); 829 while ((typeDAM=parser.next()) != END_DOCUMENT 830 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 831 if (typeDAM == END_TAG || typeDAM == TEXT) { 832 continue; 833 } 834 String tagDAM = parser.getName(); 835 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) { 836 final String component = parser.getAttributeValue(null, ATTR_VALUE); 837 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag); 838 result.put(component, trustAgentInfo); 839 } else { 840 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM); 841 } 842 } 843 return result; 844 } 845 846 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag) 847 throws XmlPullParserException, IOException { 848 int outerDepthDAM = parser.getDepth(); 849 int typeDAM; 850 TrustAgentInfo result = new TrustAgentInfo(null); 851 while ((typeDAM=parser.next()) != END_DOCUMENT 852 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 853 if (typeDAM == END_TAG || typeDAM == TEXT) { 854 continue; 855 } 856 String tagDAM = parser.getName(); 857 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) { 858 PersistableBundle bundle = new PersistableBundle(); 859 bundle.restoreFromXml(parser); 860 result.options = bundle; 861 } else { 862 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM); 863 } 864 } 865 return result; 866 } 867 868 private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag) 869 throws XmlPullParserException, IOException { 870 int outerDepthDAM = parser.getDepth(); 871 int typeDAM; 872 ArrayList<String> result = null; 873 while ((typeDAM=parser.next()) != END_DOCUMENT 874 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 875 if (typeDAM == END_TAG || typeDAM == TEXT) { 876 continue; 877 } 878 String tagDAM = parser.getName(); 879 if (TAG_PROVIDER.equals(tagDAM)) { 880 final String provider = parser.getAttributeValue(null, ATTR_VALUE); 881 if (result == null) { 882 result = new ArrayList<>(); 883 } 884 result.add(provider); 885 } else { 886 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM); 887 } 888 } 889 return result; 890 } 891 892 void dump(String prefix, PrintWriter pw) { 893 pw.print(prefix); pw.print("uid="); pw.println(getUid()); 894 pw.print(prefix); pw.println("policies:"); 895 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies(); 896 if (pols != null) { 897 for (int i=0; i<pols.size(); i++) { 898 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag); 899 } 900 } 901 pw.print(prefix); pw.print("passwordQuality=0x"); 902 pw.println(Integer.toHexString(passwordQuality)); 903 pw.print(prefix); pw.print("minimumPasswordLength="); 904 pw.println(minimumPasswordLength); 905 pw.print(prefix); pw.print("passwordHistoryLength="); 906 pw.println(passwordHistoryLength); 907 pw.print(prefix); pw.print("minimumPasswordUpperCase="); 908 pw.println(minimumPasswordUpperCase); 909 pw.print(prefix); pw.print("minimumPasswordLowerCase="); 910 pw.println(minimumPasswordLowerCase); 911 pw.print(prefix); pw.print("minimumPasswordLetters="); 912 pw.println(minimumPasswordLetters); 913 pw.print(prefix); pw.print("minimumPasswordNumeric="); 914 pw.println(minimumPasswordNumeric); 915 pw.print(prefix); pw.print("minimumPasswordSymbols="); 916 pw.println(minimumPasswordSymbols); 917 pw.print(prefix); pw.print("minimumPasswordNonLetter="); 918 pw.println(minimumPasswordNonLetter); 919 pw.print(prefix); pw.print("maximumTimeToUnlock="); 920 pw.println(maximumTimeToUnlock); 921 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe="); 922 pw.println(maximumFailedPasswordsForWipe); 923 pw.print(prefix); pw.print("specifiesGlobalProxy="); 924 pw.println(specifiesGlobalProxy); 925 pw.print(prefix); pw.print("passwordExpirationTimeout="); 926 pw.println(passwordExpirationTimeout); 927 pw.print(prefix); pw.print("passwordExpirationDate="); 928 pw.println(passwordExpirationDate); 929 if (globalProxySpec != null) { 930 pw.print(prefix); pw.print("globalProxySpec="); 931 pw.println(globalProxySpec); 932 } 933 if (globalProxyExclusionList != null) { 934 pw.print(prefix); pw.print("globalProxyEclusionList="); 935 pw.println(globalProxyExclusionList); 936 } 937 pw.print(prefix); pw.print("encryptionRequested="); 938 pw.println(encryptionRequested); 939 pw.print(prefix); pw.print("disableCamera="); 940 pw.println(disableCamera); 941 pw.print(prefix); pw.print("disableCallerId="); 942 pw.println(disableCallerId); 943 pw.print(prefix); pw.print("disableBluetoothContactSharing="); 944 pw.println(disableBluetoothContactSharing); 945 pw.print(prefix); pw.print("disableScreenCapture="); 946 pw.println(disableScreenCapture); 947 pw.print(prefix); pw.print("requireAutoTime="); 948 pw.println(requireAutoTime); 949 pw.print(prefix); pw.print("disabledKeyguardFeatures="); 950 pw.println(disabledKeyguardFeatures); 951 pw.print(prefix); pw.print("crossProfileWidgetProviders="); 952 pw.println(crossProfileWidgetProviders); 953 if (!(permittedAccessiblityServices == null)) { 954 pw.print(prefix); pw.print("permittedAccessibilityServices="); 955 pw.println(permittedAccessiblityServices.toString()); 956 } 957 if (!(permittedInputMethods == null)) { 958 pw.print(prefix); pw.print("permittedInputMethods="); 959 pw.println(permittedInputMethods.toString()); 960 } 961 } 962 } 963 964 private void handlePackagesChanged(String packageName, int userHandle) { 965 boolean removed = false; 966 if (DBG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle); 967 DevicePolicyData policy = getUserData(userHandle); 968 IPackageManager pm = AppGlobals.getPackageManager(); 969 synchronized (this) { 970 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 971 ActiveAdmin aa = policy.mAdminList.get(i); 972 try { 973 // If we're checking all packages or if the specific one we're checking matches, 974 // then check if the package and receiver still exist. 975 final String adminPackage = aa.info.getPackageName(); 976 if (packageName == null || packageName.equals(adminPackage)) { 977 if (pm.getPackageInfo(adminPackage, 0, userHandle) == null 978 || pm.getReceiverInfo(aa.info.getComponent(), 0, userHandle) 979 == null) { 980 removed = true; 981 policy.mAdminList.remove(i); 982 policy.mAdminMap.remove(aa.info.getComponent()); 983 } 984 } 985 } catch (RemoteException re) { 986 // Shouldn't happen 987 } 988 } 989 if (removed) { 990 validatePasswordOwnerLocked(policy); 991 syncDeviceCapabilitiesLocked(policy); 992 saveSettingsLocked(policy.mUserHandle); 993 } 994 995 if (policy.mDelegatedCertInstallerPackage != null && 996 (packageName == null 997 || packageName.equals(policy.mDelegatedCertInstallerPackage))) { 998 try { 999 // Check if delegated cert installer package is removed. 1000 if (pm.getPackageInfo( 1001 policy.mDelegatedCertInstallerPackage, 0, userHandle) == null) { 1002 policy.mDelegatedCertInstallerPackage = null; 1003 saveSettingsLocked(policy.mUserHandle); 1004 } 1005 } catch (RemoteException e) { 1006 // Shouldn't happen 1007 } 1008 } 1009 } 1010 } 1011 1012 /** 1013 * Instantiates the service. 1014 */ 1015 public DevicePolicyManagerService(Context context) { 1016 mContext = context; 1017 mUserManager = UserManager.get(mContext); 1018 mHasFeature = context.getPackageManager().hasSystemFeature( 1019 PackageManager.FEATURE_DEVICE_ADMIN); 1020 mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); 1021 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class); 1022 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DPM"); 1023 mLocalService = new LocalService(); 1024 if (!mHasFeature) { 1025 // Skip the rest of the initialization 1026 return; 1027 } 1028 IntentFilter filter = new IntentFilter(); 1029 filter.addAction(Intent.ACTION_BOOT_COMPLETED); 1030 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION); 1031 filter.addAction(Intent.ACTION_USER_REMOVED); 1032 filter.addAction(Intent.ACTION_USER_STARTED); 1033 filter.addAction(KeyChain.ACTION_STORAGE_CHANGED); 1034 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 1035 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 1036 filter = new IntentFilter(); 1037 filter.addAction(Intent.ACTION_PACKAGE_CHANGED); 1038 filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 1039 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE); 1040 filter.addAction(Intent.ACTION_PACKAGE_ADDED); 1041 filter.addDataScheme("package"); 1042 context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 1043 1044 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService); 1045 } 1046 1047 /** 1048 * Creates and loads the policy data from xml. 1049 * @param userHandle the user for whom to load the policy data 1050 * @return 1051 */ 1052 DevicePolicyData getUserData(int userHandle) { 1053 synchronized (this) { 1054 DevicePolicyData policy = mUserData.get(userHandle); 1055 if (policy == null) { 1056 policy = new DevicePolicyData(userHandle); 1057 mUserData.append(userHandle, policy); 1058 loadSettingsLocked(policy, userHandle); 1059 } 1060 return policy; 1061 } 1062 } 1063 1064 /** 1065 * Creates and loads the policy data from xml for data that is shared between 1066 * various profiles of a user. In contrast to {@link #getUserData(int)} 1067 * it allows access to data of users other than the calling user. 1068 * 1069 * This function should only be used for shared data, e.g. everything regarding 1070 * passwords and should be removed once multiple screen locks are present. 1071 * @param userHandle the user for whom to load the policy data 1072 * @return 1073 */ 1074 DevicePolicyData getUserDataUnchecked(int userHandle) { 1075 long ident = Binder.clearCallingIdentity(); 1076 try { 1077 return getUserData(userHandle); 1078 } finally { 1079 Binder.restoreCallingIdentity(ident); 1080 } 1081 } 1082 1083 void removeUserData(int userHandle) { 1084 synchronized (this) { 1085 if (userHandle == UserHandle.USER_OWNER) { 1086 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring."); 1087 return; 1088 } 1089 if (mDeviceOwner != null) { 1090 mDeviceOwner.removeProfileOwner(userHandle); 1091 mDeviceOwner.writeOwnerFile(); 1092 } 1093 1094 DevicePolicyData policy = mUserData.get(userHandle); 1095 if (policy != null) { 1096 mUserData.remove(userHandle); 1097 } 1098 File policyFile = new File(Environment.getUserSystemDirectory(userHandle), 1099 DEVICE_POLICIES_XML); 1100 policyFile.delete(); 1101 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath()); 1102 } 1103 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */); 1104 } 1105 1106 void loadDeviceOwner() { 1107 synchronized (this) { 1108 mDeviceOwner = DeviceOwner.load(); 1109 updateDeviceOwnerLocked(); 1110 } 1111 } 1112 1113 /** 1114 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration 1115 * reminders. Clears alarm if no expirations are configured. 1116 */ 1117 protected void setExpirationAlarmCheckLocked(Context context, DevicePolicyData policy) { 1118 final long expiration = getPasswordExpirationLocked(null, policy.mUserHandle); 1119 final long now = System.currentTimeMillis(); 1120 final long timeToExpire = expiration - now; 1121 final long alarmTime; 1122 if (expiration == 0) { 1123 // No expirations are currently configured: Cancel alarm. 1124 alarmTime = 0; 1125 } else if (timeToExpire <= 0) { 1126 // The password has already expired: Repeat every 24 hours. 1127 alarmTime = now + MS_PER_DAY; 1128 } else { 1129 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before 1130 // the expiration time. 1131 long alarmInterval = timeToExpire % MS_PER_DAY; 1132 if (alarmInterval == 0) { 1133 alarmInterval = MS_PER_DAY; 1134 } 1135 alarmTime = now + alarmInterval; 1136 } 1137 1138 long token = Binder.clearCallingIdentity(); 1139 try { 1140 AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 1141 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD, 1142 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION), 1143 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT, 1144 new UserHandle(policy.mUserHandle)); 1145 am.cancel(pi); 1146 if (alarmTime != 0) { 1147 am.set(AlarmManager.RTC, alarmTime, pi); 1148 } 1149 } finally { 1150 Binder.restoreCallingIdentity(token); 1151 } 1152 } 1153 1154 private IWindowManager getWindowManager() { 1155 if (mIWindowManager == null) { 1156 IBinder b = ServiceManager.getService(Context.WINDOW_SERVICE); 1157 mIWindowManager = IWindowManager.Stub.asInterface(b); 1158 } 1159 return mIWindowManager; 1160 } 1161 1162 private NotificationManager getNotificationManager() { 1163 if (mNotificationManager == null) { 1164 mNotificationManager = 1165 (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); 1166 } 1167 return mNotificationManager; 1168 } 1169 1170 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) { 1171 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who); 1172 if (admin != null 1173 && who.getPackageName().equals(admin.info.getActivityInfo().packageName) 1174 && who.getClassName().equals(admin.info.getActivityInfo().name)) { 1175 return admin; 1176 } 1177 return null; 1178 } 1179 1180 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy) 1181 throws SecurityException { 1182 final int callingUid = Binder.getCallingUid(); 1183 1184 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid); 1185 if (result != null) { 1186 return result; 1187 } 1188 1189 if (who != null) { 1190 final int userId = UserHandle.getUserId(callingUid); 1191 final DevicePolicyData policy = getUserData(userId); 1192 ActiveAdmin admin = policy.mAdminMap.get(who); 1193 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) { 1194 throw new SecurityException("Admin " + admin.info.getComponent() 1195 + " does not own the device"); 1196 } 1197 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) { 1198 throw new SecurityException("Admin " + admin.info.getComponent() 1199 + " does not own the profile"); 1200 } 1201 throw new SecurityException("Admin " + admin.info.getComponent() 1202 + " did not specify uses-policy for: " 1203 + admin.info.getTagForPolicy(reqPolicy)); 1204 } else { 1205 throw new SecurityException("No active admin owned by uid " 1206 + Binder.getCallingUid() + " for policy #" + reqPolicy); 1207 } 1208 } 1209 1210 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, 1211 int uid) { 1212 // Try to find an admin which can use reqPolicy 1213 final int userId = UserHandle.getUserId(uid); 1214 final DevicePolicyData policy = getUserData(userId); 1215 if (who != null) { 1216 ActiveAdmin admin = policy.mAdminMap.get(who); 1217 if (admin == null) { 1218 throw new SecurityException("No active admin " + who); 1219 } 1220 if (admin.getUid() != uid) { 1221 throw new SecurityException("Admin " + who + " is not owned by uid " 1222 + Binder.getCallingUid()); 1223 } 1224 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) { 1225 return admin; 1226 } 1227 } else { 1228 for (ActiveAdmin admin : policy.mAdminList) { 1229 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, 1230 userId)) { 1231 return admin; 1232 } 1233 } 1234 } 1235 1236 return null; 1237 } 1238 1239 private boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, 1240 int userId) { 1241 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName()); 1242 boolean ownsProfile = (getProfileOwner(userId) != null 1243 && getProfileOwner(userId).getPackageName() 1244 .equals(admin.info.getPackageName())); 1245 boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName()) 1246 && !hasUserSetupCompleted(userId); 1247 1248 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) { 1249 if (ownsDevice || (userId == UserHandle.USER_OWNER && ownsInitialization)) { 1250 return true; 1251 } 1252 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) { 1253 if (ownsDevice || ownsProfile || ownsInitialization) { 1254 return true; 1255 } 1256 } else { 1257 if (admin.info.usesPolicy(reqPolicy)) { 1258 return true; 1259 } 1260 } 1261 return false; 1262 } 1263 1264 void sendAdminCommandLocked(ActiveAdmin admin, String action) { 1265 sendAdminCommandLocked(admin, action, null); 1266 } 1267 1268 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) { 1269 sendAdminCommandLocked(admin, action, null, result); 1270 } 1271 1272 /** 1273 * Send an update to one specific admin, get notified when that admin returns a result. 1274 */ 1275 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, 1276 BroadcastReceiver result) { 1277 Intent intent = new Intent(action); 1278 intent.setComponent(admin.info.getComponent()); 1279 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) { 1280 intent.putExtra("expiration", admin.passwordExpirationDate); 1281 } 1282 if (adminExtras != null) { 1283 intent.putExtras(adminExtras); 1284 } 1285 if (result != null) { 1286 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(), 1287 null, result, mHandler, Activity.RESULT_OK, null, null); 1288 } else { 1289 mContext.sendBroadcastAsUser(intent, admin.getUserHandle()); 1290 } 1291 } 1292 1293 /** 1294 * Send an update to all admins of a user that enforce a specified policy. 1295 */ 1296 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) { 1297 final DevicePolicyData policy = getUserData(userHandle); 1298 final int count = policy.mAdminList.size(); 1299 if (count > 0) { 1300 for (int i = 0; i < count; i++) { 1301 final ActiveAdmin admin = policy.mAdminList.get(i); 1302 if (admin.info.usesPolicy(reqPolicy)) { 1303 sendAdminCommandLocked(admin, action); 1304 } 1305 } 1306 } 1307 } 1308 1309 /** 1310 * Send an update intent to all admins of a user and its profiles. Only send to admins that 1311 * enforce a specified policy. 1312 */ 1313 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy, 1314 int userHandle) { 1315 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1316 for (UserInfo ui : profiles) { 1317 int id = ui.id; 1318 sendAdminCommandLocked(action, reqPolicy, id); 1319 } 1320 } 1321 1322 void removeActiveAdminLocked(final ComponentName adminReceiver, int userHandle) { 1323 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 1324 if (admin != null) { 1325 synchronized (this) { 1326 getUserData(userHandle).mRemovingAdmins.add(adminReceiver); 1327 } 1328 sendAdminCommandLocked(admin, 1329 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED, 1330 new BroadcastReceiver() { 1331 @Override 1332 public void onReceive(Context context, Intent intent) { 1333 synchronized (DevicePolicyManagerService.this) { 1334 int userHandle = admin.getUserHandle().getIdentifier(); 1335 DevicePolicyData policy = getUserData(userHandle); 1336 boolean doProxyCleanup = admin.info.usesPolicy( 1337 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 1338 policy.mAdminList.remove(admin); 1339 policy.mAdminMap.remove(adminReceiver); 1340 validatePasswordOwnerLocked(policy); 1341 syncDeviceCapabilitiesLocked(policy); 1342 if (doProxyCleanup) { 1343 resetGlobalProxyLocked(getUserData(userHandle)); 1344 } 1345 saveSettingsLocked(userHandle); 1346 updateMaximumTimeToLockLocked(policy); 1347 policy.mRemovingAdmins.remove(adminReceiver); 1348 } 1349 } 1350 }); 1351 } 1352 } 1353 1354 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle) { 1355 if (!mHasFeature) { 1356 return null; 1357 } 1358 enforceCrossUserPermission(userHandle); 1359 Intent resolveIntent = new Intent(); 1360 resolveIntent.setComponent(adminName); 1361 List<ResolveInfo> infos = mContext.getPackageManager().queryBroadcastReceivers( 1362 resolveIntent, 1363 PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS, 1364 userHandle); 1365 if (infos == null || infos.size() <= 0) { 1366 throw new IllegalArgumentException("Unknown admin: " + adminName); 1367 } 1368 1369 try { 1370 return new DeviceAdminInfo(mContext, infos.get(0)); 1371 } catch (XmlPullParserException e) { 1372 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName, 1373 e); 1374 return null; 1375 } catch (IOException e) { 1376 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName, 1377 e); 1378 return null; 1379 } 1380 } 1381 1382 private static JournaledFile makeJournaledFile(int userHandle) { 1383 final String base = userHandle == 0 1384 ? "/data/system/" + DEVICE_POLICIES_XML 1385 : new File(Environment.getUserSystemDirectory(userHandle), DEVICE_POLICIES_XML) 1386 .getAbsolutePath(); 1387 return new JournaledFile(new File(base), new File(base + ".tmp")); 1388 } 1389 1390 private void saveSettingsLocked(int userHandle) { 1391 DevicePolicyData policy = getUserData(userHandle); 1392 JournaledFile journal = makeJournaledFile(userHandle); 1393 FileOutputStream stream = null; 1394 try { 1395 stream = new FileOutputStream(journal.chooseForWrite(), false); 1396 XmlSerializer out = new FastXmlSerializer(); 1397 out.setOutput(stream, "utf-8"); 1398 out.startDocument(null, true); 1399 1400 out.startTag(null, "policies"); 1401 if (policy.mRestrictionsProvider != null) { 1402 out.attribute(null, ATTR_PERMISSION_PROVIDER, 1403 policy.mRestrictionsProvider.flattenToString()); 1404 } 1405 if (policy.mUserSetupComplete) { 1406 out.attribute(null, ATTR_SETUP_COMPLETE, 1407 Boolean.toString(true)); 1408 } 1409 if (policy.mDelegatedCertInstallerPackage != null) { 1410 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER, 1411 policy.mDelegatedCertInstallerPackage); 1412 } 1413 1414 1415 final int N = policy.mAdminList.size(); 1416 for (int i=0; i<N; i++) { 1417 ActiveAdmin ap = policy.mAdminList.get(i); 1418 if (ap != null) { 1419 out.startTag(null, "admin"); 1420 out.attribute(null, "name", ap.info.getComponent().flattenToString()); 1421 ap.writeToXml(out); 1422 out.endTag(null, "admin"); 1423 } 1424 } 1425 1426 if (policy.mPasswordOwner >= 0) { 1427 out.startTag(null, "password-owner"); 1428 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner)); 1429 out.endTag(null, "password-owner"); 1430 } 1431 1432 if (policy.mFailedPasswordAttempts != 0) { 1433 out.startTag(null, "failed-password-attempts"); 1434 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts)); 1435 out.endTag(null, "failed-password-attempts"); 1436 } 1437 1438 if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0 1439 || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0 1440 || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0 1441 || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) { 1442 out.startTag(null, "active-password"); 1443 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality)); 1444 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength)); 1445 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase)); 1446 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase)); 1447 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters)); 1448 out.attribute(null, "numeric", Integer 1449 .toString(policy.mActivePasswordNumeric)); 1450 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols)); 1451 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter)); 1452 out.endTag(null, "active-password"); 1453 } 1454 1455 for (int i=0; i<policy.mLockTaskPackages.size(); i++) { 1456 String component = policy.mLockTaskPackages.get(i); 1457 out.startTag(null, TAG_LOCK_TASK_COMPONENTS); 1458 out.attribute(null, "name", component); 1459 out.endTag(null, TAG_LOCK_TASK_COMPONENTS); 1460 } 1461 1462 if (!policy.mStatusBarEnabledState) { 1463 out.startTag(null, TAG_STATUS_BAR); 1464 out.attribute(null, ATTR_ENABLED, Boolean.toString(policy.mStatusBarEnabledState)); 1465 out.endTag(null, TAG_STATUS_BAR); 1466 } 1467 1468 if (policy.doNotAskCredentialsOnBoot) { 1469 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML); 1470 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML); 1471 } 1472 1473 out.endTag(null, "policies"); 1474 1475 out.endDocument(); 1476 stream.flush(); 1477 FileUtils.sync(stream); 1478 stream.close(); 1479 journal.commit(); 1480 sendChangedNotification(userHandle); 1481 } catch (IOException e) { 1482 try { 1483 if (stream != null) { 1484 stream.close(); 1485 } 1486 } catch (IOException ex) { 1487 // Ignore 1488 } 1489 journal.rollback(); 1490 } 1491 } 1492 1493 private void sendChangedNotification(int userHandle) { 1494 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 1495 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 1496 long ident = Binder.clearCallingIdentity(); 1497 try { 1498 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle)); 1499 } finally { 1500 Binder.restoreCallingIdentity(ident); 1501 } 1502 } 1503 1504 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) { 1505 JournaledFile journal = makeJournaledFile(userHandle); 1506 FileInputStream stream = null; 1507 File file = journal.chooseForRead(); 1508 try { 1509 stream = new FileInputStream(file); 1510 XmlPullParser parser = Xml.newPullParser(); 1511 parser.setInput(stream, null); 1512 1513 int type; 1514 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1515 && type != XmlPullParser.START_TAG) { 1516 } 1517 String tag = parser.getName(); 1518 if (!"policies".equals(tag)) { 1519 throw new XmlPullParserException( 1520 "Settings do not start with policies tag: found " + tag); 1521 } 1522 1523 // Extract the permission provider component name if available 1524 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER); 1525 if (permissionProvider != null) { 1526 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider); 1527 } 1528 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE); 1529 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) { 1530 policy.mUserSetupComplete = true; 1531 } 1532 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null, 1533 ATTR_DELEGATED_CERT_INSTALLER); 1534 1535 type = parser.next(); 1536 int outerDepth = parser.getDepth(); 1537 policy.mLockTaskPackages.clear(); 1538 policy.mAdminList.clear(); 1539 policy.mAdminMap.clear(); 1540 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1541 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 1542 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 1543 continue; 1544 } 1545 tag = parser.getName(); 1546 if ("admin".equals(tag)) { 1547 String name = parser.getAttributeValue(null, "name"); 1548 try { 1549 DeviceAdminInfo dai = findAdmin( 1550 ComponentName.unflattenFromString(name), userHandle); 1551 if (DBG && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid) 1552 != userHandle)) { 1553 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid " 1554 + dai.getActivityInfo().applicationInfo.uid + " for user " 1555 + userHandle); 1556 } 1557 if (dai != null) { 1558 ActiveAdmin ap = new ActiveAdmin(dai); 1559 ap.readFromXml(parser); 1560 policy.mAdminMap.put(ap.info.getComponent(), ap); 1561 } 1562 } catch (RuntimeException e) { 1563 Slog.w(LOG_TAG, "Failed loading admin " + name, e); 1564 } 1565 } else if ("failed-password-attempts".equals(tag)) { 1566 policy.mFailedPasswordAttempts = Integer.parseInt( 1567 parser.getAttributeValue(null, "value")); 1568 XmlUtils.skipCurrentTag(parser); 1569 } else if ("password-owner".equals(tag)) { 1570 policy.mPasswordOwner = Integer.parseInt( 1571 parser.getAttributeValue(null, "value")); 1572 XmlUtils.skipCurrentTag(parser); 1573 } else if ("active-password".equals(tag)) { 1574 policy.mActivePasswordQuality = Integer.parseInt( 1575 parser.getAttributeValue(null, "quality")); 1576 policy.mActivePasswordLength = Integer.parseInt( 1577 parser.getAttributeValue(null, "length")); 1578 policy.mActivePasswordUpperCase = Integer.parseInt( 1579 parser.getAttributeValue(null, "uppercase")); 1580 policy.mActivePasswordLowerCase = Integer.parseInt( 1581 parser.getAttributeValue(null, "lowercase")); 1582 policy.mActivePasswordLetters = Integer.parseInt( 1583 parser.getAttributeValue(null, "letters")); 1584 policy.mActivePasswordNumeric = Integer.parseInt( 1585 parser.getAttributeValue(null, "numeric")); 1586 policy.mActivePasswordSymbols = Integer.parseInt( 1587 parser.getAttributeValue(null, "symbols")); 1588 policy.mActivePasswordNonLetter = Integer.parseInt( 1589 parser.getAttributeValue(null, "nonletter")); 1590 XmlUtils.skipCurrentTag(parser); 1591 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) { 1592 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name")); 1593 XmlUtils.skipCurrentTag(parser); 1594 } else if (TAG_STATUS_BAR.equals(tag)) { 1595 policy.mStatusBarEnabledState = Boolean.parseBoolean( 1596 parser.getAttributeValue(null, ATTR_ENABLED)); 1597 XmlUtils.skipCurrentTag(parser); 1598 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) { 1599 policy.doNotAskCredentialsOnBoot = true; 1600 } else { 1601 Slog.w(LOG_TAG, "Unknown tag: " + tag); 1602 XmlUtils.skipCurrentTag(parser); 1603 } 1604 } 1605 } catch (NullPointerException e) { 1606 Slog.w(LOG_TAG, "failed parsing " + file + " " + e); 1607 } catch (NumberFormatException e) { 1608 Slog.w(LOG_TAG, "failed parsing " + file + " " + e); 1609 } catch (XmlPullParserException e) { 1610 Slog.w(LOG_TAG, "failed parsing " + file + " " + e); 1611 } catch (FileNotFoundException e) { 1612 // Don't be noisy, this is normal if we haven't defined any policies. 1613 } catch (IOException e) { 1614 Slog.w(LOG_TAG, "failed parsing " + file + " " + e); 1615 } catch (IndexOutOfBoundsException e) { 1616 Slog.w(LOG_TAG, "failed parsing " + file + " " + e); 1617 } 1618 try { 1619 if (stream != null) { 1620 stream.close(); 1621 } 1622 } catch (IOException e) { 1623 // Ignore 1624 } 1625 1626 // Generate a list of admins from the admin map 1627 policy.mAdminList.addAll(policy.mAdminMap.values()); 1628 1629 // Validate that what we stored for the password quality matches 1630 // sufficiently what is currently set. Note that this is only 1631 // a sanity check in case the two get out of sync; this should 1632 // never normally happen. 1633 final long identity = Binder.clearCallingIdentity(); 1634 try { 1635 LockPatternUtils utils = new LockPatternUtils(mContext); 1636 if (utils.getActivePasswordQuality(userHandle) < policy.mActivePasswordQuality) { 1637 Slog.w(LOG_TAG, "Active password quality 0x" 1638 + Integer.toHexString(policy.mActivePasswordQuality) 1639 + " does not match actual quality 0x" 1640 + Integer.toHexString(utils.getActivePasswordQuality(userHandle))); 1641 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 1642 policy.mActivePasswordLength = 0; 1643 policy.mActivePasswordUpperCase = 0; 1644 policy.mActivePasswordLowerCase = 0; 1645 policy.mActivePasswordLetters = 0; 1646 policy.mActivePasswordNumeric = 0; 1647 policy.mActivePasswordSymbols = 0; 1648 policy.mActivePasswordNonLetter = 0; 1649 } 1650 } finally { 1651 Binder.restoreCallingIdentity(identity); 1652 } 1653 1654 validatePasswordOwnerLocked(policy); 1655 syncDeviceCapabilitiesLocked(policy); 1656 updateMaximumTimeToLockLocked(policy); 1657 addDeviceInitializerToLockTaskPackagesLocked(userHandle); 1658 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle); 1659 if (!policy.mStatusBarEnabledState) { 1660 setStatusBarEnabledStateInternal(policy.mStatusBarEnabledState, userHandle); 1661 } 1662 } 1663 1664 private void updateLockTaskPackagesLocked(List<String> packages, int userId) { 1665 IActivityManager am = ActivityManagerNative.getDefault(); 1666 long ident = Binder.clearCallingIdentity(); 1667 try { 1668 am.updateLockTaskPackages(userId, packages.toArray(new String[packages.size()])); 1669 } catch (RemoteException e) { 1670 // Not gonna happen. 1671 } finally { 1672 Binder.restoreCallingIdentity(ident); 1673 } 1674 } 1675 1676 private void updateDeviceOwnerLocked() { 1677 IActivityManager am = ActivityManagerNative.getDefault(); 1678 long ident = Binder.clearCallingIdentity(); 1679 try { 1680 am.updateDeviceOwner(getDeviceOwner()); 1681 } catch (RemoteException e) { 1682 // Not gonna happen. 1683 } finally { 1684 Binder.restoreCallingIdentity(ident); 1685 } 1686 } 1687 1688 static void validateQualityConstant(int quality) { 1689 switch (quality) { 1690 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED: 1691 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK: 1692 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: 1693 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: 1694 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX: 1695 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: 1696 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC: 1697 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX: 1698 return; 1699 } 1700 throw new IllegalArgumentException("Invalid quality constant: 0x" 1701 + Integer.toHexString(quality)); 1702 } 1703 1704 void validatePasswordOwnerLocked(DevicePolicyData policy) { 1705 if (policy.mPasswordOwner >= 0) { 1706 boolean haveOwner = false; 1707 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 1708 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) { 1709 haveOwner = true; 1710 break; 1711 } 1712 } 1713 if (!haveOwner) { 1714 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner 1715 + " no longer active; disabling"); 1716 policy.mPasswordOwner = -1; 1717 } 1718 } 1719 } 1720 1721 /** 1722 * Pushes down policy information to the system for any policies related to general device 1723 * capabilities that need to be enforced by lower level services (e.g. Camera services). 1724 */ 1725 void syncDeviceCapabilitiesLocked(DevicePolicyData policy) { 1726 // Ensure the status of the camera is synced down to the system. Interested native services 1727 // should monitor this value and act accordingly. 1728 String cameraPropertyForUser = SYSTEM_PROP_DISABLE_CAMERA_PREFIX + policy.mUserHandle; 1729 boolean systemState = SystemProperties.getBoolean(cameraPropertyForUser, false); 1730 boolean cameraDisabled = getCameraDisabled(null, policy.mUserHandle); 1731 if (cameraDisabled != systemState) { 1732 long token = Binder.clearCallingIdentity(); 1733 try { 1734 String value = cameraDisabled ? "1" : "0"; 1735 if (DBG) Slog.v(LOG_TAG, "Change in camera state [" 1736 + cameraPropertyForUser + "] = " + value); 1737 SystemProperties.set(cameraPropertyForUser, value); 1738 } finally { 1739 Binder.restoreCallingIdentity(token); 1740 } 1741 } 1742 } 1743 1744 public void systemReady() { 1745 if (!mHasFeature) { 1746 return; 1747 } 1748 getUserData(UserHandle.USER_OWNER); 1749 loadDeviceOwner(); 1750 cleanUpOldUsers(); 1751 // Register an observer for watching for user setup complete. 1752 new SetupContentObserver(mHandler).register(mContext.getContentResolver()); 1753 // Initialize the user setup state, to handle the upgrade case. 1754 updateUserSetupComplete(); 1755 1756 // Update the screen capture disabled cache in the window manager 1757 List<UserInfo> users = mUserManager.getUsers(true); 1758 final int N = users.size(); 1759 for (int i = 0; i < N; i++) { 1760 int userHandle = users.get(i).id; 1761 updateScreenCaptureDisabledInWindowManager(userHandle, 1762 getScreenCaptureDisabled(null, userHandle)); 1763 } 1764 } 1765 1766 private void cleanUpOldUsers() { 1767 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled 1768 // before reboot 1769 Set<Integer> usersWithProfileOwners; 1770 Set<Integer> usersWithData; 1771 synchronized(this) { 1772 usersWithProfileOwners = mDeviceOwner != null 1773 ? mDeviceOwner.getProfileOwnerKeys() : new HashSet<Integer>(); 1774 usersWithData = new HashSet<Integer>(); 1775 for (int i = 0; i < mUserData.size(); i++) { 1776 usersWithData.add(mUserData.keyAt(i)); 1777 } 1778 } 1779 List<UserInfo> allUsers = mUserManager.getUsers(); 1780 1781 Set<Integer> deletedUsers = new HashSet<Integer>(); 1782 deletedUsers.addAll(usersWithProfileOwners); 1783 deletedUsers.addAll(usersWithData); 1784 for (UserInfo userInfo : allUsers) { 1785 deletedUsers.remove(userInfo.id); 1786 } 1787 for (Integer userId : deletedUsers) { 1788 removeUserData(userId); 1789 } 1790 } 1791 1792 private void handlePasswordExpirationNotification(int userHandle) { 1793 synchronized (this) { 1794 final long now = System.currentTimeMillis(); 1795 1796 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1797 for (UserInfo ui : profiles) { 1798 int profileUserHandle = ui.id; 1799 final DevicePolicyData policy = getUserData(profileUserHandle); 1800 final int count = policy.mAdminList.size(); 1801 if (count > 0) { 1802 for (int i = 0; i < count; i++) { 1803 final ActiveAdmin admin = policy.mAdminList.get(i); 1804 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD) 1805 && admin.passwordExpirationTimeout > 0L 1806 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS 1807 && admin.passwordExpirationDate > 0L) { 1808 sendAdminCommandLocked(admin, 1809 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING); 1810 } 1811 } 1812 } 1813 } 1814 setExpirationAlarmCheckLocked(mContext, getUserData(userHandle)); 1815 } 1816 } 1817 1818 private class MonitoringCertNotificationTask extends AsyncTask<Intent, Void, Void> { 1819 @Override 1820 protected Void doInBackground(Intent... params) { 1821 int userHandle = params[0].getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL); 1822 1823 if (userHandle == UserHandle.USER_ALL) { 1824 for (UserInfo userInfo : mUserManager.getUsers()) { 1825 manageNotification(userInfo.getUserHandle()); 1826 } 1827 } else { 1828 manageNotification(new UserHandle(userHandle)); 1829 } 1830 return null; 1831 } 1832 1833 private void manageNotification(UserHandle userHandle) { 1834 if (!mUserManager.isUserRunning(userHandle)) { 1835 return; 1836 } 1837 1838 // Call out to KeyChain to check for user-added CAs 1839 boolean hasCert = false; 1840 try { 1841 KeyChainConnection kcs = KeyChain.bindAsUser(mContext, userHandle); 1842 try { 1843 if (!kcs.getService().getUserCaAliases().getList().isEmpty()) { 1844 hasCert = true; 1845 } 1846 } catch (RemoteException e) { 1847 Log.e(LOG_TAG, "Could not connect to KeyChain service", e); 1848 } finally { 1849 kcs.close(); 1850 } 1851 } catch (InterruptedException e) { 1852 Thread.currentThread().interrupt(); 1853 } catch (RuntimeException e) { 1854 Log.e(LOG_TAG, "Could not connect to KeyChain service", e); 1855 } 1856 if (!hasCert) { 1857 getNotificationManager().cancelAsUser( 1858 null, MONITORING_CERT_NOTIFICATION_ID, userHandle); 1859 return; 1860 } 1861 1862 // Build and show a warning notification 1863 int smallIconId; 1864 String contentText; 1865 final String ownerName = getDeviceOwnerName(); 1866 if (isManagedProfile(userHandle.getIdentifier())) { 1867 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_administrator); 1868 smallIconId = R.drawable.stat_sys_certificate_info; 1869 } else if (ownerName != null) { 1870 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, ownerName); 1871 smallIconId = R.drawable.stat_sys_certificate_info; 1872 } else { 1873 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown); 1874 smallIconId = android.R.drawable.stat_sys_warning; 1875 } 1876 1877 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO); 1878 dialogIntent.setFlags( 1879 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 1880 dialogIntent.setPackage("com.android.settings"); 1881 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0, 1882 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, userHandle); 1883 1884 final Context userContext; 1885 try { 1886 userContext = mContext.createPackageContextAsUser("android", 0, userHandle); 1887 } catch (PackageManager.NameNotFoundException e) { 1888 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e); 1889 return; 1890 } 1891 final Notification noti = new Notification.Builder(userContext) 1892 .setSmallIcon(smallIconId) 1893 .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning)) 1894 .setContentText(contentText) 1895 .setContentIntent(notifyIntent) 1896 .setPriority(Notification.PRIORITY_HIGH) 1897 .setShowWhen(false) 1898 .setColor(mContext.getColor( 1899 com.android.internal.R.color.system_notification_accent_color)) 1900 .build(); 1901 1902 getNotificationManager().notifyAsUser( 1903 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle); 1904 } 1905 } 1906 1907 /** 1908 * @param adminReceiver The admin to add 1909 * @param refreshing true = update an active admin, no error 1910 */ 1911 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) { 1912 if (!mHasFeature) { 1913 return; 1914 } 1915 setActiveAdmin(adminReceiver, refreshing, userHandle, null); 1916 } 1917 1918 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle, 1919 Bundle onEnableData) { 1920 mContext.enforceCallingOrSelfPermission( 1921 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 1922 enforceCrossUserPermission(userHandle); 1923 1924 DevicePolicyData policy = getUserData(userHandle); 1925 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle); 1926 if (info == null) { 1927 throw new IllegalArgumentException("Bad admin: " + adminReceiver); 1928 } 1929 synchronized (this) { 1930 long ident = Binder.clearCallingIdentity(); 1931 try { 1932 if (!refreshing 1933 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) { 1934 throw new IllegalArgumentException("Admin is already added"); 1935 } 1936 ActiveAdmin newAdmin = new ActiveAdmin(info); 1937 policy.mAdminMap.put(adminReceiver, newAdmin); 1938 int replaceIndex = -1; 1939 final int N = policy.mAdminList.size(); 1940 for (int i=0; i < N; i++) { 1941 ActiveAdmin oldAdmin = policy.mAdminList.get(i); 1942 if (oldAdmin.info.getComponent().equals(adminReceiver)) { 1943 replaceIndex = i; 1944 break; 1945 } 1946 } 1947 if (replaceIndex == -1) { 1948 policy.mAdminList.add(newAdmin); 1949 enableIfNecessary(info.getPackageName(), userHandle); 1950 } else { 1951 policy.mAdminList.set(replaceIndex, newAdmin); 1952 } 1953 saveSettingsLocked(userHandle); 1954 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 1955 onEnableData, null); 1956 } finally { 1957 Binder.restoreCallingIdentity(ident); 1958 } 1959 } 1960 } 1961 1962 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) { 1963 if (!mHasFeature) { 1964 return false; 1965 } 1966 enforceCrossUserPermission(userHandle); 1967 synchronized (this) { 1968 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null; 1969 } 1970 } 1971 1972 @Override 1973 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) { 1974 if (!mHasFeature) { 1975 return false; 1976 } 1977 enforceCrossUserPermission(userHandle); 1978 synchronized (this) { 1979 DevicePolicyData policyData = getUserData(userHandle); 1980 return policyData.mRemovingAdmins.contains(adminReceiver); 1981 } 1982 } 1983 1984 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) { 1985 if (!mHasFeature) { 1986 return false; 1987 } 1988 enforceCrossUserPermission(userHandle); 1989 synchronized (this) { 1990 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 1991 if (administrator == null) { 1992 throw new SecurityException("No active admin " + adminReceiver); 1993 } 1994 return administrator.info.usesPolicy(policyId); 1995 } 1996 } 1997 1998 @SuppressWarnings("unchecked") 1999 public List<ComponentName> getActiveAdmins(int userHandle) { 2000 if (!mHasFeature) { 2001 return Collections.EMPTY_LIST; 2002 } 2003 2004 enforceCrossUserPermission(userHandle); 2005 synchronized (this) { 2006 DevicePolicyData policy = getUserData(userHandle); 2007 final int N = policy.mAdminList.size(); 2008 if (N <= 0) { 2009 return null; 2010 } 2011 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N); 2012 for (int i=0; i<N; i++) { 2013 res.add(policy.mAdminList.get(i).info.getComponent()); 2014 } 2015 return res; 2016 } 2017 } 2018 2019 public boolean packageHasActiveAdmins(String packageName, int userHandle) { 2020 if (!mHasFeature) { 2021 return false; 2022 } 2023 enforceCrossUserPermission(userHandle); 2024 synchronized (this) { 2025 DevicePolicyData policy = getUserData(userHandle); 2026 final int N = policy.mAdminList.size(); 2027 for (int i=0; i<N; i++) { 2028 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) { 2029 return true; 2030 } 2031 } 2032 return false; 2033 } 2034 } 2035 2036 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) { 2037 if (!mHasFeature) { 2038 return; 2039 } 2040 enforceCrossUserPermission(userHandle); 2041 synchronized (this) { 2042 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 2043 if (admin == null) { 2044 return; 2045 } 2046 if (admin.getUid() != Binder.getCallingUid()) { 2047 // Active device owners must remain active admins. 2048 if (isDeviceOwner(adminReceiver.getPackageName())) { 2049 return; 2050 } 2051 mContext.enforceCallingOrSelfPermission( 2052 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 2053 } 2054 long ident = Binder.clearCallingIdentity(); 2055 try { 2056 removeActiveAdminLocked(adminReceiver, userHandle); 2057 } finally { 2058 Binder.restoreCallingIdentity(ident); 2059 } 2060 } 2061 } 2062 2063 public void setPasswordQuality(ComponentName who, int quality) { 2064 if (!mHasFeature) { 2065 return; 2066 } 2067 Preconditions.checkNotNull(who, "ComponentName is null"); 2068 final int userHandle = UserHandle.getCallingUserId(); 2069 validateQualityConstant(quality); 2070 2071 synchronized (this) { 2072 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2073 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2074 if (ap.passwordQuality != quality) { 2075 ap.passwordQuality = quality; 2076 saveSettingsLocked(userHandle); 2077 } 2078 } 2079 } 2080 2081 public int getPasswordQuality(ComponentName who, int userHandle) { 2082 if (!mHasFeature) { 2083 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 2084 } 2085 enforceCrossUserPermission(userHandle); 2086 synchronized (this) { 2087 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 2088 2089 if (who != null) { 2090 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2091 return admin != null ? admin.passwordQuality : mode; 2092 } 2093 2094 // Return strictest policy for this user and profiles that are visible from this user. 2095 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2096 for (UserInfo userInfo : profiles) { 2097 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2098 final int N = policy.mAdminList.size(); 2099 for (int i=0; i<N; i++) { 2100 ActiveAdmin admin = policy.mAdminList.get(i); 2101 if (mode < admin.passwordQuality) { 2102 mode = admin.passwordQuality; 2103 } 2104 } 2105 } 2106 return mode; 2107 } 2108 } 2109 2110 public void setPasswordMinimumLength(ComponentName who, int length) { 2111 if (!mHasFeature) { 2112 return; 2113 } 2114 Preconditions.checkNotNull(who, "ComponentName is null"); 2115 final int userHandle = UserHandle.getCallingUserId(); 2116 synchronized (this) { 2117 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2118 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2119 if (ap.minimumPasswordLength != length) { 2120 ap.minimumPasswordLength = length; 2121 saveSettingsLocked(userHandle); 2122 } 2123 } 2124 } 2125 2126 public int getPasswordMinimumLength(ComponentName who, int userHandle) { 2127 if (!mHasFeature) { 2128 return 0; 2129 } 2130 enforceCrossUserPermission(userHandle); 2131 synchronized (this) { 2132 int length = 0; 2133 2134 if (who != null) { 2135 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2136 return admin != null ? admin.minimumPasswordLength : length; 2137 } 2138 2139 // Return strictest policy for this user and profiles that are visible from this user. 2140 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2141 for (UserInfo userInfo : profiles) { 2142 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2143 final int N = policy.mAdminList.size(); 2144 for (int i=0; i<N; i++) { 2145 ActiveAdmin admin = policy.mAdminList.get(i); 2146 if (length < admin.minimumPasswordLength) { 2147 length = admin.minimumPasswordLength; 2148 } 2149 } 2150 } 2151 return length; 2152 } 2153 } 2154 2155 public void setPasswordHistoryLength(ComponentName who, int length) { 2156 if (!mHasFeature) { 2157 return; 2158 } 2159 Preconditions.checkNotNull(who, "ComponentName is null"); 2160 final int userHandle = UserHandle.getCallingUserId(); 2161 synchronized (this) { 2162 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2163 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2164 if (ap.passwordHistoryLength != length) { 2165 ap.passwordHistoryLength = length; 2166 saveSettingsLocked(userHandle); 2167 } 2168 } 2169 } 2170 2171 public int getPasswordHistoryLength(ComponentName who, int userHandle) { 2172 if (!mHasFeature) { 2173 return 0; 2174 } 2175 enforceCrossUserPermission(userHandle); 2176 synchronized (this) { 2177 int length = 0; 2178 2179 if (who != null) { 2180 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2181 return admin != null ? admin.passwordHistoryLength : length; 2182 } 2183 2184 // Return strictest policy for this user and profiles that are visible from this user. 2185 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2186 for (UserInfo userInfo : profiles) { 2187 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2188 final int N = policy.mAdminList.size(); 2189 for (int i = 0; i < N; i++) { 2190 ActiveAdmin admin = policy.mAdminList.get(i); 2191 if (length < admin.passwordHistoryLength) { 2192 length = admin.passwordHistoryLength; 2193 } 2194 } 2195 } 2196 return length; 2197 } 2198 } 2199 2200 public void setPasswordExpirationTimeout(ComponentName who, long timeout) { 2201 if (!mHasFeature) { 2202 return; 2203 } 2204 Preconditions.checkNotNull(who, "ComponentName is null"); 2205 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms"); 2206 final int userHandle = UserHandle.getCallingUserId(); 2207 synchronized (this) { 2208 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2209 DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD); 2210 // Calling this API automatically bumps the expiration date 2211 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 2212 ap.passwordExpirationDate = expiration; 2213 ap.passwordExpirationTimeout = timeout; 2214 if (timeout > 0L) { 2215 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on " 2216 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT) 2217 .format(new Date(expiration))); 2218 } 2219 saveSettingsLocked(userHandle); 2220 // in case this is the first one 2221 setExpirationAlarmCheckLocked(mContext, getUserData(userHandle)); 2222 } 2223 } 2224 2225 /** 2226 * Return a single admin's expiration cycle time, or the min of all cycle times. 2227 * Returns 0 if not configured. 2228 */ 2229 public long getPasswordExpirationTimeout(ComponentName who, int userHandle) { 2230 if (!mHasFeature) { 2231 return 0L; 2232 } 2233 enforceCrossUserPermission(userHandle); 2234 synchronized (this) { 2235 long timeout = 0L; 2236 2237 if (who != null) { 2238 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2239 return admin != null ? admin.passwordExpirationTimeout : timeout; 2240 } 2241 2242 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2243 for (UserInfo userInfo : profiles) { 2244 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2245 final int N = policy.mAdminList.size(); 2246 for (int i = 0; i < N; i++) { 2247 ActiveAdmin admin = policy.mAdminList.get(i); 2248 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L 2249 && timeout > admin.passwordExpirationTimeout)) { 2250 timeout = admin.passwordExpirationTimeout; 2251 } 2252 } 2253 } 2254 return timeout; 2255 } 2256 } 2257 2258 @Override 2259 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) { 2260 final int userId = UserHandle.getCallingUserId(); 2261 List<String> changedProviders = null; 2262 2263 synchronized (this) { 2264 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 2265 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 2266 if (activeAdmin.crossProfileWidgetProviders == null) { 2267 activeAdmin.crossProfileWidgetProviders = new ArrayList<>(); 2268 } 2269 List<String> providers = activeAdmin.crossProfileWidgetProviders; 2270 if (!providers.contains(packageName)) { 2271 providers.add(packageName); 2272 changedProviders = new ArrayList<>(providers); 2273 saveSettingsLocked(userId); 2274 } 2275 } 2276 2277 if (changedProviders != null) { 2278 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 2279 return true; 2280 } 2281 2282 return false; 2283 } 2284 2285 @Override 2286 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) { 2287 final int userId = UserHandle.getCallingUserId(); 2288 List<String> changedProviders = null; 2289 2290 synchronized (this) { 2291 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 2292 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 2293 if (activeAdmin.crossProfileWidgetProviders == null) { 2294 return false; 2295 } 2296 List<String> providers = activeAdmin.crossProfileWidgetProviders; 2297 if (providers.remove(packageName)) { 2298 changedProviders = new ArrayList<>(providers); 2299 saveSettingsLocked(userId); 2300 } 2301 } 2302 2303 if (changedProviders != null) { 2304 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 2305 return true; 2306 } 2307 2308 return false; 2309 } 2310 2311 @Override 2312 public List<String> getCrossProfileWidgetProviders(ComponentName admin) { 2313 synchronized (this) { 2314 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 2315 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 2316 if (activeAdmin.crossProfileWidgetProviders == null 2317 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 2318 return null; 2319 } 2320 if (Binder.getCallingUid() == Process.myUid()) { 2321 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders); 2322 } else { 2323 return activeAdmin.crossProfileWidgetProviders; 2324 } 2325 } 2326 } 2327 2328 /** 2329 * Return a single admin's expiration date/time, or the min (soonest) for all admins. 2330 * Returns 0 if not configured. 2331 */ 2332 private long getPasswordExpirationLocked(ComponentName who, int userHandle) { 2333 long timeout = 0L; 2334 2335 if (who != null) { 2336 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2337 return admin != null ? admin.passwordExpirationDate : timeout; 2338 } 2339 2340 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2341 for (UserInfo userInfo : profiles) { 2342 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2343 final int N = policy.mAdminList.size(); 2344 for (int i = 0; i < N; i++) { 2345 ActiveAdmin admin = policy.mAdminList.get(i); 2346 if (timeout == 0L || (admin.passwordExpirationDate != 0 2347 && timeout > admin.passwordExpirationDate)) { 2348 timeout = admin.passwordExpirationDate; 2349 } 2350 } 2351 } 2352 return timeout; 2353 } 2354 2355 public long getPasswordExpiration(ComponentName who, int userHandle) { 2356 if (!mHasFeature) { 2357 return 0L; 2358 } 2359 enforceCrossUserPermission(userHandle); 2360 synchronized (this) { 2361 return getPasswordExpirationLocked(who, userHandle); 2362 } 2363 } 2364 2365 public void setPasswordMinimumUpperCase(ComponentName who, int length) { 2366 if (!mHasFeature) { 2367 return; 2368 } 2369 Preconditions.checkNotNull(who, "ComponentName is null"); 2370 final int userHandle = UserHandle.getCallingUserId(); 2371 synchronized (this) { 2372 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2373 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2374 if (ap.minimumPasswordUpperCase != length) { 2375 ap.minimumPasswordUpperCase = length; 2376 saveSettingsLocked(userHandle); 2377 } 2378 } 2379 } 2380 2381 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle) { 2382 if (!mHasFeature) { 2383 return 0; 2384 } 2385 enforceCrossUserPermission(userHandle); 2386 synchronized (this) { 2387 int length = 0; 2388 2389 if (who != null) { 2390 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2391 return admin != null ? admin.minimumPasswordUpperCase : length; 2392 } 2393 2394 // Return strictest policy for this user and profiles that are visible from this user. 2395 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2396 for (UserInfo userInfo : profiles) { 2397 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2398 final int N = policy.mAdminList.size(); 2399 for (int i=0; i<N; i++) { 2400 ActiveAdmin admin = policy.mAdminList.get(i); 2401 if (length < admin.minimumPasswordUpperCase) { 2402 length = admin.minimumPasswordUpperCase; 2403 } 2404 } 2405 } 2406 return length; 2407 } 2408 } 2409 2410 public void setPasswordMinimumLowerCase(ComponentName who, int length) { 2411 Preconditions.checkNotNull(who, "ComponentName is null"); 2412 final int userHandle = UserHandle.getCallingUserId(); 2413 synchronized (this) { 2414 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2415 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2416 if (ap.minimumPasswordLowerCase != length) { 2417 ap.minimumPasswordLowerCase = length; 2418 saveSettingsLocked(userHandle); 2419 } 2420 } 2421 } 2422 2423 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle) { 2424 if (!mHasFeature) { 2425 return 0; 2426 } 2427 enforceCrossUserPermission(userHandle); 2428 synchronized (this) { 2429 int length = 0; 2430 2431 if (who != null) { 2432 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2433 return admin != null ? admin.minimumPasswordLowerCase : length; 2434 } 2435 2436 // Return strictest policy for this user and profiles that are visible from this user. 2437 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2438 for (UserInfo userInfo : profiles) { 2439 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2440 final int N = policy.mAdminList.size(); 2441 for (int i=0; i<N; i++) { 2442 ActiveAdmin admin = policy.mAdminList.get(i); 2443 if (length < admin.minimumPasswordLowerCase) { 2444 length = admin.minimumPasswordLowerCase; 2445 } 2446 } 2447 } 2448 return length; 2449 } 2450 } 2451 2452 public void setPasswordMinimumLetters(ComponentName who, int length) { 2453 if (!mHasFeature) { 2454 return; 2455 } 2456 Preconditions.checkNotNull(who, "ComponentName is null"); 2457 final int userHandle = UserHandle.getCallingUserId(); 2458 synchronized (this) { 2459 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2460 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2461 if (ap.minimumPasswordLetters != length) { 2462 ap.minimumPasswordLetters = length; 2463 saveSettingsLocked(userHandle); 2464 } 2465 } 2466 } 2467 2468 public int getPasswordMinimumLetters(ComponentName who, int userHandle) { 2469 if (!mHasFeature) { 2470 return 0; 2471 } 2472 enforceCrossUserPermission(userHandle); 2473 synchronized (this) { 2474 int length = 0; 2475 2476 if (who != null) { 2477 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2478 return admin != null ? admin.minimumPasswordLetters : length; 2479 } 2480 2481 // Return strictest policy for this user and profiles that are visible from this user. 2482 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2483 for (UserInfo userInfo : profiles) { 2484 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2485 final int N = policy.mAdminList.size(); 2486 for (int i=0; i<N; i++) { 2487 ActiveAdmin admin = policy.mAdminList.get(i); 2488 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 2489 continue; 2490 } 2491 if (length < admin.minimumPasswordLetters) { 2492 length = admin.minimumPasswordLetters; 2493 } 2494 } 2495 } 2496 return length; 2497 } 2498 } 2499 2500 public void setPasswordMinimumNumeric(ComponentName who, int length) { 2501 if (!mHasFeature) { 2502 return; 2503 } 2504 Preconditions.checkNotNull(who, "ComponentName is null"); 2505 final int userHandle = UserHandle.getCallingUserId(); 2506 synchronized (this) { 2507 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2508 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2509 if (ap.minimumPasswordNumeric != length) { 2510 ap.minimumPasswordNumeric = length; 2511 saveSettingsLocked(userHandle); 2512 } 2513 } 2514 } 2515 2516 public int getPasswordMinimumNumeric(ComponentName who, int userHandle) { 2517 if (!mHasFeature) { 2518 return 0; 2519 } 2520 enforceCrossUserPermission(userHandle); 2521 synchronized (this) { 2522 int length = 0; 2523 2524 if (who != null) { 2525 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2526 return admin != null ? admin.minimumPasswordNumeric : length; 2527 } 2528 2529 // Return strictest policy for this user and profiles that are visible from this user. 2530 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2531 for (UserInfo userInfo : profiles) { 2532 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2533 final int N = policy.mAdminList.size(); 2534 for (int i = 0; i < N; i++) { 2535 ActiveAdmin admin = policy.mAdminList.get(i); 2536 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 2537 continue; 2538 } 2539 if (length < admin.minimumPasswordNumeric) { 2540 length = admin.minimumPasswordNumeric; 2541 } 2542 } 2543 } 2544 return length; 2545 } 2546 } 2547 2548 public void setPasswordMinimumSymbols(ComponentName who, int length) { 2549 if (!mHasFeature) { 2550 return; 2551 } 2552 Preconditions.checkNotNull(who, "ComponentName is null"); 2553 final int userHandle = UserHandle.getCallingUserId(); 2554 synchronized (this) { 2555 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2556 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2557 if (ap.minimumPasswordSymbols != length) { 2558 ap.minimumPasswordSymbols = length; 2559 saveSettingsLocked(userHandle); 2560 } 2561 } 2562 } 2563 2564 public int getPasswordMinimumSymbols(ComponentName who, int userHandle) { 2565 if (!mHasFeature) { 2566 return 0; 2567 } 2568 enforceCrossUserPermission(userHandle); 2569 synchronized (this) { 2570 int length = 0; 2571 2572 if (who != null) { 2573 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2574 return admin != null ? admin.minimumPasswordSymbols : length; 2575 } 2576 2577 // Return strictest policy for this user and profiles that are visible from this user. 2578 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2579 for (UserInfo userInfo : profiles) { 2580 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2581 final int N = policy.mAdminList.size(); 2582 for (int i=0; i<N; i++) { 2583 ActiveAdmin admin = policy.mAdminList.get(i); 2584 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 2585 continue; 2586 } 2587 if (length < admin.minimumPasswordSymbols) { 2588 length = admin.minimumPasswordSymbols; 2589 } 2590 } 2591 } 2592 return length; 2593 } 2594 } 2595 2596 public void setPasswordMinimumNonLetter(ComponentName who, int length) { 2597 if (!mHasFeature) { 2598 return; 2599 } 2600 Preconditions.checkNotNull(who, "ComponentName is null"); 2601 final int userHandle = UserHandle.getCallingUserId(); 2602 synchronized (this) { 2603 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2604 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2605 if (ap.minimumPasswordNonLetter != length) { 2606 ap.minimumPasswordNonLetter = length; 2607 saveSettingsLocked(userHandle); 2608 } 2609 } 2610 } 2611 2612 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle) { 2613 if (!mHasFeature) { 2614 return 0; 2615 } 2616 enforceCrossUserPermission(userHandle); 2617 synchronized (this) { 2618 int length = 0; 2619 2620 if (who != null) { 2621 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2622 return admin != null ? admin.minimumPasswordNonLetter : length; 2623 } 2624 2625 // Return strictest policy for this user and profiles that are visible from this user. 2626 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2627 for (UserInfo userInfo : profiles) { 2628 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2629 final int N = policy.mAdminList.size(); 2630 for (int i=0; i<N; i++) { 2631 ActiveAdmin admin = policy.mAdminList.get(i); 2632 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 2633 continue; 2634 } 2635 if (length < admin.minimumPasswordNonLetter) { 2636 length = admin.minimumPasswordNonLetter; 2637 } 2638 } 2639 } 2640 return length; 2641 } 2642 } 2643 2644 public boolean isActivePasswordSufficient(int userHandle) { 2645 if (!mHasFeature) { 2646 return true; 2647 } 2648 enforceCrossUserPermission(userHandle); 2649 2650 synchronized (this) { 2651 2652 // The active password is stored in the user that runs the launcher 2653 // If the user this is called from is part of a profile group, that is the parent 2654 // of the group. 2655 UserInfo parent = getProfileParent(userHandle); 2656 int id = (parent == null) ? userHandle : parent.id; 2657 DevicePolicyData policy = getUserDataUnchecked(id); 2658 2659 // This API can only be called by an active device admin, 2660 // so try to retrieve it to check that the caller is one. 2661 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2662 if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle) 2663 || policy.mActivePasswordLength < getPasswordMinimumLength(null, userHandle)) { 2664 return false; 2665 } 2666 if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 2667 return true; 2668 } 2669 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(null, userHandle) 2670 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(null, userHandle) 2671 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(null, userHandle) 2672 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(null, userHandle) 2673 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(null, userHandle) 2674 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(null, userHandle); 2675 } 2676 } 2677 2678 public int getCurrentFailedPasswordAttempts(int userHandle) { 2679 synchronized (this) { 2680 // This API can only be called by an active device admin, 2681 // so try to retrieve it to check that the caller is one. 2682 getActiveAdminForCallerLocked(null, 2683 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN); 2684 2685 // The active password is stored in the parent. 2686 UserInfo parent = getProfileParent(userHandle); 2687 int id = (parent == null) ? userHandle : parent.id; 2688 DevicePolicyData policy = getUserDataUnchecked(id); 2689 2690 return policy.mFailedPasswordAttempts; 2691 } 2692 } 2693 2694 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num) { 2695 if (!mHasFeature) { 2696 return; 2697 } 2698 Preconditions.checkNotNull(who, "ComponentName is null"); 2699 final int userHandle = UserHandle.getCallingUserId(); 2700 synchronized (this) { 2701 // This API can only be called by an active device admin, 2702 // so try to retrieve it to check that the caller is one. 2703 getActiveAdminForCallerLocked(who, 2704 DeviceAdminInfo.USES_POLICY_WIPE_DATA); 2705 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2706 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN); 2707 if (ap.maximumFailedPasswordsForWipe != num) { 2708 ap.maximumFailedPasswordsForWipe = num; 2709 saveSettingsLocked(userHandle); 2710 } 2711 } 2712 } 2713 2714 @Override 2715 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle) { 2716 if (!mHasFeature) { 2717 return 0; 2718 } 2719 enforceCrossUserPermission(userHandle); 2720 synchronized (this) { 2721 ActiveAdmin admin = (who != null) ? getActiveAdminUncheckedLocked(who, userHandle) 2722 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle); 2723 return admin != null ? admin.maximumFailedPasswordsForWipe : 0; 2724 } 2725 } 2726 2727 @Override 2728 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) { 2729 if (!mHasFeature) { 2730 return UserHandle.USER_NULL; 2731 } 2732 enforceCrossUserPermission(userHandle); 2733 synchronized (this) { 2734 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle); 2735 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL; 2736 } 2737 } 2738 2739 /** 2740 * Returns the admin with the strictest policy on maximum failed passwords for this user and all 2741 * profiles that are visible from this user. If the policy for the primary and any other profile 2742 * are equal, it returns the admin for the primary profile. 2743 * Returns {@code null} if none of them have that policy set. 2744 */ 2745 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(int userHandle) { 2746 int count = 0; 2747 ActiveAdmin strictestAdmin = null; 2748 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 2749 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2750 for (ActiveAdmin admin : policy.mAdminList) { 2751 if (admin.maximumFailedPasswordsForWipe == 2752 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 2753 continue; // No max number of failed passwords policy set for this profile. 2754 } 2755 2756 // We always favor the primary profile if several profiles have the same value set. 2757 if (count == 0 || 2758 count > admin.maximumFailedPasswordsForWipe || 2759 (userInfo.isPrimary() && count >= admin.maximumFailedPasswordsForWipe)) { 2760 count = admin.maximumFailedPasswordsForWipe; 2761 strictestAdmin = admin; 2762 } 2763 } 2764 } 2765 return strictestAdmin; 2766 } 2767 2768 public boolean resetPassword(String passwordOrNull, int flags) { 2769 if (!mHasFeature) { 2770 return false; 2771 } 2772 final int userHandle = UserHandle.getCallingUserId(); 2773 enforceNotManagedProfile(userHandle, "reset the password"); 2774 2775 String password = passwordOrNull != null ? passwordOrNull : ""; 2776 2777 int quality; 2778 synchronized (this) { 2779 // This api can only be called by an active device admin, 2780 // so try to retrieve it to check that the caller is one. 2781 getActiveAdminForCallerLocked(null, 2782 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD); 2783 quality = getPasswordQuality(null, userHandle); 2784 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { 2785 int realQuality = LockPatternUtils.computePasswordQuality(password); 2786 if (realQuality < quality 2787 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 2788 Slog.w(LOG_TAG, "resetPassword: password quality 0x" 2789 + Integer.toHexString(realQuality) 2790 + " does not meet required quality 0x" 2791 + Integer.toHexString(quality)); 2792 return false; 2793 } 2794 quality = Math.max(realQuality, quality); 2795 } 2796 int length = getPasswordMinimumLength(null, userHandle); 2797 if (password.length() < length) { 2798 Slog.w(LOG_TAG, "resetPassword: password length " + password.length() 2799 + " does not meet required length " + length); 2800 return false; 2801 } 2802 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 2803 int letters = 0; 2804 int uppercase = 0; 2805 int lowercase = 0; 2806 int numbers = 0; 2807 int symbols = 0; 2808 int nonletter = 0; 2809 for (int i = 0; i < password.length(); i++) { 2810 char c = password.charAt(i); 2811 if (c >= 'A' && c <= 'Z') { 2812 letters++; 2813 uppercase++; 2814 } else if (c >= 'a' && c <= 'z') { 2815 letters++; 2816 lowercase++; 2817 } else if (c >= '0' && c <= '9') { 2818 numbers++; 2819 nonletter++; 2820 } else { 2821 symbols++; 2822 nonletter++; 2823 } 2824 } 2825 int neededLetters = getPasswordMinimumLetters(null, userHandle); 2826 if(letters < neededLetters) { 2827 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters 2828 + " does not meet required number of letters " + neededLetters); 2829 return false; 2830 } 2831 int neededNumbers = getPasswordMinimumNumeric(null, userHandle); 2832 if (numbers < neededNumbers) { 2833 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers 2834 + " does not meet required number of numerical digits " 2835 + neededNumbers); 2836 return false; 2837 } 2838 int neededLowerCase = getPasswordMinimumLowerCase(null, userHandle); 2839 if (lowercase < neededLowerCase) { 2840 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase 2841 + " does not meet required number of lowercase letters " 2842 + neededLowerCase); 2843 return false; 2844 } 2845 int neededUpperCase = getPasswordMinimumUpperCase(null, userHandle); 2846 if (uppercase < neededUpperCase) { 2847 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase 2848 + " does not meet required number of uppercase letters " 2849 + neededUpperCase); 2850 return false; 2851 } 2852 int neededSymbols = getPasswordMinimumSymbols(null, userHandle); 2853 if (symbols < neededSymbols) { 2854 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols 2855 + " does not meet required number of special symbols " + neededSymbols); 2856 return false; 2857 } 2858 int neededNonLetter = getPasswordMinimumNonLetter(null, userHandle); 2859 if (nonletter < neededNonLetter) { 2860 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter 2861 + " does not meet required number of non-letter characters " 2862 + neededNonLetter); 2863 return false; 2864 } 2865 } 2866 } 2867 2868 int callingUid = Binder.getCallingUid(); 2869 DevicePolicyData policy = getUserData(userHandle); 2870 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) { 2871 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user"); 2872 return false; 2873 } 2874 2875 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwnerOrInitializer(callingUid); 2876 boolean doNotAskCredentialsOnBoot = 2877 (flags & DevicePolicyManager.DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0; 2878 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) { 2879 setDoNotAskCredentialsOnBoot(); 2880 } 2881 2882 // Don't do this with the lock held, because it is going to call 2883 // back in to the service. 2884 long ident = Binder.clearCallingIdentity(); 2885 try { 2886 LockPatternUtils utils = new LockPatternUtils(mContext); 2887 if (!TextUtils.isEmpty(password)) { 2888 utils.saveLockPassword(password, null, quality, userHandle); 2889 } else { 2890 utils.clearLock(userHandle); 2891 } 2892 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0; 2893 if (requireEntry) { 2894 utils.requireCredentialEntry(UserHandle.USER_ALL); 2895 } 2896 synchronized (this) { 2897 int newOwner = requireEntry ? callingUid : -1; 2898 if (policy.mPasswordOwner != newOwner) { 2899 policy.mPasswordOwner = newOwner; 2900 saveSettingsLocked(userHandle); 2901 } 2902 } 2903 } finally { 2904 Binder.restoreCallingIdentity(ident); 2905 } 2906 2907 return true; 2908 } 2909 2910 private void setDoNotAskCredentialsOnBoot() { 2911 synchronized (this) { 2912 DevicePolicyData policyData = getUserData(UserHandle.USER_OWNER); 2913 if (!policyData.doNotAskCredentialsOnBoot) { 2914 policyData.doNotAskCredentialsOnBoot = true; 2915 saveSettingsLocked(UserHandle.USER_OWNER); 2916 } 2917 } 2918 } 2919 2920 public boolean getDoNotAskCredentialsOnBoot() { 2921 mContext.enforceCallingOrSelfPermission( 2922 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null); 2923 synchronized (this) { 2924 DevicePolicyData policyData = getUserData(UserHandle.USER_OWNER); 2925 return policyData.doNotAskCredentialsOnBoot; 2926 } 2927 } 2928 2929 public void setMaximumTimeToLock(ComponentName who, long timeMs) { 2930 if (!mHasFeature) { 2931 return; 2932 } 2933 Preconditions.checkNotNull(who, "ComponentName is null"); 2934 final int userHandle = UserHandle.getCallingUserId(); 2935 synchronized (this) { 2936 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2937 DeviceAdminInfo.USES_POLICY_FORCE_LOCK); 2938 if (ap.maximumTimeToUnlock != timeMs) { 2939 ap.maximumTimeToUnlock = timeMs; 2940 saveSettingsLocked(userHandle); 2941 updateMaximumTimeToLockLocked(getUserData(userHandle)); 2942 } 2943 } 2944 } 2945 2946 void updateMaximumTimeToLockLocked(DevicePolicyData policy) { 2947 long timeMs = getMaximumTimeToLock(null, policy.mUserHandle); 2948 if (policy.mLastMaximumTimeToLock == timeMs) { 2949 return; 2950 } 2951 2952 long ident = Binder.clearCallingIdentity(); 2953 try { 2954 if (timeMs <= 0) { 2955 timeMs = Integer.MAX_VALUE; 2956 } else { 2957 // Make sure KEEP_SCREEN_ON is disabled, since that 2958 // would allow bypassing of the maximum time to lock. 2959 Settings.Global.putInt(mContext.getContentResolver(), 2960 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0); 2961 } 2962 2963 policy.mLastMaximumTimeToLock = timeMs; 2964 mPowerManagerInternal.setMaximumScreenOffTimeoutFromDeviceAdmin((int)timeMs); 2965 } finally { 2966 Binder.restoreCallingIdentity(ident); 2967 } 2968 } 2969 2970 public long getMaximumTimeToLock(ComponentName who, int userHandle) { 2971 if (!mHasFeature) { 2972 return 0; 2973 } 2974 enforceCrossUserPermission(userHandle); 2975 synchronized (this) { 2976 long time = 0; 2977 2978 if (who != null) { 2979 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2980 return admin != null ? admin.maximumTimeToUnlock : time; 2981 } 2982 2983 // Return strictest policy for this user and profiles that are visible from this user. 2984 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2985 for (UserInfo userInfo : profiles) { 2986 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 2987 final int N = policy.mAdminList.size(); 2988 for (int i=0; i<N; i++) { 2989 ActiveAdmin admin = policy.mAdminList.get(i); 2990 if (time == 0) { 2991 time = admin.maximumTimeToUnlock; 2992 } else if (admin.maximumTimeToUnlock != 0 2993 && time > admin.maximumTimeToUnlock) { 2994 time = admin.maximumTimeToUnlock; 2995 } 2996 } 2997 } 2998 return time; 2999 } 3000 } 3001 3002 public void lockNow() { 3003 if (!mHasFeature) { 3004 return; 3005 } 3006 synchronized (this) { 3007 // This API can only be called by an active device admin, 3008 // so try to retrieve it to check that the caller is one. 3009 getActiveAdminForCallerLocked(null, 3010 DeviceAdminInfo.USES_POLICY_FORCE_LOCK); 3011 lockNowUnchecked(); 3012 } 3013 } 3014 3015 private void lockNowUnchecked() { 3016 long ident = Binder.clearCallingIdentity(); 3017 try { 3018 // Power off the display 3019 mPowerManager.goToSleep(SystemClock.uptimeMillis(), 3020 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0); 3021 // Ensure the device is locked 3022 new LockPatternUtils(mContext).requireCredentialEntry(UserHandle.USER_ALL); 3023 getWindowManager().lockNow(null); 3024 } catch (RemoteException e) { 3025 } finally { 3026 Binder.restoreCallingIdentity(ident); 3027 } 3028 } 3029 3030 private boolean isExtStorageEncrypted() { 3031 String state = SystemProperties.get("vold.decrypt"); 3032 return !"".equals(state); 3033 } 3034 3035 @Override 3036 public void enforceCanManageCaCerts(ComponentName who) { 3037 if (who == null) { 3038 if (!isCallerDelegatedCertInstaller()) { 3039 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null); 3040 } 3041 } else { 3042 synchronized (this) { 3043 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3044 } 3045 } 3046 } 3047 3048 private boolean isCallerDelegatedCertInstaller() { 3049 final int callingUid = Binder.getCallingUid(); 3050 final int userHandle = UserHandle.getUserId(callingUid); 3051 synchronized (this) { 3052 final DevicePolicyData policy = getUserData(userHandle); 3053 if (policy.mDelegatedCertInstallerPackage == null) { 3054 return false; 3055 } 3056 3057 try { 3058 int uid = mContext.getPackageManager().getPackageUid( 3059 policy.mDelegatedCertInstallerPackage, userHandle); 3060 return uid == callingUid; 3061 } catch (NameNotFoundException e) { 3062 return false; 3063 } 3064 } 3065 } 3066 3067 @Override 3068 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException { 3069 enforceCanManageCaCerts(admin); 3070 3071 byte[] pemCert; 3072 try { 3073 X509Certificate cert = parseCert(certBuffer); 3074 pemCert = Credentials.convertToPem(cert); 3075 } catch (CertificateException ce) { 3076 Log.e(LOG_TAG, "Problem converting cert", ce); 3077 return false; 3078 } catch (IOException ioe) { 3079 Log.e(LOG_TAG, "Problem reading cert", ioe); 3080 return false; 3081 } 3082 3083 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 3084 final long id = Binder.clearCallingIdentity(); 3085 try { 3086 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 3087 try { 3088 keyChainConnection.getService().installCaCertificate(pemCert); 3089 return true; 3090 } catch (RemoteException e) { 3091 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e); 3092 } finally { 3093 keyChainConnection.close(); 3094 } 3095 } catch (InterruptedException e1) { 3096 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1); 3097 Thread.currentThread().interrupt(); 3098 } finally { 3099 Binder.restoreCallingIdentity(id); 3100 } 3101 return false; 3102 } 3103 3104 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException { 3105 CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); 3106 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream( 3107 certBuffer)); 3108 } 3109 3110 @Override 3111 public void uninstallCaCert(ComponentName admin, String alias) { 3112 enforceCanManageCaCerts(admin); 3113 3114 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 3115 final long id = Binder.clearCallingIdentity(); 3116 try { 3117 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 3118 try { 3119 keyChainConnection.getService().deleteCaCertificate(alias); 3120 } catch (RemoteException e) { 3121 Log.e(LOG_TAG, "from CaCertUninstaller: ", e); 3122 } finally { 3123 keyChainConnection.close(); 3124 } 3125 } catch (InterruptedException ie) { 3126 Log.w(LOG_TAG, "CaCertUninstaller: ", ie); 3127 Thread.currentThread().interrupt(); 3128 } finally { 3129 Binder.restoreCallingIdentity(id); 3130 } 3131 } 3132 3133 @Override 3134 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, String alias) { 3135 if (who == null) { 3136 if (!isCallerDelegatedCertInstaller()) { 3137 throw new SecurityException("who == null, but caller is not cert installer"); 3138 } 3139 } else { 3140 synchronized (this) { 3141 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3142 } 3143 } 3144 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 3145 final long id = Binder.clearCallingIdentity(); 3146 try { 3147 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 3148 try { 3149 IKeyChainService keyChain = keyChainConnection.getService(); 3150 return keyChain.installKeyPair(privKey, cert, alias); 3151 } catch (RemoteException e) { 3152 Log.e(LOG_TAG, "Installing certificate", e); 3153 } finally { 3154 keyChainConnection.close(); 3155 } 3156 } catch (InterruptedException e) { 3157 Log.w(LOG_TAG, "Interrupted while installing certificate", e); 3158 Thread.currentThread().interrupt(); 3159 } finally { 3160 Binder.restoreCallingIdentity(id); 3161 } 3162 return false; 3163 } 3164 3165 @Override 3166 public void choosePrivateKeyAlias(final int uid, final String host, int port, final String url, 3167 final String alias, final IBinder response) { 3168 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers. 3169 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) { 3170 return; 3171 } 3172 3173 final UserHandle caller = Binder.getCallingUserHandle(); 3174 final ComponentName profileOwner = getProfileOwner(caller.getIdentifier()); 3175 3176 if (profileOwner == null) { 3177 sendPrivateKeyAliasResponse(null, response); 3178 return; 3179 } 3180 3181 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS); 3182 intent.setComponent(profileOwner); 3183 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid); 3184 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_HOST, host); 3185 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_PORT, port); 3186 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URL, url); 3187 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias); 3188 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response); 3189 3190 final long id = Binder.clearCallingIdentity(); 3191 try { 3192 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() { 3193 @Override 3194 public void onReceive(Context context, Intent intent) { 3195 final String chosenAlias = getResultData(); 3196 sendPrivateKeyAliasResponse(chosenAlias, response); 3197 } 3198 }, null, Activity.RESULT_OK, null, null); 3199 } finally { 3200 Binder.restoreCallingIdentity(id); 3201 } 3202 } 3203 3204 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) { 3205 final IKeyChainAliasCallback keyChainAliasResponse = 3206 IKeyChainAliasCallback.Stub.asInterface(responseBinder); 3207 new AsyncTask<Void, Void, Void>() { 3208 @Override 3209 protected Void doInBackground(Void... unused) { 3210 try { 3211 keyChainAliasResponse.alias(alias); 3212 } catch (Exception e) { 3213 // Catch everything (not just RemoteException): caller could throw a 3214 // RuntimeException back across processes. 3215 Log.e(LOG_TAG, "error while responding to callback", e); 3216 } 3217 return null; 3218 } 3219 }.execute(); 3220 } 3221 3222 @Override 3223 public void setCertInstallerPackage(ComponentName who, String installerPackage) 3224 throws SecurityException { 3225 int userHandle = UserHandle.getCallingUserId(); 3226 synchronized (this) { 3227 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3228 DevicePolicyData policy = getUserData(userHandle); 3229 policy.mDelegatedCertInstallerPackage = installerPackage; 3230 saveSettingsLocked(userHandle); 3231 } 3232 } 3233 3234 @Override 3235 public String getCertInstallerPackage(ComponentName who) throws SecurityException { 3236 int userHandle = UserHandle.getCallingUserId(); 3237 synchronized (this) { 3238 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3239 DevicePolicyData policy = getUserData(userHandle); 3240 return policy.mDelegatedCertInstallerPackage; 3241 } 3242 } 3243 3244 private void wipeDataLocked(boolean wipeExtRequested, String reason) { 3245 // TODO: wipe all public volumes on device 3246 3247 // If the SD card is encrypted and non-removable, we have to force a wipe. 3248 boolean forceExtWipe = !Environment.isExternalStorageRemovable() && isExtStorageEncrypted(); 3249 3250 // Note: we can only do the wipe via ExternalStorageFormatter if the volume is not emulated. 3251 if ((forceExtWipe || wipeExtRequested) && !Environment.isExternalStorageEmulated()) { 3252 Intent intent = new Intent(ExternalStorageFormatter.FORMAT_AND_FACTORY_RESET); 3253 intent.putExtra(ExternalStorageFormatter.EXTRA_ALWAYS_RESET, true); 3254 intent.putExtra(Intent.EXTRA_REASON, reason); 3255 intent.setComponent(ExternalStorageFormatter.COMPONENT_NAME); 3256 mWakeLock.acquire(10000); 3257 mContext.startService(intent); 3258 } else { 3259 try { 3260 RecoverySystem.rebootWipeUserData(mContext, reason); 3261 } catch (IOException | SecurityException e) { 3262 Slog.w(LOG_TAG, "Failed requesting data wipe", e); 3263 } 3264 } 3265 } 3266 3267 @Override 3268 public void wipeData(int flags, final int userHandle) { 3269 if (!mHasFeature) { 3270 return; 3271 } 3272 enforceCrossUserPermission(userHandle); 3273 synchronized (this) { 3274 // This API can only be called by an active device admin, 3275 // so try to retrieve it to check that the caller is one. 3276 final ActiveAdmin admin = getActiveAdminForCallerLocked(null, 3277 DeviceAdminInfo.USES_POLICY_WIPE_DATA); 3278 3279 final String source; 3280 final ComponentName cname = admin.info.getComponent(); 3281 if (cname != null) { 3282 source = cname.flattenToShortString(); 3283 } else { 3284 source = admin.info.getPackageName(); 3285 } 3286 3287 long ident = Binder.clearCallingIdentity(); 3288 try { 3289 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) { 3290 boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName()) 3291 && !hasUserSetupCompleted(userHandle); 3292 if (userHandle != UserHandle.USER_OWNER 3293 || !(isDeviceOwner(admin.info.getPackageName()) 3294 || ownsInitialization)) { 3295 throw new SecurityException( 3296 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA"); 3297 } 3298 PersistentDataBlockManager manager = (PersistentDataBlockManager) 3299 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE); 3300 if (manager != null) { 3301 manager.wipe(); 3302 } 3303 } 3304 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0; 3305 wipeDeviceOrUserLocked(wipeExtRequested, userHandle, 3306 "DevicePolicyManager.wipeData() from " + source); 3307 } finally { 3308 Binder.restoreCallingIdentity(ident); 3309 } 3310 } 3311 } 3312 3313 private void wipeDeviceOrUserLocked(boolean wipeExtRequested, final int userHandle, String reason) { 3314 if (userHandle == UserHandle.USER_OWNER) { 3315 wipeDataLocked(wipeExtRequested, reason); 3316 } else { 3317 mHandler.post(new Runnable() { 3318 public void run() { 3319 try { 3320 IActivityManager am = ActivityManagerNative.getDefault(); 3321 if (am.getCurrentUser().id == userHandle) { 3322 am.switchUser(UserHandle.USER_OWNER); 3323 } 3324 if (!mUserManager.removeUser(userHandle)) { 3325 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle); 3326 } 3327 } catch (RemoteException re) { 3328 // Shouldn't happen 3329 } 3330 } 3331 }); 3332 } 3333 } 3334 3335 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) { 3336 if (!mHasFeature) { 3337 return; 3338 } 3339 enforceCrossUserPermission(userHandle); 3340 mContext.enforceCallingOrSelfPermission( 3341 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 3342 3343 synchronized (this) { 3344 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle); 3345 if (admin == null) { 3346 try { 3347 result.sendResult(null); 3348 } catch (RemoteException e) { 3349 } 3350 return; 3351 } 3352 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED); 3353 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 3354 intent.setComponent(admin.info.getComponent()); 3355 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle), 3356 null, new BroadcastReceiver() { 3357 @Override 3358 public void onReceive(Context context, Intent intent) { 3359 try { 3360 result.sendResult(getResultExtras(false)); 3361 } catch (RemoteException e) { 3362 } 3363 } 3364 }, null, Activity.RESULT_OK, null, null); 3365 } 3366 } 3367 3368 public void setActivePasswordState(int quality, int length, int letters, int uppercase, 3369 int lowercase, int numbers, int symbols, int nonletter, int userHandle) { 3370 if (!mHasFeature) { 3371 return; 3372 } 3373 enforceCrossUserPermission(userHandle); 3374 enforceNotManagedProfile(userHandle, "set the active password"); 3375 3376 mContext.enforceCallingOrSelfPermission( 3377 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 3378 DevicePolicyData p = getUserData(userHandle); 3379 3380 validateQualityConstant(quality); 3381 3382 synchronized (this) { 3383 if (p.mActivePasswordQuality != quality || p.mActivePasswordLength != length 3384 || p.mFailedPasswordAttempts != 0 || p.mActivePasswordLetters != letters 3385 || p.mActivePasswordUpperCase != uppercase 3386 || p.mActivePasswordLowerCase != lowercase 3387 || p.mActivePasswordNumeric != numbers 3388 || p.mActivePasswordSymbols != symbols 3389 || p.mActivePasswordNonLetter != nonletter) { 3390 long ident = Binder.clearCallingIdentity(); 3391 try { 3392 p.mActivePasswordQuality = quality; 3393 p.mActivePasswordLength = length; 3394 p.mActivePasswordLetters = letters; 3395 p.mActivePasswordLowerCase = lowercase; 3396 p.mActivePasswordUpperCase = uppercase; 3397 p.mActivePasswordNumeric = numbers; 3398 p.mActivePasswordSymbols = symbols; 3399 p.mActivePasswordNonLetter = nonletter; 3400 p.mFailedPasswordAttempts = 0; 3401 saveSettingsLocked(userHandle); 3402 updatePasswordExpirationsLocked(userHandle); 3403 setExpirationAlarmCheckLocked(mContext, p); 3404 sendAdminCommandToSelfAndProfilesLocked( 3405 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED, 3406 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle); 3407 } finally { 3408 Binder.restoreCallingIdentity(ident); 3409 } 3410 } 3411 } 3412 } 3413 3414 /** 3415 * Called any time the device password is updated. Resets all password expiration clocks. 3416 */ 3417 private void updatePasswordExpirationsLocked(int userHandle) { 3418 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 3419 for (UserInfo userInfo : profiles) { 3420 int profileId = userInfo.id; 3421 DevicePolicyData policy = getUserDataUnchecked(profileId); 3422 final int N = policy.mAdminList.size(); 3423 if (N > 0) { 3424 for (int i=0; i<N; i++) { 3425 ActiveAdmin admin = policy.mAdminList.get(i); 3426 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) { 3427 long timeout = admin.passwordExpirationTimeout; 3428 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 3429 admin.passwordExpirationDate = expiration; 3430 } 3431 } 3432 } 3433 saveSettingsLocked(profileId); 3434 } 3435 } 3436 3437 public void reportFailedPasswordAttempt(int userHandle) { 3438 enforceCrossUserPermission(userHandle); 3439 enforceNotManagedProfile(userHandle, "report failed password attempt"); 3440 mContext.enforceCallingOrSelfPermission( 3441 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 3442 3443 long ident = Binder.clearCallingIdentity(); 3444 try { 3445 boolean wipeData = false; 3446 int identifier = 0; 3447 synchronized (this) { 3448 DevicePolicyData policy = getUserData(userHandle); 3449 policy.mFailedPasswordAttempts++; 3450 saveSettingsLocked(userHandle); 3451 if (mHasFeature) { 3452 ActiveAdmin strictestAdmin = 3453 getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle); 3454 int max = strictestAdmin != null 3455 ? strictestAdmin.maximumFailedPasswordsForWipe : 0; 3456 if (max > 0 && policy.mFailedPasswordAttempts >= max) { 3457 // Wipe the user/profile associated with the policy that was violated. This 3458 // is not necessarily calling user: if the policy that fired was from a 3459 // managed profile rather than the main user profile, we wipe former only. 3460 wipeData = true; 3461 identifier = strictestAdmin.getUserHandle().getIdentifier(); 3462 } 3463 sendAdminCommandToSelfAndProfilesLocked( 3464 DeviceAdminReceiver.ACTION_PASSWORD_FAILED, 3465 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 3466 } 3467 } 3468 if (wipeData) { 3469 // Call without holding lock. 3470 wipeDeviceOrUserLocked(false, identifier, 3471 "reportFailedPasswordAttempt()"); 3472 } 3473 } finally { 3474 Binder.restoreCallingIdentity(ident); 3475 } 3476 } 3477 3478 public void reportSuccessfulPasswordAttempt(int userHandle) { 3479 enforceCrossUserPermission(userHandle); 3480 mContext.enforceCallingOrSelfPermission( 3481 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 3482 3483 synchronized (this) { 3484 DevicePolicyData policy = getUserData(userHandle); 3485 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) { 3486 long ident = Binder.clearCallingIdentity(); 3487 try { 3488 policy.mFailedPasswordAttempts = 0; 3489 policy.mPasswordOwner = -1; 3490 saveSettingsLocked(userHandle); 3491 if (mHasFeature) { 3492 sendAdminCommandToSelfAndProfilesLocked( 3493 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED, 3494 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 3495 } 3496 } finally { 3497 Binder.restoreCallingIdentity(ident); 3498 } 3499 } 3500 } 3501 } 3502 3503 public ComponentName setGlobalProxy(ComponentName who, String proxySpec, 3504 String exclusionList) { 3505 if (!mHasFeature) { 3506 return null; 3507 } 3508 synchronized(this) { 3509 Preconditions.checkNotNull(who, "ComponentName is null"); 3510 3511 // Only check if owner has set global proxy. We don't allow other users to set it. 3512 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER); 3513 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 3514 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 3515 3516 // Scan through active admins and find if anyone has already 3517 // set the global proxy. 3518 Set<ComponentName> compSet = policy.mAdminMap.keySet(); 3519 for (ComponentName component : compSet) { 3520 ActiveAdmin ap = policy.mAdminMap.get(component); 3521 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) { 3522 // Another admin already sets the global proxy 3523 // Return it to the caller. 3524 return component; 3525 } 3526 } 3527 3528 // If the user is not the owner, don't set the global proxy. Fail silently. 3529 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) { 3530 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User " 3531 + UserHandle.getCallingUserId() + " is not permitted."); 3532 return null; 3533 } 3534 if (proxySpec == null) { 3535 admin.specifiesGlobalProxy = false; 3536 admin.globalProxySpec = null; 3537 admin.globalProxyExclusionList = null; 3538 } else { 3539 3540 admin.specifiesGlobalProxy = true; 3541 admin.globalProxySpec = proxySpec; 3542 admin.globalProxyExclusionList = exclusionList; 3543 } 3544 3545 // Reset the global proxy accordingly 3546 // Do this using system permissions, as apps cannot write to secure settings 3547 long origId = Binder.clearCallingIdentity(); 3548 try { 3549 resetGlobalProxyLocked(policy); 3550 } finally { 3551 Binder.restoreCallingIdentity(origId); 3552 } 3553 return null; 3554 } 3555 } 3556 3557 public ComponentName getGlobalProxyAdmin(int userHandle) { 3558 if (!mHasFeature) { 3559 return null; 3560 } 3561 enforceCrossUserPermission(userHandle); 3562 synchronized(this) { 3563 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER); 3564 // Scan through active admins and find if anyone has already 3565 // set the global proxy. 3566 final int N = policy.mAdminList.size(); 3567 for (int i = 0; i < N; i++) { 3568 ActiveAdmin ap = policy.mAdminList.get(i); 3569 if (ap.specifiesGlobalProxy) { 3570 // Device admin sets the global proxy 3571 // Return it to the caller. 3572 return ap.info.getComponent(); 3573 } 3574 } 3575 } 3576 // No device admin sets the global proxy. 3577 return null; 3578 } 3579 3580 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) { 3581 synchronized (this) { 3582 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 3583 } 3584 long token = Binder.clearCallingIdentity(); 3585 try { 3586 ConnectivityManager connectivityManager = (ConnectivityManager) 3587 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 3588 connectivityManager.setGlobalProxy(proxyInfo); 3589 } finally { 3590 Binder.restoreCallingIdentity(token); 3591 } 3592 } 3593 3594 private void resetGlobalProxyLocked(DevicePolicyData policy) { 3595 final int N = policy.mAdminList.size(); 3596 for (int i = 0; i < N; i++) { 3597 ActiveAdmin ap = policy.mAdminList.get(i); 3598 if (ap.specifiesGlobalProxy) { 3599 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList); 3600 return; 3601 } 3602 } 3603 // No device admins defining global proxies - reset global proxy settings to none 3604 saveGlobalProxyLocked(null, null); 3605 } 3606 3607 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) { 3608 if (exclusionList == null) { 3609 exclusionList = ""; 3610 } 3611 if (proxySpec == null) { 3612 proxySpec = ""; 3613 } 3614 // Remove white spaces 3615 proxySpec = proxySpec.trim(); 3616 String data[] = proxySpec.split(":"); 3617 int proxyPort = 8080; 3618 if (data.length > 1) { 3619 try { 3620 proxyPort = Integer.parseInt(data[1]); 3621 } catch (NumberFormatException e) {} 3622 } 3623 exclusionList = exclusionList.trim(); 3624 ContentResolver res = mContext.getContentResolver(); 3625 3626 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList); 3627 if (!proxyProperties.isValid()) { 3628 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3629 return; 3630 } 3631 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]); 3632 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort); 3633 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 3634 exclusionList); 3635 } 3636 3637 /** 3638 * Set the storage encryption request for a single admin. Returns the new total request 3639 * status (for all admins). 3640 */ 3641 public int setStorageEncryption(ComponentName who, boolean encrypt) { 3642 if (!mHasFeature) { 3643 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 3644 } 3645 Preconditions.checkNotNull(who, "ComponentName is null"); 3646 final int userHandle = UserHandle.getCallingUserId(); 3647 synchronized (this) { 3648 // Check for permissions 3649 // Only owner can set storage encryption 3650 if (userHandle != UserHandle.USER_OWNER 3651 || UserHandle.getCallingUserId() != UserHandle.USER_OWNER) { 3652 Slog.w(LOG_TAG, "Only owner is allowed to set storage encryption. User " 3653 + UserHandle.getCallingUserId() + " is not permitted."); 3654 return 0; 3655 } 3656 3657 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 3658 DeviceAdminInfo.USES_ENCRYPTED_STORAGE); 3659 3660 // Quick exit: If the filesystem does not support encryption, we can exit early. 3661 if (!isEncryptionSupported()) { 3662 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 3663 } 3664 3665 // (1) Record the value for the admin so it's sticky 3666 if (ap.encryptionRequested != encrypt) { 3667 ap.encryptionRequested = encrypt; 3668 saveSettingsLocked(userHandle); 3669 } 3670 3671 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER); 3672 // (2) Compute "max" for all admins 3673 boolean newRequested = false; 3674 final int N = policy.mAdminList.size(); 3675 for (int i = 0; i < N; i++) { 3676 newRequested |= policy.mAdminList.get(i).encryptionRequested; 3677 } 3678 3679 // Notify OS of new request 3680 setEncryptionRequested(newRequested); 3681 3682 // Return the new global request status 3683 return newRequested 3684 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 3685 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 3686 } 3687 } 3688 3689 /** 3690 * Get the current storage encryption request status for a given admin, or aggregate of all 3691 * active admins. 3692 */ 3693 public boolean getStorageEncryption(ComponentName who, int userHandle) { 3694 if (!mHasFeature) { 3695 return false; 3696 } 3697 enforceCrossUserPermission(userHandle); 3698 synchronized (this) { 3699 // Check for permissions if a particular caller is specified 3700 if (who != null) { 3701 // When checking for a single caller, status is based on caller's request 3702 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle); 3703 return ap != null ? ap.encryptionRequested : false; 3704 } 3705 3706 // If no particular caller is specified, return the aggregate set of requests. 3707 // This is short circuited by returning true on the first hit. 3708 DevicePolicyData policy = getUserData(userHandle); 3709 final int N = policy.mAdminList.size(); 3710 for (int i = 0; i < N; i++) { 3711 if (policy.mAdminList.get(i).encryptionRequested) { 3712 return true; 3713 } 3714 } 3715 return false; 3716 } 3717 } 3718 3719 /** 3720 * Get the current encryption status of the device. 3721 */ 3722 public int getStorageEncryptionStatus(int userHandle) { 3723 if (!mHasFeature) { 3724 // Ok to return current status. 3725 } 3726 enforceCrossUserPermission(userHandle); 3727 return getEncryptionStatus(); 3728 } 3729 3730 /** 3731 * Hook to low-levels: This should report if the filesystem supports encrypted storage. 3732 */ 3733 private boolean isEncryptionSupported() { 3734 // Note, this can be implemented as 3735 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 3736 // But is provided as a separate internal method if there's a faster way to do a 3737 // simple check for supported-or-not. 3738 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 3739 } 3740 3741 /** 3742 * Hook to low-levels: Reporting the current status of encryption. 3743 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}, 3744 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE}, 3745 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, or 3746 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}. 3747 */ 3748 private int getEncryptionStatus() { 3749 String status = SystemProperties.get("ro.crypto.state", "unsupported"); 3750 if ("encrypted".equalsIgnoreCase(status)) { 3751 final long token = Binder.clearCallingIdentity(); 3752 try { 3753 return LockPatternUtils.isDeviceEncrypted() 3754 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 3755 : DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY; 3756 } finally { 3757 Binder.restoreCallingIdentity(token); 3758 } 3759 } else if ("unencrypted".equalsIgnoreCase(status)) { 3760 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 3761 } else { 3762 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 3763 } 3764 } 3765 3766 /** 3767 * Hook to low-levels: If needed, record the new admin setting for encryption. 3768 */ 3769 private void setEncryptionRequested(boolean encrypt) { 3770 } 3771 3772 3773 /** 3774 * Set whether the screen capture is disabled for the user managed by the specified admin. 3775 */ 3776 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) { 3777 if (!mHasFeature) { 3778 return; 3779 } 3780 Preconditions.checkNotNull(who, "ComponentName is null"); 3781 final int userHandle = UserHandle.getCallingUserId(); 3782 synchronized (this) { 3783 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 3784 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3785 if (ap.disableScreenCapture != disabled) { 3786 ap.disableScreenCapture = disabled; 3787 saveSettingsLocked(userHandle); 3788 updateScreenCaptureDisabledInWindowManager(userHandle, disabled); 3789 } 3790 } 3791 } 3792 3793 /** 3794 * Returns whether or not screen capture is disabled for a given admin, or disabled for any 3795 * active admin (if given admin is null). 3796 */ 3797 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) { 3798 if (!mHasFeature) { 3799 return false; 3800 } 3801 synchronized (this) { 3802 if (who != null) { 3803 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 3804 return (admin != null) ? admin.disableScreenCapture : false; 3805 } 3806 3807 DevicePolicyData policy = getUserData(userHandle); 3808 final int N = policy.mAdminList.size(); 3809 for (int i = 0; i < N; i++) { 3810 ActiveAdmin admin = policy.mAdminList.get(i); 3811 if (admin.disableScreenCapture) { 3812 return true; 3813 } 3814 } 3815 return false; 3816 } 3817 } 3818 3819 private void updateScreenCaptureDisabledInWindowManager(int userHandle, boolean disabled) { 3820 long ident = Binder.clearCallingIdentity(); 3821 try { 3822 getWindowManager().setScreenCaptureDisabled(userHandle, disabled); 3823 } catch (RemoteException e) { 3824 Log.w(LOG_TAG, "Unable to notify WindowManager.", e); 3825 } finally { 3826 Binder.restoreCallingIdentity(ident); 3827 } 3828 } 3829 3830 /** 3831 * Set whether auto time is required by the specified admin (must be device owner). 3832 */ 3833 public void setAutoTimeRequired(ComponentName who, boolean required) { 3834 if (!mHasFeature) { 3835 return; 3836 } 3837 Preconditions.checkNotNull(who, "ComponentName is null"); 3838 final int userHandle = UserHandle.getCallingUserId(); 3839 synchronized (this) { 3840 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 3841 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 3842 if (admin.requireAutoTime != required) { 3843 admin.requireAutoTime = required; 3844 saveSettingsLocked(userHandle); 3845 } 3846 } 3847 3848 // Turn AUTO_TIME on in settings if it is required 3849 if (required) { 3850 long ident = Binder.clearCallingIdentity(); 3851 try { 3852 Settings.Global.putInt(mContext.getContentResolver(), 3853 Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */); 3854 } finally { 3855 Binder.restoreCallingIdentity(ident); 3856 } 3857 } 3858 } 3859 3860 /** 3861 * Returns whether or not auto time is required by the device owner. 3862 */ 3863 public boolean getAutoTimeRequired() { 3864 if (!mHasFeature) { 3865 return false; 3866 } 3867 synchronized (this) { 3868 ActiveAdmin deviceOwner = getDeviceOwnerAdmin(); 3869 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false; 3870 } 3871 } 3872 3873 /** 3874 * The system property used to share the state of the camera. The native camera service 3875 * is expected to read this property and act accordingly. The userId should be appended 3876 * to this key. 3877 */ 3878 public static final String SYSTEM_PROP_DISABLE_CAMERA_PREFIX = "sys.secpolicy.camera.off_"; 3879 3880 /** 3881 * Disables all device cameras according to the specified admin. 3882 */ 3883 public void setCameraDisabled(ComponentName who, boolean disabled) { 3884 if (!mHasFeature) { 3885 return; 3886 } 3887 Preconditions.checkNotNull(who, "ComponentName is null"); 3888 final int userHandle = UserHandle.getCallingUserId(); 3889 synchronized (this) { 3890 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 3891 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 3892 if (ap.disableCamera != disabled) { 3893 ap.disableCamera = disabled; 3894 saveSettingsLocked(userHandle); 3895 } 3896 syncDeviceCapabilitiesLocked(getUserData(userHandle)); 3897 } 3898 } 3899 3900 /** 3901 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any 3902 * active admins. 3903 */ 3904 public boolean getCameraDisabled(ComponentName who, int userHandle) { 3905 if (!mHasFeature) { 3906 return false; 3907 } 3908 synchronized (this) { 3909 if (who != null) { 3910 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 3911 return (admin != null) ? admin.disableCamera : false; 3912 } 3913 3914 DevicePolicyData policy = getUserData(userHandle); 3915 // Determine whether or not the device camera is disabled for any active admins. 3916 final int N = policy.mAdminList.size(); 3917 for (int i = 0; i < N; i++) { 3918 ActiveAdmin admin = policy.mAdminList.get(i); 3919 if (admin.disableCamera) { 3920 return true; 3921 } 3922 } 3923 return false; 3924 } 3925 } 3926 3927 /** 3928 * Selectively disable keyguard features. 3929 */ 3930 public void setKeyguardDisabledFeatures(ComponentName who, int which) { 3931 if (!mHasFeature) { 3932 return; 3933 } 3934 Preconditions.checkNotNull(who, "ComponentName is null"); 3935 final int userHandle = UserHandle.getCallingUserId(); 3936 enforceNotManagedProfile(userHandle, "disable keyguard features"); 3937 synchronized (this) { 3938 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 3939 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES); 3940 if (ap.disabledKeyguardFeatures != which) { 3941 ap.disabledKeyguardFeatures = which; 3942 saveSettingsLocked(userHandle); 3943 } 3944 syncDeviceCapabilitiesLocked(getUserData(userHandle)); 3945 } 3946 } 3947 3948 /** 3949 * Gets the disabled state for features in keyguard for the given admin, 3950 * or the aggregate of all active admins if who is null. 3951 */ 3952 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle) { 3953 if (!mHasFeature) { 3954 return 0; 3955 } 3956 enforceCrossUserPermission(userHandle); 3957 synchronized (this) { 3958 if (who != null) { 3959 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 3960 return (admin != null) ? admin.disabledKeyguardFeatures : 0; 3961 } 3962 3963 // Determine which keyguard features are disabled for any active admins. 3964 DevicePolicyData policy = getUserData(userHandle); 3965 final int N = policy.mAdminList.size(); 3966 int which = 0; 3967 for (int i = 0; i < N; i++) { 3968 ActiveAdmin admin = policy.mAdminList.get(i); 3969 which |= admin.disabledKeyguardFeatures; 3970 } 3971 return which; 3972 } 3973 } 3974 3975 @Override 3976 public boolean setDeviceOwner(String packageName, String ownerName) { 3977 if (!mHasFeature) { 3978 return false; 3979 } 3980 if (packageName == null 3981 || !DeviceOwner.isInstalled(packageName, mContext.getPackageManager())) { 3982 throw new IllegalArgumentException("Invalid package name " + packageName 3983 + " for device owner"); 3984 } 3985 synchronized (this) { 3986 if (!allowedToSetDeviceOwnerOnDevice()) { 3987 throw new IllegalStateException( 3988 "Trying to set device owner but device is already provisioned."); 3989 } 3990 3991 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) { 3992 throw new IllegalStateException( 3993 "Trying to set device owner but device owner is already set."); 3994 } 3995 3996 // Shutting down backup manager service permanently. 3997 long ident = Binder.clearCallingIdentity(); 3998 try { 3999 IBackupManager ibm = IBackupManager.Stub.asInterface( 4000 ServiceManager.getService(Context.BACKUP_SERVICE)); 4001 ibm.setBackupServiceActive(UserHandle.USER_OWNER, false); 4002 } catch (RemoteException e) { 4003 throw new IllegalStateException("Failed deactivating backup service.", e); 4004 } finally { 4005 Binder.restoreCallingIdentity(ident); 4006 } 4007 4008 if (mDeviceOwner == null) { 4009 // Device owner is not set and does not exist, set it. 4010 mDeviceOwner = DeviceOwner.createWithDeviceOwner(packageName, ownerName); 4011 } else { 4012 // Device owner is not set but a profile owner exists, update Device owner state. 4013 mDeviceOwner.setDeviceOwner(packageName, ownerName); 4014 } 4015 mDeviceOwner.writeOwnerFile(); 4016 updateDeviceOwnerLocked(); 4017 return true; 4018 } 4019 } 4020 4021 @Override 4022 public boolean isDeviceOwner(String packageName) { 4023 if (!mHasFeature) { 4024 return false; 4025 } 4026 synchronized (this) { 4027 return mDeviceOwner != null 4028 && mDeviceOwner.hasDeviceOwner() 4029 && mDeviceOwner.getDeviceOwnerPackageName().equals(packageName); 4030 } 4031 } 4032 4033 @Override 4034 public String getDeviceOwner() { 4035 if (!mHasFeature) { 4036 return null; 4037 } 4038 synchronized (this) { 4039 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) { 4040 return mDeviceOwner.getDeviceOwnerPackageName(); 4041 } 4042 } 4043 return null; 4044 } 4045 4046 @Override 4047 public String getDeviceOwnerName() { 4048 if (!mHasFeature) { 4049 return null; 4050 } 4051 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 4052 synchronized (this) { 4053 if (mDeviceOwner != null) { 4054 return mDeviceOwner.getDeviceOwnerName(); 4055 } 4056 } 4057 return null; 4058 } 4059 4060 // Returns the active device owner or null if there is no device owner. 4061 private ActiveAdmin getDeviceOwnerAdmin() { 4062 String deviceOwnerPackageName = getDeviceOwner(); 4063 if (deviceOwnerPackageName == null) { 4064 return null; 4065 } 4066 4067 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER); 4068 final int n = policy.mAdminList.size(); 4069 for (int i = 0; i < n; i++) { 4070 ActiveAdmin admin = policy.mAdminList.get(i); 4071 if (deviceOwnerPackageName.equals(admin.info.getPackageName())) { 4072 return admin; 4073 } 4074 } 4075 return null; 4076 } 4077 4078 @Override 4079 public void clearDeviceOwner(String packageName) { 4080 Preconditions.checkNotNull(packageName, "packageName is null"); 4081 try { 4082 int uid = mContext.getPackageManager().getPackageUid(packageName, 0); 4083 if (uid != Binder.getCallingUid()) { 4084 throw new SecurityException("Invalid packageName"); 4085 } 4086 } catch (NameNotFoundException e) { 4087 throw new SecurityException(e); 4088 } 4089 if (!isDeviceOwner(packageName)) { 4090 throw new SecurityException("clearDeviceOwner can only be called by the device owner"); 4091 } 4092 synchronized (this) { 4093 long ident = Binder.clearCallingIdentity(); 4094 try { 4095 clearUserRestrictions(new UserHandle(UserHandle.USER_OWNER)); 4096 if (mDeviceOwner != null) { 4097 mDeviceOwner.clearDeviceOwner(); 4098 mDeviceOwner.writeOwnerFile(); 4099 updateDeviceOwnerLocked(); 4100 } 4101 } finally { 4102 Binder.restoreCallingIdentity(ident); 4103 } 4104 } 4105 } 4106 4107 @Override 4108 public boolean setDeviceInitializer(ComponentName who, ComponentName initializer, 4109 String ownerName) { 4110 if (!mHasFeature) { 4111 return false; 4112 } 4113 if (initializer == null || !DeviceOwner.isInstalled( 4114 initializer.getPackageName(), mContext.getPackageManager())) { 4115 throw new IllegalArgumentException("Invalid component name " + initializer 4116 + " for device initializer"); 4117 } 4118 synchronized (this) { 4119 enforceCanSetDeviceInitializer(who); 4120 4121 if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) { 4122 throw new IllegalStateException( 4123 "Trying to set device initializer but device initializer is already set."); 4124 } 4125 4126 if (mDeviceOwner == null) { 4127 // Device owner state does not exist, create it. 4128 mDeviceOwner = DeviceOwner.createWithDeviceInitializer(initializer, ownerName); 4129 } else { 4130 // Device owner already exists, update it. 4131 mDeviceOwner.setDeviceInitializer(initializer, ownerName); 4132 } 4133 4134 addDeviceInitializerToLockTaskPackagesLocked(UserHandle.USER_OWNER); 4135 mDeviceOwner.writeOwnerFile(); 4136 return true; 4137 } 4138 } 4139 4140 private void enforceCanSetDeviceInitializer(ComponentName who) { 4141 if (who == null) { 4142 mContext.enforceCallingOrSelfPermission( 4143 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 4144 if (hasUserSetupCompleted(UserHandle.USER_OWNER)) { 4145 throw new IllegalStateException( 4146 "Trying to set device initializer but device is already provisioned."); 4147 } 4148 } else { 4149 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 4150 } 4151 } 4152 4153 @Override 4154 public boolean isDeviceInitializer(String packageName) { 4155 if (!mHasFeature) { 4156 return false; 4157 } 4158 synchronized (this) { 4159 return mDeviceOwner != null 4160 && mDeviceOwner.hasDeviceInitializer() 4161 && mDeviceOwner.getDeviceInitializerPackageName().equals(packageName); 4162 } 4163 } 4164 4165 @Override 4166 public String getDeviceInitializer() { 4167 if (!mHasFeature) { 4168 return null; 4169 } 4170 synchronized (this) { 4171 if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) { 4172 return mDeviceOwner.getDeviceInitializerPackageName(); 4173 } 4174 } 4175 return null; 4176 } 4177 4178 @Override 4179 public ComponentName getDeviceInitializerComponent() { 4180 if (!mHasFeature) { 4181 return null; 4182 } 4183 synchronized (this) { 4184 if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) { 4185 return mDeviceOwner.getDeviceInitializerComponent(); 4186 } 4187 } 4188 return null; 4189 } 4190 4191 @Override 4192 public void clearDeviceInitializer(ComponentName who) { 4193 if (!mHasFeature) { 4194 return; 4195 } 4196 Preconditions.checkNotNull(who, "ComponentName is null"); 4197 4198 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, UserHandle.getCallingUserId()); 4199 4200 if (admin.getUid() != Binder.getCallingUid()) { 4201 throw new SecurityException("Admin " + who + " is not owned by uid " 4202 + Binder.getCallingUid()); 4203 } 4204 4205 if (!isDeviceInitializer(admin.info.getPackageName()) 4206 && !isDeviceOwner(admin.info.getPackageName())) { 4207 throw new SecurityException( 4208 "clearDeviceInitializer can only be called by the device initializer/owner"); 4209 } 4210 synchronized (this) { 4211 long ident = Binder.clearCallingIdentity(); 4212 try { 4213 if (mDeviceOwner != null) { 4214 mDeviceOwner.clearDeviceInitializer(); 4215 mDeviceOwner.writeOwnerFile(); 4216 } 4217 } finally { 4218 Binder.restoreCallingIdentity(ident); 4219 } 4220 } 4221 } 4222 4223 @Override 4224 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) { 4225 if (!mHasFeature) { 4226 return false; 4227 } 4228 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 4229 4230 UserInfo info = mUserManager.getUserInfo(userHandle); 4231 if (info == null) { 4232 // User doesn't exist. 4233 throw new IllegalArgumentException( 4234 "Attempted to set profile owner for invalid userId: " + userHandle); 4235 } 4236 if (info.isGuest()) { 4237 throw new IllegalStateException("Cannot set a profile owner on a guest"); 4238 } 4239 4240 if (who == null 4241 || !DeviceOwner.isInstalledForUser(who.getPackageName(), userHandle)) { 4242 throw new IllegalArgumentException("Component " + who 4243 + " not installed for userId:" + userHandle); 4244 } 4245 synchronized (this) { 4246 // Only SYSTEM_UID can override the userSetupComplete 4247 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID 4248 && hasUserSetupCompleted(userHandle)) { 4249 throw new IllegalStateException( 4250 "Trying to set profile owner but user is already set-up."); 4251 } 4252 4253 if (mDeviceOwner == null) { 4254 // Device owner state does not exist, create it. 4255 mDeviceOwner = DeviceOwner.createWithProfileOwner(who, ownerName, 4256 userHandle); 4257 mDeviceOwner.writeOwnerFile(); 4258 return true; 4259 } else { 4260 // Device owner already exists, update it. 4261 mDeviceOwner.setProfileOwner(who, ownerName, userHandle); 4262 mDeviceOwner.writeOwnerFile(); 4263 return true; 4264 } 4265 } 4266 } 4267 4268 @Override 4269 public void clearProfileOwner(ComponentName who) { 4270 if (!mHasFeature) { 4271 return; 4272 } 4273 UserHandle callingUser = Binder.getCallingUserHandle(); 4274 // Check if this is the profile owner who is calling 4275 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4276 synchronized (this) { 4277 long ident = Binder.clearCallingIdentity(); 4278 try { 4279 clearUserRestrictions(callingUser); 4280 if (mDeviceOwner != null) { 4281 mDeviceOwner.removeProfileOwner(callingUser.getIdentifier()); 4282 mDeviceOwner.writeOwnerFile(); 4283 } 4284 } finally { 4285 Binder.restoreCallingIdentity(ident); 4286 } 4287 } 4288 } 4289 4290 private void clearUserRestrictions(UserHandle userHandle) { 4291 AudioManager audioManager = 4292 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 4293 Bundle userRestrictions = mUserManager.getUserRestrictions(); 4294 mUserManager.setUserRestrictions(new Bundle(), userHandle); 4295 if (userRestrictions.getBoolean(UserManager.DISALLOW_ADJUST_VOLUME)) { 4296 audioManager.setMasterMute(false, 0); 4297 } 4298 if (userRestrictions.getBoolean(UserManager.DISALLOW_UNMUTE_MICROPHONE)) { 4299 audioManager.setMicrophoneMute(false); 4300 } 4301 } 4302 4303 @Override 4304 public boolean hasUserSetupCompleted() { 4305 return hasUserSetupCompleted(UserHandle.getCallingUserId()); 4306 } 4307 4308 private boolean hasUserSetupCompleted(int userHandle) { 4309 if (!mHasFeature) { 4310 return true; 4311 } 4312 DevicePolicyData policy = getUserData(userHandle); 4313 // If policy is null, return true, else check if the setup has completed. 4314 return policy == null || policy.mUserSetupComplete; 4315 } 4316 4317 @Override 4318 public boolean setUserEnabled(ComponentName who) { 4319 if (!mHasFeature) { 4320 return false; 4321 } 4322 synchronized (this) { 4323 if (who == null) { 4324 throw new NullPointerException("ComponentName is null"); 4325 } 4326 int userId = UserHandle.getCallingUserId(); 4327 4328 ActiveAdmin activeAdmin = 4329 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4330 if (!isDeviceInitializer(activeAdmin.info.getPackageName())) { 4331 throw new SecurityException( 4332 "This method can only be called by device initializers"); 4333 } 4334 4335 long id = Binder.clearCallingIdentity(); 4336 try { 4337 if (!isDeviceOwner(activeAdmin.info.getPackageName())) { 4338 IPackageManager ipm = AppGlobals.getPackageManager(); 4339 ipm.setComponentEnabledSetting(who, 4340 PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 4341 PackageManager.DONT_KILL_APP, userId); 4342 4343 removeActiveAdmin(who, userId); 4344 } 4345 4346 if (userId == UserHandle.USER_OWNER) { 4347 Settings.Global.putInt(mContext.getContentResolver(), 4348 Settings.Global.DEVICE_PROVISIONED, 1); 4349 } 4350 Settings.Secure.putIntForUser(mContext.getContentResolver(), 4351 Settings.Secure.USER_SETUP_COMPLETE, 1, userId); 4352 } catch (RemoteException e) { 4353 Log.i(LOG_TAG, "Can't talk to package manager", e); 4354 return false; 4355 } finally { 4356 restoreCallingIdentity(id); 4357 } 4358 return true; 4359 } 4360 } 4361 4362 @Override 4363 public void setProfileEnabled(ComponentName who) { 4364 if (!mHasFeature) { 4365 return; 4366 } 4367 Preconditions.checkNotNull(who, "ComponentName is null"); 4368 final int userHandle = UserHandle.getCallingUserId(); 4369 synchronized (this) { 4370 // Check if this is the profile owner who is calling 4371 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4372 int userId = UserHandle.getCallingUserId(); 4373 4374 long id = Binder.clearCallingIdentity(); 4375 try { 4376 mUserManager.setUserEnabled(userId); 4377 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 4378 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle)); 4379 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 4380 Intent.FLAG_RECEIVER_FOREGROUND); 4381 // TODO This should send to parent of profile (which is always owner at the moment). 4382 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER); 4383 } finally { 4384 restoreCallingIdentity(id); 4385 } 4386 } 4387 } 4388 4389 @Override 4390 public void setProfileName(ComponentName who, String profileName) { 4391 Preconditions.checkNotNull(who, "ComponentName is null"); 4392 int userId = UserHandle.getCallingUserId(); 4393 // Check if this is the profile owner (includes device owner). 4394 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4395 4396 long id = Binder.clearCallingIdentity(); 4397 try { 4398 mUserManager.setUserName(userId, profileName); 4399 } finally { 4400 restoreCallingIdentity(id); 4401 } 4402 } 4403 4404 @Override 4405 public ComponentName getProfileOwner(int userHandle) { 4406 if (!mHasFeature) { 4407 return null; 4408 } 4409 4410 synchronized (this) { 4411 if (mDeviceOwner != null) { 4412 return mDeviceOwner.getProfileOwnerComponent(userHandle); 4413 } 4414 } 4415 return null; 4416 } 4417 4418 // Returns the active profile owner for this user or null if the current user has no 4419 // profile owner. 4420 private ActiveAdmin getProfileOwnerAdmin(int userHandle) { 4421 ComponentName profileOwner = 4422 mDeviceOwner != null ? mDeviceOwner.getProfileOwnerComponent(userHandle) : null; 4423 if (profileOwner == null) { 4424 return null; 4425 } 4426 4427 DevicePolicyData policy = getUserData(userHandle); 4428 final int n = policy.mAdminList.size(); 4429 for (int i = 0; i < n; i++) { 4430 ActiveAdmin admin = policy.mAdminList.get(i); 4431 if (profileOwner.equals(admin.info.getComponent())) { 4432 return admin; 4433 } 4434 } 4435 return null; 4436 } 4437 4438 @Override 4439 public String getProfileOwnerName(int userHandle) { 4440 if (!mHasFeature) { 4441 return null; 4442 } 4443 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 4444 4445 synchronized (this) { 4446 if (mDeviceOwner != null) { 4447 return mDeviceOwner.getProfileOwnerName(userHandle); 4448 } 4449 } 4450 return null; 4451 } 4452 4453 /** 4454 * Device owner can only be set on an unprovisioned device. However, if initiated via "adb", 4455 * we also allow it if no accounts or additional users are present on the device. 4456 */ 4457 private boolean allowedToSetDeviceOwnerOnDevice() { 4458 if (!hasUserSetupCompleted(UserHandle.USER_OWNER)) { 4459 return true; 4460 } 4461 4462 int callingId = Binder.getCallingUid(); 4463 return (callingId == Process.SHELL_UID || callingId == Process.ROOT_UID) 4464 && mUserManager.getUserCount() == 1 4465 && AccountManager.get(mContext).getAccounts().length == 0; 4466 } 4467 4468 private void enforceCrossUserPermission(int userHandle) { 4469 if (userHandle < 0) { 4470 throw new IllegalArgumentException("Invalid userId " + userHandle); 4471 } 4472 final int callingUid = Binder.getCallingUid(); 4473 if (userHandle == UserHandle.getUserId(callingUid)) return; 4474 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4475 mContext.enforceCallingOrSelfPermission( 4476 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have" 4477 + " INTERACT_ACROSS_USERS_FULL permission"); 4478 } 4479 } 4480 4481 private void enforceSystemProcess(String message) { 4482 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 4483 throw new SecurityException(message); 4484 } 4485 } 4486 4487 private void enforceNotManagedProfile(int userHandle, String message) { 4488 if(isManagedProfile(userHandle)) { 4489 throw new SecurityException("You can not " + message + " for a managed profile. "); 4490 } 4491 } 4492 4493 private UserInfo getProfileParent(int userHandle) { 4494 long ident = Binder.clearCallingIdentity(); 4495 try { 4496 return mUserManager.getProfileParent(userHandle); 4497 } finally { 4498 Binder.restoreCallingIdentity(ident); 4499 } 4500 } 4501 4502 private boolean isManagedProfile(int userHandle) { 4503 long ident = Binder.clearCallingIdentity(); 4504 try { 4505 return mUserManager.getUserInfo(userHandle).isManagedProfile(); 4506 } finally { 4507 Binder.restoreCallingIdentity(ident); 4508 } 4509 } 4510 4511 private void enableIfNecessary(String packageName, int userId) { 4512 try { 4513 IPackageManager ipm = AppGlobals.getPackageManager(); 4514 ApplicationInfo ai = ipm.getApplicationInfo(packageName, 4515 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS, 4516 userId); 4517 if (ai.enabledSetting 4518 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 4519 ipm.setApplicationEnabledSetting(packageName, 4520 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 4521 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 4522 } 4523 } catch (RemoteException e) { 4524 } 4525 } 4526 4527 @Override 4528 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 4529 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 4530 != PackageManager.PERMISSION_GRANTED) { 4531 4532 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid=" 4533 + Binder.getCallingPid() 4534 + ", uid=" + Binder.getCallingUid()); 4535 return; 4536 } 4537 4538 final Printer p = new PrintWriterPrinter(pw); 4539 4540 synchronized (this) { 4541 p.println("Current Device Policy Manager state:"); 4542 if (mDeviceOwner != null) { 4543 mDeviceOwner.dump(" ", pw); 4544 } 4545 int userCount = mUserData.size(); 4546 for (int u = 0; u < userCount; u++) { 4547 DevicePolicyData policy = getUserData(mUserData.keyAt(u)); 4548 p.println(" Enabled Device Admins (User " + policy.mUserHandle + "):"); 4549 final int N = policy.mAdminList.size(); 4550 for (int i=0; i<N; i++) { 4551 ActiveAdmin ap = policy.mAdminList.get(i); 4552 if (ap != null) { 4553 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString()); 4554 pw.println(":"); 4555 ap.dump(" ", pw); 4556 } 4557 } 4558 if (!policy.mRemovingAdmins.isEmpty()) { 4559 p.println(" Removing Device Admins (User " + policy.mUserHandle + "): " 4560 + policy.mRemovingAdmins); 4561 } 4562 4563 pw.println(" "); 4564 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner); 4565 } 4566 } 4567 } 4568 4569 @Override 4570 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 4571 ComponentName activity) { 4572 Preconditions.checkNotNull(who, "ComponentName is null"); 4573 final int userHandle = UserHandle.getCallingUserId(); 4574 synchronized (this) { 4575 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4576 4577 IPackageManager pm = AppGlobals.getPackageManager(); 4578 long id = Binder.clearCallingIdentity(); 4579 try { 4580 pm.addPersistentPreferredActivity(filter, activity, userHandle); 4581 } catch (RemoteException re) { 4582 // Shouldn't happen 4583 } finally { 4584 restoreCallingIdentity(id); 4585 } 4586 } 4587 } 4588 4589 @Override 4590 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 4591 Preconditions.checkNotNull(who, "ComponentName is null"); 4592 final int userHandle = UserHandle.getCallingUserId(); 4593 synchronized (this) { 4594 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4595 4596 IPackageManager pm = AppGlobals.getPackageManager(); 4597 long id = Binder.clearCallingIdentity(); 4598 try { 4599 pm.clearPackagePersistentPreferredActivities(packageName, userHandle); 4600 } catch (RemoteException re) { 4601 // Shouldn't happen 4602 } finally { 4603 restoreCallingIdentity(id); 4604 } 4605 } 4606 } 4607 4608 @Override 4609 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) { 4610 Preconditions.checkNotNull(who, "ComponentName is null"); 4611 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 4612 synchronized (this) { 4613 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4614 4615 long id = Binder.clearCallingIdentity(); 4616 try { 4617 mUserManager.setApplicationRestrictions(packageName, settings, userHandle); 4618 } finally { 4619 restoreCallingIdentity(id); 4620 } 4621 } 4622 } 4623 4624 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent, 4625 PersistableBundle args) { 4626 if (!mHasFeature) { 4627 return; 4628 } 4629 Preconditions.checkNotNull(admin, "admin is null"); 4630 Preconditions.checkNotNull(agent, "agent is null"); 4631 final int userHandle = UserHandle.getCallingUserId(); 4632 enforceNotManagedProfile(userHandle, "set trust agent configuration"); 4633 synchronized (this) { 4634 ActiveAdmin ap = getActiveAdminForCallerLocked(admin, 4635 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES); 4636 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args)); 4637 saveSettingsLocked(userHandle); 4638 syncDeviceCapabilitiesLocked(getUserData(userHandle)); 4639 } 4640 } 4641 4642 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, 4643 ComponentName agent, int userHandle) { 4644 if (!mHasFeature) { 4645 return null; 4646 } 4647 Preconditions.checkNotNull(agent, "agent null"); 4648 enforceCrossUserPermission(userHandle); 4649 4650 synchronized (this) { 4651 final String componentName = agent.flattenToString(); 4652 if (admin != null) { 4653 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle); 4654 if (ap == null) return null; 4655 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName); 4656 if (trustAgentInfo == null || trustAgentInfo.options == null) return null; 4657 List<PersistableBundle> result = new ArrayList<PersistableBundle>(); 4658 result.add(trustAgentInfo.options); 4659 return result; 4660 } 4661 4662 // Return strictest policy for this user and profiles that are visible from this user. 4663 final List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 4664 List<PersistableBundle> result = null; 4665 4666 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track 4667 // of the options. If any admin doesn't have options, discard options for the rest 4668 // and return null. 4669 boolean allAdminsHaveOptions = true; 4670 for (UserInfo userInfo : profiles) { 4671 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 4672 final int N = policy.mAdminList.size(); 4673 for (int i=0; i < N; i++) { 4674 final ActiveAdmin active = policy.mAdminList.get(i); 4675 final boolean disablesTrust = (active.disabledKeyguardFeatures 4676 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 4677 final TrustAgentInfo info = active.trustAgentInfos.get(componentName); 4678 if (info != null && info.options != null && !info.options.isEmpty()) { 4679 if (disablesTrust) { 4680 if (result == null) { 4681 result = new ArrayList<PersistableBundle>(); 4682 } 4683 result.add(info.options); 4684 } else { 4685 Log.w(LOG_TAG, "Ignoring admin " + active.info 4686 + " because it has trust options but doesn't declare " 4687 + "KEYGUARD_DISABLE_TRUST_AGENTS"); 4688 } 4689 } else if (disablesTrust) { 4690 allAdminsHaveOptions = false; 4691 break; 4692 } 4693 } 4694 } 4695 return allAdminsHaveOptions ? result : null; 4696 } 4697 } 4698 4699 @Override 4700 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 4701 Preconditions.checkNotNull(who, "ComponentName is null"); 4702 synchronized (this) { 4703 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4704 4705 int userHandle = UserHandle.getCallingUserId(); 4706 DevicePolicyData userData = getUserData(userHandle); 4707 userData.mRestrictionsProvider = permissionProvider; 4708 saveSettingsLocked(userHandle); 4709 } 4710 } 4711 4712 @Override 4713 public ComponentName getRestrictionsProvider(int userHandle) { 4714 synchronized (this) { 4715 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 4716 throw new SecurityException("Only the system can query the permission provider"); 4717 } 4718 DevicePolicyData userData = getUserData(userHandle); 4719 return userData != null ? userData.mRestrictionsProvider : null; 4720 } 4721 } 4722 4723 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 4724 Preconditions.checkNotNull(who, "ComponentName is null"); 4725 int callingUserId = UserHandle.getCallingUserId(); 4726 synchronized (this) { 4727 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4728 4729 IPackageManager pm = AppGlobals.getPackageManager(); 4730 long id = Binder.clearCallingIdentity(); 4731 try { 4732 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 4733 pm.addCrossProfileIntentFilter(filter, who.getPackageName(), callingUserId, 4734 UserHandle.USER_OWNER, 0); 4735 } 4736 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 4737 pm.addCrossProfileIntentFilter(filter, who.getPackageName(), 4738 UserHandle.USER_OWNER, callingUserId, 0); 4739 } 4740 } catch (RemoteException re) { 4741 // Shouldn't happen 4742 } finally { 4743 restoreCallingIdentity(id); 4744 } 4745 } 4746 } 4747 4748 public void clearCrossProfileIntentFilters(ComponentName who) { 4749 Preconditions.checkNotNull(who, "ComponentName is null"); 4750 int callingUserId = UserHandle.getCallingUserId(); 4751 synchronized (this) { 4752 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4753 IPackageManager pm = AppGlobals.getPackageManager(); 4754 long id = Binder.clearCallingIdentity(); 4755 try { 4756 // Removing those that go from the managed profile to the primary user. 4757 pm.clearCrossProfileIntentFilters(callingUserId, who.getPackageName()); 4758 // And those that go from the primary user to the managed profile. 4759 // If we want to support multiple managed profiles, we will have to only remove 4760 // those that have callingUserId as their target. 4761 pm.clearCrossProfileIntentFilters(UserHandle.USER_OWNER, who.getPackageName()); 4762 } catch (RemoteException re) { 4763 // Shouldn't happen 4764 } finally { 4765 restoreCallingIdentity(id); 4766 } 4767 } 4768 } 4769 4770 /** 4771 * @return true if all packages in enabledPackages are either in the list 4772 * permittedList or are a system app. 4773 */ 4774 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages, 4775 List<String> permittedList) { 4776 int userIdToCheck = UserHandle.getCallingUserId(); 4777 long id = Binder.clearCallingIdentity(); 4778 try { 4779 // If we have an enabled packages list for a managed profile the packages 4780 // we should check are installed for the parent user. 4781 UserInfo user = mUserManager.getUserInfo(userIdToCheck); 4782 if (user.isManagedProfile()) { 4783 userIdToCheck = user.profileGroupId; 4784 } 4785 4786 IPackageManager pm = AppGlobals.getPackageManager(); 4787 for (String enabledPackage : enabledPackages) { 4788 boolean systemService = false; 4789 try { 4790 ApplicationInfo applicationInfo = pm.getApplicationInfo(enabledPackage, 4791 PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck); 4792 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 4793 } catch (RemoteException e) { 4794 Log.i(LOG_TAG, "Can't talk to package managed", e); 4795 } 4796 if (!systemService && !permittedList.contains(enabledPackage)) { 4797 return false; 4798 } 4799 } 4800 } finally { 4801 restoreCallingIdentity(id); 4802 } 4803 return true; 4804 } 4805 4806 private AccessibilityManager getAccessibilityManagerForUser(int userId) { 4807 // Not using AccessibilityManager.getInstance because that guesses 4808 // at the user you require based on callingUid and caches for a given 4809 // process. 4810 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); 4811 IAccessibilityManager service = iBinder == null 4812 ? null : IAccessibilityManager.Stub.asInterface(iBinder); 4813 return new AccessibilityManager(mContext, service, userId); 4814 } 4815 4816 @Override 4817 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) { 4818 if (!mHasFeature) { 4819 return false; 4820 } 4821 Preconditions.checkNotNull(who, "ComponentName is null"); 4822 4823 if (packageList != null) { 4824 int userId = UserHandle.getCallingUserId(); 4825 List<AccessibilityServiceInfo> enabledServices = null; 4826 long id = Binder.clearCallingIdentity(); 4827 try { 4828 UserInfo user = mUserManager.getUserInfo(userId); 4829 if (user.isManagedProfile()) { 4830 userId = user.profileGroupId; 4831 } 4832 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId); 4833 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList( 4834 AccessibilityServiceInfo.FEEDBACK_ALL_MASK); 4835 } finally { 4836 restoreCallingIdentity(id); 4837 } 4838 4839 if (enabledServices != null) { 4840 List<String> enabledPackages = new ArrayList<String>(); 4841 for (AccessibilityServiceInfo service : enabledServices) { 4842 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName); 4843 } 4844 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) { 4845 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, " 4846 + "because it contains already enabled accesibility services."); 4847 return false; 4848 } 4849 } 4850 } 4851 4852 synchronized (this) { 4853 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 4854 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4855 admin.permittedAccessiblityServices = packageList; 4856 saveSettingsLocked(UserHandle.getCallingUserId()); 4857 } 4858 return true; 4859 } 4860 4861 @Override 4862 public List getPermittedAccessibilityServices(ComponentName who) { 4863 if (!mHasFeature) { 4864 return null; 4865 } 4866 Preconditions.checkNotNull(who, "ComponentName is null"); 4867 4868 synchronized (this) { 4869 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 4870 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4871 return admin.permittedAccessiblityServices; 4872 } 4873 } 4874 4875 @Override 4876 public List getPermittedAccessibilityServicesForUser(int userId) { 4877 if (!mHasFeature) { 4878 return null; 4879 } 4880 synchronized (this) { 4881 List<String> result = null; 4882 // If we have multiple profiles we return the intersection of the 4883 // permitted lists. This can happen in cases where we have a device 4884 // and profile owner. 4885 List<UserInfo> profiles = mUserManager.getProfiles(userId); 4886 final int PROFILES_SIZE = profiles.size(); 4887 for (int i = 0; i < PROFILES_SIZE; ++i) { 4888 // Just loop though all admins, only device or profiles 4889 // owners can have permitted lists set. 4890 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id); 4891 final int N = policy.mAdminList.size(); 4892 for (int j = 0; j < N; j++) { 4893 ActiveAdmin admin = policy.mAdminList.get(j); 4894 List<String> fromAdmin = admin.permittedAccessiblityServices; 4895 if (fromAdmin != null) { 4896 if (result == null) { 4897 result = new ArrayList<String>(fromAdmin); 4898 } else { 4899 result.retainAll(fromAdmin); 4900 } 4901 } 4902 } 4903 } 4904 4905 // If we have a permitted list add all system accessibility services. 4906 if (result != null) { 4907 long id = Binder.clearCallingIdentity(); 4908 try { 4909 UserInfo user = mUserManager.getUserInfo(userId); 4910 if (user.isManagedProfile()) { 4911 userId = user.profileGroupId; 4912 } 4913 AccessibilityManager accessibilityManager = 4914 getAccessibilityManagerForUser(userId); 4915 List<AccessibilityServiceInfo> installedServices = 4916 accessibilityManager.getInstalledAccessibilityServiceList(); 4917 4918 IPackageManager pm = AppGlobals.getPackageManager(); 4919 if (installedServices != null) { 4920 for (AccessibilityServiceInfo service : installedServices) { 4921 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo; 4922 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 4923 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 4924 result.add(serviceInfo.packageName); 4925 } 4926 } 4927 } 4928 } finally { 4929 restoreCallingIdentity(id); 4930 } 4931 } 4932 4933 return result; 4934 } 4935 } 4936 4937 private boolean checkCallerIsCurrentUserOrProfile() { 4938 int callingUserId = UserHandle.getCallingUserId(); 4939 long token = Binder.clearCallingIdentity(); 4940 try { 4941 UserInfo currentUser; 4942 UserInfo callingUser = mUserManager.getUserInfo(callingUserId); 4943 try { 4944 currentUser = ActivityManagerNative.getDefault().getCurrentUser(); 4945 } catch (RemoteException e) { 4946 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e); 4947 return false; 4948 } 4949 4950 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) { 4951 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile " 4952 + "of a user that isn't the foreground user."); 4953 return false; 4954 } 4955 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) { 4956 Slog.e(LOG_TAG, "Cannot set permitted input methods " 4957 + "of a user that isn't the foreground user."); 4958 return false; 4959 } 4960 } finally { 4961 Binder.restoreCallingIdentity(token); 4962 } 4963 return true; 4964 } 4965 4966 @Override 4967 public boolean setPermittedInputMethods(ComponentName who, List packageList) { 4968 if (!mHasFeature) { 4969 return false; 4970 } 4971 Preconditions.checkNotNull(who, "ComponentName is null"); 4972 4973 // TODO When InputMethodManager supports per user calls remove 4974 // this restriction. 4975 if (!checkCallerIsCurrentUserOrProfile()) { 4976 return false; 4977 } 4978 4979 if (packageList != null) { 4980 // InputMethodManager fetches input methods for current user. 4981 // So this can only be set when calling user is the current user 4982 // or parent is current user in case of managed profiles. 4983 InputMethodManager inputMethodManager = (InputMethodManager) mContext 4984 .getSystemService(Context.INPUT_METHOD_SERVICE); 4985 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList(); 4986 4987 if (enabledImes != null) { 4988 List<String> enabledPackages = new ArrayList<String>(); 4989 for (InputMethodInfo ime : enabledImes) { 4990 enabledPackages.add(ime.getPackageName()); 4991 } 4992 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) { 4993 Slog.e(LOG_TAG, "Cannot set permitted input methods, " 4994 + "because it contains already enabled input method."); 4995 return false; 4996 } 4997 } 4998 } 4999 5000 synchronized (this) { 5001 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5002 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5003 admin.permittedInputMethods = packageList; 5004 saveSettingsLocked(UserHandle.getCallingUserId()); 5005 } 5006 return true; 5007 } 5008 5009 @Override 5010 public List getPermittedInputMethods(ComponentName who) { 5011 if (!mHasFeature) { 5012 return null; 5013 } 5014 Preconditions.checkNotNull(who, "ComponentName is null"); 5015 5016 synchronized (this) { 5017 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5018 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5019 return admin.permittedInputMethods; 5020 } 5021 } 5022 5023 @Override 5024 public List getPermittedInputMethodsForCurrentUser() { 5025 UserInfo currentUser; 5026 try { 5027 currentUser = ActivityManagerNative.getDefault().getCurrentUser(); 5028 } catch (RemoteException e) { 5029 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e); 5030 // Activity managed is dead, just allow all IMEs 5031 return null; 5032 } 5033 5034 int userId = currentUser.id; 5035 synchronized (this) { 5036 List<String> result = null; 5037 // If we have multiple profiles we return the intersection of the 5038 // permitted lists. This can happen in cases where we have a device 5039 // and profile owner. 5040 List<UserInfo> profiles = mUserManager.getProfiles(userId); 5041 final int PROFILES_SIZE = profiles.size(); 5042 for (int i = 0; i < PROFILES_SIZE; ++i) { 5043 // Just loop though all admins, only device or profiles 5044 // owners can have permitted lists set. 5045 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id); 5046 final int N = policy.mAdminList.size(); 5047 for (int j = 0; j < N; j++) { 5048 ActiveAdmin admin = policy.mAdminList.get(j); 5049 List<String> fromAdmin = admin.permittedInputMethods; 5050 if (fromAdmin != null) { 5051 if (result == null) { 5052 result = new ArrayList<String>(fromAdmin); 5053 } else { 5054 result.retainAll(fromAdmin); 5055 } 5056 } 5057 } 5058 } 5059 5060 // If we have a permitted list add all system input methods. 5061 if (result != null) { 5062 InputMethodManager inputMethodManager = (InputMethodManager) mContext 5063 .getSystemService(Context.INPUT_METHOD_SERVICE); 5064 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList(); 5065 long id = Binder.clearCallingIdentity(); 5066 try { 5067 IPackageManager pm = AppGlobals.getPackageManager(); 5068 if (imes != null) { 5069 for (InputMethodInfo ime : imes) { 5070 ServiceInfo serviceInfo = ime.getServiceInfo(); 5071 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 5072 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 5073 result.add(serviceInfo.packageName); 5074 } 5075 } 5076 } 5077 } finally { 5078 restoreCallingIdentity(id); 5079 } 5080 } 5081 return result; 5082 } 5083 } 5084 5085 @Override 5086 public UserHandle createUser(ComponentName who, String name) { 5087 Preconditions.checkNotNull(who, "ComponentName is null"); 5088 synchronized (this) { 5089 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5090 5091 long id = Binder.clearCallingIdentity(); 5092 try { 5093 UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */); 5094 if (userInfo != null) { 5095 return userInfo.getUserHandle(); 5096 } 5097 return null; 5098 } finally { 5099 restoreCallingIdentity(id); 5100 } 5101 } 5102 } 5103 5104 @Override 5105 public UserHandle createAndInitializeUser(ComponentName who, String name, 5106 String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) { 5107 UserHandle user = createUser(who, name); 5108 if (user == null) { 5109 return null; 5110 } 5111 long id = Binder.clearCallingIdentity(); 5112 try { 5113 String profileOwnerPkg = profileOwnerComponent.getPackageName(); 5114 final IPackageManager ipm = AppGlobals.getPackageManager(); 5115 IActivityManager activityManager = ActivityManagerNative.getDefault(); 5116 5117 final int userHandle = user.getIdentifier(); 5118 try { 5119 // Install the profile owner if not present. 5120 if (!ipm.isPackageAvailable(profileOwnerPkg, userHandle)) { 5121 ipm.installExistingPackageAsUser(profileOwnerPkg, userHandle); 5122 } 5123 5124 // Start user in background. 5125 activityManager.startUserInBackground(userHandle); 5126 } catch (RemoteException e) { 5127 Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e); 5128 } 5129 5130 setActiveAdmin(profileOwnerComponent, true, userHandle, adminExtras); 5131 setProfileOwner(profileOwnerComponent, ownerName, userHandle); 5132 return user; 5133 } finally { 5134 restoreCallingIdentity(id); 5135 } 5136 } 5137 5138 @Override 5139 public boolean removeUser(ComponentName who, UserHandle userHandle) { 5140 Preconditions.checkNotNull(who, "ComponentName is null"); 5141 synchronized (this) { 5142 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5143 5144 long id = Binder.clearCallingIdentity(); 5145 try { 5146 return mUserManager.removeUser(userHandle.getIdentifier()); 5147 } finally { 5148 restoreCallingIdentity(id); 5149 } 5150 } 5151 } 5152 5153 @Override 5154 public boolean switchUser(ComponentName who, UserHandle userHandle) { 5155 Preconditions.checkNotNull(who, "ComponentName is null"); 5156 synchronized (this) { 5157 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5158 5159 long id = Binder.clearCallingIdentity(); 5160 try { 5161 int userId = UserHandle.USER_OWNER; 5162 if (userHandle != null) { 5163 userId = userHandle.getIdentifier(); 5164 } 5165 return ActivityManagerNative.getDefault().switchUser(userId); 5166 } catch (RemoteException e) { 5167 Log.e(LOG_TAG, "Couldn't switch user", e); 5168 return false; 5169 } finally { 5170 restoreCallingIdentity(id); 5171 } 5172 } 5173 } 5174 5175 @Override 5176 public Bundle getApplicationRestrictions(ComponentName who, String packageName) { 5177 Preconditions.checkNotNull(who, "ComponentName is null"); 5178 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 5179 5180 synchronized (this) { 5181 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5182 5183 long id = Binder.clearCallingIdentity(); 5184 try { 5185 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle); 5186 // if no restrictions were saved, mUserManager.getApplicationRestrictions 5187 // returns null, but DPM method should return an empty Bundle as per JavaDoc 5188 return bundle != null ? bundle : Bundle.EMPTY; 5189 } finally { 5190 restoreCallingIdentity(id); 5191 } 5192 } 5193 } 5194 5195 @Override 5196 public void setUserRestriction(ComponentName who, String key, boolean enabled) { 5197 Preconditions.checkNotNull(who, "ComponentName is null"); 5198 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 5199 final int userHandle = user.getIdentifier(); 5200 synchronized (this) { 5201 ActiveAdmin activeAdmin = 5202 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5203 boolean isDeviceOwner = isDeviceOwner(activeAdmin.info.getPackageName()); 5204 if (!isDeviceOwner && userHandle != UserHandle.USER_OWNER 5205 && DEVICE_OWNER_USER_RESTRICTIONS.contains(key)) { 5206 throw new SecurityException("Profile owners cannot set user restriction " + key); 5207 } 5208 if (IMMUTABLE_USER_RESTRICTIONS.contains(key)) { 5209 throw new SecurityException("User restriction " + key + " cannot be changed"); 5210 } 5211 boolean alreadyRestricted = mUserManager.hasUserRestriction(key, user); 5212 5213 IAudioService iAudioService = null; 5214 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key) 5215 || UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) { 5216 iAudioService = IAudioService.Stub.asInterface( 5217 ServiceManager.getService(Context.AUDIO_SERVICE)); 5218 } 5219 5220 if (enabled && !alreadyRestricted) { 5221 try { 5222 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) { 5223 iAudioService.setMicrophoneMute(true, who.getPackageName()); 5224 } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) { 5225 iAudioService.setMasterMute(true, 0, who.getPackageName()); 5226 } 5227 } catch (RemoteException re) { 5228 Slog.e(LOG_TAG, "Failed to talk to AudioService.", re); 5229 } 5230 } 5231 long id = Binder.clearCallingIdentity(); 5232 try { 5233 if (enabled && !alreadyRestricted) { 5234 if (UserManager.DISALLOW_CONFIG_WIFI.equals(key)) { 5235 Settings.Secure.putIntForUser(mContext.getContentResolver(), 5236 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0, 5237 userHandle); 5238 } else if (UserManager.DISALLOW_USB_FILE_TRANSFER.equals(key)) { 5239 UsbManager manager = 5240 (UsbManager) mContext.getSystemService(Context.USB_SERVICE); 5241 manager.setCurrentFunction("none", false); 5242 } else if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) { 5243 Settings.Secure.putIntForUser(mContext.getContentResolver(), 5244 Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF, 5245 userHandle); 5246 Settings.Secure.putStringForUser(mContext.getContentResolver(), 5247 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, "", 5248 userHandle); 5249 } else if (UserManager.DISALLOW_DEBUGGING_FEATURES.equals(key)) { 5250 // Only disable adb if changing for primary user, since it is global 5251 if (userHandle == UserHandle.USER_OWNER) { 5252 Settings.Global.putStringForUser(mContext.getContentResolver(), 5253 Settings.Global.ADB_ENABLED, "0", userHandle); 5254 } 5255 } else if (UserManager.ENSURE_VERIFY_APPS.equals(key)) { 5256 Settings.Global.putStringForUser(mContext.getContentResolver(), 5257 Settings.Global.PACKAGE_VERIFIER_ENABLE, "1", 5258 userHandle); 5259 Settings.Global.putStringForUser(mContext.getContentResolver(), 5260 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1", 5261 userHandle); 5262 } else if (UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES.equals(key)) { 5263 Settings.Secure.putIntForUser(mContext.getContentResolver(), 5264 Settings.Secure.INSTALL_NON_MARKET_APPS, 0, 5265 userHandle); 5266 } 5267 } 5268 mUserManager.setUserRestriction(key, enabled, user); 5269 if (enabled != alreadyRestricted) { 5270 if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) { 5271 // Send out notifications however as some clients may want to reread the 5272 // value which actually changed due to a restriction having been applied. 5273 final String property = Settings.Secure.SYS_PROP_SETTING_VERSION; 5274 long version = SystemProperties.getLong(property, 0) + 1; 5275 SystemProperties.set(property, Long.toString(version)); 5276 5277 final String name = Settings.Secure.LOCATION_PROVIDERS_ALLOWED; 5278 Uri url = Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name); 5279 mContext.getContentResolver().notifyChange(url, null, true, userHandle); 5280 } 5281 } 5282 } finally { 5283 restoreCallingIdentity(id); 5284 } 5285 if (!enabled && alreadyRestricted) { 5286 try { 5287 if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) { 5288 iAudioService.setMicrophoneMute(false, who.getPackageName()); 5289 } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) { 5290 iAudioService.setMasterMute(false, 0, who.getPackageName()); 5291 } 5292 } catch (RemoteException re) { 5293 Slog.e(LOG_TAG, "Failed to talk to AudioService.", re); 5294 } 5295 } 5296 sendChangedNotification(userHandle); 5297 } 5298 } 5299 5300 @Override 5301 public boolean setApplicationHidden(ComponentName who, String packageName, 5302 boolean hidden) { 5303 Preconditions.checkNotNull(who, "ComponentName is null"); 5304 int callingUserId = UserHandle.getCallingUserId(); 5305 synchronized (this) { 5306 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5307 5308 long id = Binder.clearCallingIdentity(); 5309 try { 5310 IPackageManager pm = AppGlobals.getPackageManager(); 5311 return pm.setApplicationHiddenSettingAsUser(packageName, hidden, callingUserId); 5312 } catch (RemoteException re) { 5313 // shouldn't happen 5314 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re); 5315 } finally { 5316 restoreCallingIdentity(id); 5317 } 5318 return false; 5319 } 5320 } 5321 5322 @Override 5323 public boolean isApplicationHidden(ComponentName who, String packageName) { 5324 Preconditions.checkNotNull(who, "ComponentName is null"); 5325 int callingUserId = UserHandle.getCallingUserId(); 5326 synchronized (this) { 5327 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5328 5329 long id = Binder.clearCallingIdentity(); 5330 try { 5331 IPackageManager pm = AppGlobals.getPackageManager(); 5332 return pm.getApplicationHiddenSettingAsUser(packageName, callingUserId); 5333 } catch (RemoteException re) { 5334 // shouldn't happen 5335 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re); 5336 } finally { 5337 restoreCallingIdentity(id); 5338 } 5339 return false; 5340 } 5341 } 5342 5343 @Override 5344 public void enableSystemApp(ComponentName who, String packageName) { 5345 Preconditions.checkNotNull(who, "ComponentName is null"); 5346 synchronized (this) { 5347 // This API can only be called by an active device admin, 5348 // so try to retrieve it to check that the caller is one. 5349 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5350 5351 int userId = UserHandle.getCallingUserId(); 5352 long id = Binder.clearCallingIdentity(); 5353 5354 try { 5355 if (DBG) { 5356 Slog.v(LOG_TAG, "installing " + packageName + " for " 5357 + userId); 5358 } 5359 5360 UserManager um = UserManager.get(mContext); 5361 UserInfo primaryUser = um.getProfileParent(userId); 5362 5363 // Call did not come from a managed profile 5364 if (primaryUser == null) { 5365 primaryUser = um.getUserInfo(userId); 5366 } 5367 5368 IPackageManager pm = AppGlobals.getPackageManager(); 5369 if (!isSystemApp(pm, packageName, primaryUser.id)) { 5370 throw new IllegalArgumentException("Only system apps can be enabled this way."); 5371 } 5372 5373 // Install the app. 5374 pm.installExistingPackageAsUser(packageName, userId); 5375 5376 } catch (RemoteException re) { 5377 // shouldn't happen 5378 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re); 5379 } finally { 5380 restoreCallingIdentity(id); 5381 } 5382 } 5383 } 5384 5385 @Override 5386 public int enableSystemAppWithIntent(ComponentName who, Intent intent) { 5387 Preconditions.checkNotNull(who, "ComponentName is null"); 5388 synchronized (this) { 5389 // This API can only be called by an active device admin, 5390 // so try to retrieve it to check that the caller is one. 5391 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5392 5393 int userId = UserHandle.getCallingUserId(); 5394 long id = Binder.clearCallingIdentity(); 5395 5396 try { 5397 UserManager um = UserManager.get(mContext); 5398 UserInfo primaryUser = um.getProfileParent(userId); 5399 5400 // Call did not come from a managed profile. 5401 if (primaryUser == null) { 5402 primaryUser = um.getUserInfo(userId); 5403 } 5404 5405 IPackageManager pm = AppGlobals.getPackageManager(); 5406 List<ResolveInfo> activitiesToEnable = pm.queryIntentActivities(intent, 5407 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 5408 0, // no flags 5409 primaryUser.id); 5410 5411 if (DBG) Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable); 5412 int numberOfAppsInstalled = 0; 5413 if (activitiesToEnable != null) { 5414 for (ResolveInfo info : activitiesToEnable) { 5415 if (info.activityInfo != null) { 5416 String packageName = info.activityInfo.packageName; 5417 if (isSystemApp(pm, packageName, primaryUser.id)) { 5418 numberOfAppsInstalled++; 5419 pm.installExistingPackageAsUser(packageName, userId); 5420 } else { 5421 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a" 5422 + " system app"); 5423 } 5424 } 5425 } 5426 } 5427 return numberOfAppsInstalled; 5428 } catch (RemoteException e) { 5429 // shouldn't happen 5430 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent); 5431 return 0; 5432 } finally { 5433 restoreCallingIdentity(id); 5434 } 5435 } 5436 } 5437 5438 private boolean isSystemApp(IPackageManager pm, String packageName, int userId) 5439 throws RemoteException { 5440 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES, 5441 userId); 5442 if (appInfo == null) { 5443 throw new IllegalArgumentException("The application " + packageName + 5444 " is not present on this device"); 5445 } 5446 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 5447 } 5448 5449 @Override 5450 public void setAccountManagementDisabled(ComponentName who, String accountType, 5451 boolean disabled) { 5452 if (!mHasFeature) { 5453 return; 5454 } 5455 Preconditions.checkNotNull(who, "ComponentName is null"); 5456 synchronized (this) { 5457 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5458 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5459 if (disabled) { 5460 ap.accountTypesWithManagementDisabled.add(accountType); 5461 } else { 5462 ap.accountTypesWithManagementDisabled.remove(accountType); 5463 } 5464 saveSettingsLocked(UserHandle.getCallingUserId()); 5465 } 5466 } 5467 5468 @Override 5469 public String[] getAccountTypesWithManagementDisabled() { 5470 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId()); 5471 } 5472 5473 @Override 5474 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) { 5475 enforceCrossUserPermission(userId); 5476 if (!mHasFeature) { 5477 return null; 5478 } 5479 synchronized (this) { 5480 DevicePolicyData policy = getUserData(userId); 5481 final int N = policy.mAdminList.size(); 5482 HashSet<String> resultSet = new HashSet<String>(); 5483 for (int i = 0; i < N; i++) { 5484 ActiveAdmin admin = policy.mAdminList.get(i); 5485 resultSet.addAll(admin.accountTypesWithManagementDisabled); 5486 } 5487 return resultSet.toArray(new String[resultSet.size()]); 5488 } 5489 } 5490 5491 @Override 5492 public void setUninstallBlocked(ComponentName who, String packageName, 5493 boolean uninstallBlocked) { 5494 Preconditions.checkNotNull(who, "ComponentName is null"); 5495 final int userId = UserHandle.getCallingUserId(); 5496 synchronized (this) { 5497 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5498 5499 long id = Binder.clearCallingIdentity(); 5500 try { 5501 IPackageManager pm = AppGlobals.getPackageManager(); 5502 pm.setBlockUninstallForUser(packageName, uninstallBlocked, userId); 5503 } catch (RemoteException re) { 5504 // Shouldn't happen. 5505 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 5506 } finally { 5507 restoreCallingIdentity(id); 5508 } 5509 } 5510 } 5511 5512 @Override 5513 public boolean isUninstallBlocked(ComponentName who, String packageName) { 5514 // This function should return true if and only if the package is blocked by 5515 // setUninstallBlocked(). It should still return false for other cases of blocks, such as 5516 // when the package is a system app, or when it is an active device admin. 5517 final int userId = UserHandle.getCallingUserId(); 5518 5519 synchronized (this) { 5520 if (who != null) { 5521 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5522 } 5523 5524 long id = Binder.clearCallingIdentity(); 5525 try { 5526 IPackageManager pm = AppGlobals.getPackageManager(); 5527 return pm.getBlockUninstallForUser(packageName, userId); 5528 } catch (RemoteException re) { 5529 // Shouldn't happen. 5530 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 5531 } finally { 5532 restoreCallingIdentity(id); 5533 } 5534 } 5535 return false; 5536 } 5537 5538 @Override 5539 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { 5540 if (!mHasFeature) { 5541 return; 5542 } 5543 Preconditions.checkNotNull(who, "ComponentName is null"); 5544 synchronized (this) { 5545 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5546 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5547 if (admin.disableCallerId != disabled) { 5548 admin.disableCallerId = disabled; 5549 saveSettingsLocked(UserHandle.getCallingUserId()); 5550 } 5551 } 5552 } 5553 5554 @Override 5555 public boolean getCrossProfileCallerIdDisabled(ComponentName who) { 5556 if (!mHasFeature) { 5557 return false; 5558 } 5559 Preconditions.checkNotNull(who, "ComponentName is null"); 5560 synchronized (this) { 5561 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5562 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5563 return admin.disableCallerId; 5564 } 5565 } 5566 5567 @Override 5568 public boolean getCrossProfileCallerIdDisabledForUser(int userId) { 5569 // TODO: Should there be a check to make sure this relationship is within a profile group? 5570 //enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 5571 synchronized (this) { 5572 ActiveAdmin admin = getProfileOwnerAdmin(userId); 5573 return (admin != null) ? admin.disableCallerId : false; 5574 } 5575 } 5576 5577 @Override 5578 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 5579 Intent originalIntent) { 5580 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent( 5581 actualLookupKey, actualContactId, originalIntent); 5582 final int callingUserId = UserHandle.getCallingUserId(); 5583 5584 final long ident = Binder.clearCallingIdentity(); 5585 try { 5586 synchronized (this) { 5587 final int managedUserId = getManagedUserId(callingUserId); 5588 if (managedUserId < 0) { 5589 return; 5590 } 5591 if (getCrossProfileCallerIdDisabledForUser(managedUserId)) { 5592 if (VERBOSE_LOG) { 5593 Log.v(LOG_TAG, 5594 "Cross-profile contacts access disabled for user " + managedUserId); 5595 } 5596 return; 5597 } 5598 ContactsInternal.startQuickContactWithErrorToastForUser( 5599 mContext, intent, new UserHandle(managedUserId)); 5600 } 5601 } finally { 5602 Binder.restoreCallingIdentity(ident); 5603 } 5604 } 5605 5606 /** 5607 * @return the user ID of the managed user that is linked to the current user, if any. 5608 * Otherwise -1. 5609 */ 5610 public int getManagedUserId(int callingUserId) { 5611 if (VERBOSE_LOG) { 5612 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId); 5613 } 5614 5615 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) { 5616 if (ui.id == callingUserId || !ui.isManagedProfile()) { 5617 continue; // Caller user self, or not a managed profile. Skip. 5618 } 5619 if (VERBOSE_LOG) { 5620 Log.v(LOG_TAG, "Managed user=" + ui.id); 5621 } 5622 return ui.id; 5623 } 5624 if (VERBOSE_LOG) { 5625 Log.v(LOG_TAG, "Managed user not found."); 5626 } 5627 return -1; 5628 } 5629 5630 @Override 5631 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { 5632 if (!mHasFeature) { 5633 return; 5634 } 5635 Preconditions.checkNotNull(who, "ComponentName is null"); 5636 synchronized (this) { 5637 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5638 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5639 if (admin.disableBluetoothContactSharing != disabled) { 5640 admin.disableBluetoothContactSharing = disabled; 5641 saveSettingsLocked(UserHandle.getCallingUserId()); 5642 } 5643 } 5644 } 5645 5646 @Override 5647 public boolean getBluetoothContactSharingDisabled(ComponentName who) { 5648 if (!mHasFeature) { 5649 return false; 5650 } 5651 Preconditions.checkNotNull(who, "ComponentName is null"); 5652 synchronized (this) { 5653 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5654 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5655 return admin.disableBluetoothContactSharing; 5656 } 5657 } 5658 5659 @Override 5660 public boolean getBluetoothContactSharingDisabledForUser(int userId) { 5661 // TODO: Should there be a check to make sure this relationship is 5662 // within a profile group? 5663 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 5664 synchronized (this) { 5665 ActiveAdmin admin = getProfileOwnerAdmin(userId); 5666 return (admin != null) ? admin.disableBluetoothContactSharing : false; 5667 } 5668 } 5669 5670 /** 5671 * Sets which packages may enter lock task mode. 5672 * 5673 * This function can only be called by the device owner. 5674 * @param packages The list of packages allowed to enter lock task mode. 5675 */ 5676 public void setLockTaskPackages(ComponentName who, String[] packages) 5677 throws SecurityException { 5678 Preconditions.checkNotNull(who, "ComponentName is null"); 5679 synchronized (this) { 5680 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5681 5682 int userHandle = Binder.getCallingUserHandle().getIdentifier(); 5683 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages))); 5684 } 5685 } 5686 5687 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) { 5688 DevicePolicyData policy = getUserData(userHandle); 5689 policy.mLockTaskPackages = packages; 5690 5691 // Store the settings persistently. 5692 saveSettingsLocked(userHandle); 5693 updateLockTaskPackagesLocked(packages, userHandle); 5694 } 5695 5696 /** 5697 * This function returns the list of components allowed to start the task lock mode. 5698 */ 5699 public String[] getLockTaskPackages(ComponentName who) { 5700 Preconditions.checkNotNull(who, "ComponentName is null"); 5701 synchronized (this) { 5702 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5703 int userHandle = Binder.getCallingUserHandle().getIdentifier(); 5704 final List<String> packages = getLockTaskPackagesLocked(userHandle); 5705 return packages.toArray(new String[packages.size()]); 5706 } 5707 } 5708 5709 private List<String> getLockTaskPackagesLocked(int userHandle) { 5710 final DevicePolicyData policy = getUserData(userHandle); 5711 return policy.mLockTaskPackages; 5712 } 5713 5714 /** 5715 * This function lets the caller know whether the given package is allowed to start the 5716 * lock task mode. 5717 * @param pkg The package to check 5718 */ 5719 public boolean isLockTaskPermitted(String pkg) { 5720 // Get current user's devicepolicy 5721 int uid = Binder.getCallingUid(); 5722 int userHandle = UserHandle.getUserId(uid); 5723 DevicePolicyData policy = getUserData(userHandle); 5724 synchronized (this) { 5725 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) { 5726 String lockTaskPackage = policy.mLockTaskPackages.get(i); 5727 5728 // If the given package equals one of the packages stored our list, 5729 // we allow this package to start lock task mode. 5730 if (lockTaskPackage.equals(pkg)) { 5731 return true; 5732 } 5733 } 5734 } 5735 return false; 5736 } 5737 5738 @Override 5739 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 5740 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 5741 throw new SecurityException("notifyLockTaskModeChanged can only be called by system"); 5742 } 5743 synchronized (this) { 5744 final DevicePolicyData policy = getUserData(userHandle); 5745 Bundle adminExtras = new Bundle(); 5746 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 5747 for (ActiveAdmin admin : policy.mAdminList) { 5748 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName()); 5749 boolean ownsProfile = (getProfileOwner(userHandle) != null 5750 && getProfileOwner(userHandle).equals(admin.info.getPackageName())); 5751 if (ownsDevice || ownsProfile) { 5752 if (isEnabled) { 5753 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING, 5754 adminExtras, null); 5755 } else { 5756 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING); 5757 } 5758 } 5759 } 5760 } 5761 } 5762 5763 @Override 5764 public void setGlobalSetting(ComponentName who, String setting, String value) { 5765 final ContentResolver contentResolver = mContext.getContentResolver(); 5766 Preconditions.checkNotNull(who, "ComponentName is null"); 5767 5768 synchronized (this) { 5769 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5770 5771 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) { 5772 // BLUETOOTH_ON and WIFI_ON used to be supported but not any more. We do not want to 5773 // throw a SecurityException not to break apps. 5774 if (!Settings.Global.BLUETOOTH_ON.equals(setting) 5775 && !Settings.Global.WIFI_ON.equals(setting)) { 5776 throw new SecurityException(String.format( 5777 "Permission denial: device owners cannot update %1$s", setting)); 5778 } 5779 } 5780 5781 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) { 5782 // ignore if it contradicts an existing policy 5783 long timeMs = getMaximumTimeToLock(who, UserHandle.getCallingUserId()); 5784 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) { 5785 return; 5786 } 5787 } 5788 5789 long id = Binder.clearCallingIdentity(); 5790 try { 5791 Settings.Global.putString(contentResolver, setting, value); 5792 } finally { 5793 restoreCallingIdentity(id); 5794 } 5795 } 5796 } 5797 5798 @Override 5799 public void setSecureSetting(ComponentName who, String setting, String value) { 5800 Preconditions.checkNotNull(who, "ComponentName is null"); 5801 int callingUserId = UserHandle.getCallingUserId(); 5802 final ContentResolver contentResolver = mContext.getContentResolver(); 5803 5804 synchronized (this) { 5805 ActiveAdmin activeAdmin = 5806 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5807 5808 if (isDeviceOwner(activeAdmin.info.getPackageName())) { 5809 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) { 5810 throw new SecurityException(String.format( 5811 "Permission denial: Device owners cannot update %1$s", setting)); 5812 } 5813 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) { 5814 throw new SecurityException(String.format( 5815 "Permission denial: Profile owners cannot update %1$s", setting)); 5816 } 5817 5818 long id = Binder.clearCallingIdentity(); 5819 try { 5820 Settings.Secure.putStringForUser(contentResolver, setting, value, callingUserId); 5821 } finally { 5822 restoreCallingIdentity(id); 5823 } 5824 } 5825 } 5826 5827 @Override 5828 public void setMasterVolumeMuted(ComponentName who, boolean on) { 5829 Preconditions.checkNotNull(who, "ComponentName is null"); 5830 synchronized (this) { 5831 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5832 5833 IAudioService iAudioService = IAudioService.Stub.asInterface( 5834 ServiceManager.getService(Context.AUDIO_SERVICE)); 5835 try { 5836 iAudioService.setMasterMute(on, 0, who.getPackageName()); 5837 } catch (RemoteException re) { 5838 Slog.e(LOG_TAG, "Failed to setMasterMute", re); 5839 } 5840 } 5841 } 5842 5843 @Override 5844 public boolean isMasterVolumeMuted(ComponentName who) { 5845 Preconditions.checkNotNull(who, "ComponentName is null"); 5846 synchronized (this) { 5847 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5848 5849 AudioManager audioManager = 5850 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 5851 return audioManager.isMasterMute(); 5852 } 5853 } 5854 5855 @Override 5856 public void setUserIcon(ComponentName who, Bitmap icon) { 5857 synchronized (this) { 5858 Preconditions.checkNotNull(who, "ComponentName is null"); 5859 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5860 5861 int userId = UserHandle.getCallingUserId(); 5862 long id = Binder.clearCallingIdentity(); 5863 try { 5864 mUserManager.setUserIcon(userId, icon); 5865 } finally { 5866 restoreCallingIdentity(id); 5867 } 5868 } 5869 } 5870 5871 @Override 5872 public void sendDeviceInitializerStatus(int statusCode, String description) { 5873 synchronized (this) { 5874 String packageName = getDeviceInitializer(); 5875 if (packageName == null) { 5876 throw new SecurityException("No device initializers"); 5877 } 5878 UserHandle callingUser = Binder.getCallingUserHandle(); 5879 int deviceInitializerUid = -1; 5880 try { 5881 deviceInitializerUid = mContext.getPackageManager().getPackageUid( 5882 packageName, callingUser.getIdentifier()); 5883 } catch (NameNotFoundException e) { 5884 throw new SecurityException(e); 5885 } 5886 if (Binder.getCallingUid() != deviceInitializerUid) { 5887 throw new SecurityException("Caller must be a device initializer"); 5888 } 5889 long id = Binder.clearCallingIdentity(); 5890 try { 5891 Intent intent = new Intent( 5892 DevicePolicyManager.ACTION_SEND_DEVICE_INITIALIZER_STATUS); 5893 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_INITIALIZER_STATUS_CODE, 5894 statusCode); 5895 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_INITIALIZER_STATUS_DESCRIPTION, 5896 description); 5897 mContext.sendBroadcastAsUser(intent, callingUser, 5898 android.Manifest.permission.RECEIVE_DEVICE_INITIALIZER_STATUS); 5899 } finally { 5900 restoreCallingIdentity(id); 5901 } 5902 } 5903 } 5904 5905 @Override 5906 public boolean setKeyguardEnabledState(ComponentName who, boolean enabled) { 5907 Preconditions.checkNotNull(who, "ComponentName is null"); 5908 synchronized (this) { 5909 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5910 } 5911 final int userId = UserHandle.getCallingUserId(); 5912 LockPatternUtils utils = new LockPatternUtils(mContext); 5913 5914 long ident = Binder.clearCallingIdentity(); 5915 try { 5916 // disallow disabling the keyguard if a password is currently set 5917 if (!enabled && utils.isSecure(userId)) { 5918 return false; 5919 } 5920 utils.setLockScreenDisabled(!enabled, userId); 5921 } finally { 5922 Binder.restoreCallingIdentity(ident); 5923 } 5924 return true; 5925 } 5926 5927 @Override 5928 public void setStatusBarEnabledState(ComponentName who, boolean enabled) { 5929 int userId = UserHandle.getCallingUserId(); 5930 synchronized (this) { 5931 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5932 DevicePolicyData policy = getUserData(userId); 5933 if (policy.mStatusBarEnabledState != enabled) { 5934 policy.mStatusBarEnabledState = enabled; 5935 setStatusBarEnabledStateInternal(enabled, userId); 5936 saveSettingsLocked(userId); 5937 } 5938 } 5939 } 5940 5941 private void setStatusBarEnabledStateInternal(boolean enabled, int userId) { 5942 long ident = Binder.clearCallingIdentity(); 5943 try { 5944 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 5945 ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); 5946 if (statusBarService != null) { 5947 int flags = enabled ? StatusBarManager.DISABLE_NONE : STATUS_BAR_DISABLE_MASK; 5948 statusBarService.disableForUser(flags, mToken, mContext.getPackageName(), userId); 5949 } 5950 } catch (RemoteException e) { 5951 Slog.e(LOG_TAG, "Failed to disable the status bar", e); 5952 } finally { 5953 Binder.restoreCallingIdentity(ident); 5954 } 5955 } 5956 5957 /** 5958 * We need to update the internal state of whether a user has completed setup once. After 5959 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes 5960 * as we don't trust any apps that might try to reset it. 5961 * <p> 5962 * Unfortunately, we don't know which user's setup state was changed, so we write all of 5963 * them. 5964 */ 5965 void updateUserSetupComplete() { 5966 List<UserInfo> users = mUserManager.getUsers(true); 5967 ContentResolver resolver = mContext.getContentResolver(); 5968 final int N = users.size(); 5969 for (int i = 0; i < N; i++) { 5970 int userHandle = users.get(i).id; 5971 if (Settings.Secure.getIntForUser(resolver, Settings.Secure.USER_SETUP_COMPLETE, 0, 5972 userHandle) != 0) { 5973 DevicePolicyData policy = getUserData(userHandle); 5974 if (!policy.mUserSetupComplete) { 5975 policy.mUserSetupComplete = true; 5976 synchronized (this) { 5977 // The DeviceInitializer was whitelisted but now should be removed. 5978 removeDeviceInitializerFromLockTaskPackages(userHandle); 5979 saveSettingsLocked(userHandle); 5980 } 5981 } 5982 } 5983 } 5984 } 5985 5986 private void addDeviceInitializerToLockTaskPackagesLocked(int userHandle) { 5987 if (hasUserSetupCompleted(userHandle)) { 5988 return; 5989 } 5990 5991 final String deviceInitializerPackage = getDeviceInitializer(); 5992 if (deviceInitializerPackage == null) { 5993 return; 5994 } 5995 5996 final List<String> packages = getLockTaskPackagesLocked(userHandle); 5997 if (!packages.contains(deviceInitializerPackage)) { 5998 packages.add(deviceInitializerPackage); 5999 setLockTaskPackagesLocked(userHandle, packages); 6000 } 6001 } 6002 6003 private void removeDeviceInitializerFromLockTaskPackages(int userHandle) { 6004 final String deviceInitializerPackage = getDeviceInitializer(); 6005 if (deviceInitializerPackage == null) { 6006 return; 6007 } 6008 6009 List<String> packages = getLockTaskPackagesLocked(userHandle); 6010 if (packages.remove(deviceInitializerPackage)) { 6011 setLockTaskPackagesLocked(userHandle, packages); 6012 } 6013 } 6014 6015 private class SetupContentObserver extends ContentObserver { 6016 6017 private final Uri mUserSetupComplete = Settings.Secure.getUriFor( 6018 Settings.Secure.USER_SETUP_COMPLETE); 6019 6020 public SetupContentObserver(Handler handler) { 6021 super(handler); 6022 } 6023 6024 void register(ContentResolver resolver) { 6025 resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL); 6026 } 6027 6028 @Override 6029 public void onChange(boolean selfChange, Uri uri) { 6030 if (mUserSetupComplete.equals(uri)) { 6031 updateUserSetupComplete(); 6032 } 6033 } 6034 } 6035 6036 private final class LocalService extends DevicePolicyManagerInternal { 6037 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners; 6038 6039 @Override 6040 public List<String> getCrossProfileWidgetProviders(int profileId) { 6041 synchronized (DevicePolicyManagerService.this) { 6042 if (mDeviceOwner == null) { 6043 return Collections.emptyList(); 6044 } 6045 ComponentName ownerComponent = mDeviceOwner.getProfileOwnerComponent(profileId); 6046 if (ownerComponent == null) { 6047 return Collections.emptyList(); 6048 } 6049 6050 DevicePolicyData policy = getUserDataUnchecked(profileId); 6051 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent); 6052 6053 if (admin == null || admin.crossProfileWidgetProviders == null 6054 || admin.crossProfileWidgetProviders.isEmpty()) { 6055 return Collections.emptyList(); 6056 } 6057 6058 return admin.crossProfileWidgetProviders; 6059 } 6060 } 6061 6062 @Override 6063 public void addOnCrossProfileWidgetProvidersChangeListener( 6064 OnCrossProfileWidgetProvidersChangeListener listener) { 6065 synchronized (DevicePolicyManagerService.this) { 6066 if (mWidgetProviderListeners == null) { 6067 mWidgetProviderListeners = new ArrayList<>(); 6068 } 6069 if (!mWidgetProviderListeners.contains(listener)) { 6070 mWidgetProviderListeners.add(listener); 6071 } 6072 } 6073 } 6074 6075 @Override 6076 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) { 6077 final int userId = UserHandle.getUserId(uid); 6078 synchronized(DevicePolicyManagerService.this) { 6079 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null; 6080 } 6081 } 6082 6083 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) { 6084 final List<OnCrossProfileWidgetProvidersChangeListener> listeners; 6085 synchronized (DevicePolicyManagerService.this) { 6086 listeners = new ArrayList<>(mWidgetProviderListeners); 6087 } 6088 final int listenerCount = listeners.size(); 6089 for (int i = 0; i < listenerCount; i++) { 6090 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i); 6091 listener.onCrossProfileWidgetProvidersChanged(userId, packages); 6092 } 6093 } 6094 } 6095 6096 /** 6097 * Returns true if specified admin is allowed to limit passwords and has a 6098 * {@code passwordQuality} of at least {@code minPasswordQuality} 6099 */ 6100 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) { 6101 if (admin.passwordQuality < minPasswordQuality) { 6102 return false; 6103 } 6104 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 6105 } 6106 6107 @Override 6108 public void setSystemUpdatePolicy(ComponentName who, PersistableBundle policy) { 6109 synchronized (this) { 6110 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6111 if (policy == null) { 6112 mDeviceOwner.clearSystemUpdatePolicy(); 6113 } else { 6114 mDeviceOwner.setSystemUpdatePolicy(policy); 6115 } 6116 mDeviceOwner.writeOwnerFile(); 6117 } 6118 mContext.sendBroadcastAsUser( 6119 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED), 6120 UserHandle.OWNER); 6121 } 6122 6123 @Override 6124 public PersistableBundle getSystemUpdatePolicy() { 6125 synchronized (this) { 6126 return mDeviceOwner.getSystemUpdatePolicy(); 6127 } 6128 } 6129 6130 /** 6131 * Checks if the caller of the method is the device owner app or device initialization app. 6132 * 6133 * @param callerUid UID of the caller. 6134 * @return true if the caller is the device owner app or device initializer. 6135 */ 6136 private boolean isCallerDeviceOwnerOrInitializer(int callerUid) { 6137 String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid); 6138 for (String pkg : pkgs) { 6139 if (isDeviceOwner(pkg) || isDeviceInitializer(pkg)) { 6140 return true; 6141 } 6142 } 6143 return false; 6144 } 6145 6146 @Override 6147 public void notifyPendingSystemUpdate(long updateReceivedTime) { 6148 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE, 6149 "Only the system update service can broadcast update information"); 6150 6151 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) { 6152 Slog.w(LOG_TAG, "Only the system update service in the primary user" + 6153 "can broadcast update information."); 6154 return; 6155 } 6156 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE); 6157 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME, 6158 updateReceivedTime); 6159 6160 synchronized (this) { 6161 String deviceOwnerPackage = getDeviceOwner(); 6162 if (deviceOwnerPackage == null) { 6163 return; 6164 } 6165 6166 try { 6167 ActivityInfo[] receivers = mContext.getPackageManager().getPackageInfo( 6168 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers; 6169 if (receivers != null) { 6170 for (int i = 0; i < receivers.length; i++) { 6171 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) { 6172 intent.setComponent(new ComponentName(deviceOwnerPackage, 6173 receivers[i].name)); 6174 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER); 6175 } 6176 } 6177 } 6178 } catch (NameNotFoundException e) { 6179 Log.e(LOG_TAG, "Cannot find device owner package", e); 6180 } 6181 } 6182 } 6183} 6184