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