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