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