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