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