DevicePolicyManagerService.java revision cb6fd80721253ffa9dcab5cf8c2f4e9b9cd17ccc
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 // Returns the active device owner or null if there is no device owner. 4632 @VisibleForTesting 4633 ActiveAdmin getDeviceOwnerAdminLocked() { 4634 ComponentName component = getDeviceOwner(); 4635 if (component == null) { 4636 return null; 4637 } 4638 4639 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId()); 4640 final int n = policy.mAdminList.size(); 4641 for (int i = 0; i < n; i++) { 4642 ActiveAdmin admin = policy.mAdminList.get(i); 4643 if (component.equals(admin.info.getComponent())) { 4644 return admin; 4645 } 4646 } 4647 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component); 4648 return null; 4649 } 4650 4651 @Override 4652 public void clearDeviceOwner(String packageName) { 4653 Preconditions.checkNotNull(packageName, "packageName is null"); 4654 final int callingUid = mInjector.binderGetCallingUid(); 4655 try { 4656 int uid = mContext.getPackageManager().getPackageUid(packageName, 0); 4657 if (uid != callingUid) { 4658 throw new SecurityException("Invalid packageName"); 4659 } 4660 } catch (NameNotFoundException e) { 4661 throw new SecurityException(e); 4662 } 4663 if (!mOwners.hasDeviceOwner() || !getDeviceOwner().getPackageName().equals(packageName) 4664 || (mOwners.getDeviceOwnerUserId() != UserHandle.getUserId(callingUid))) { 4665 throw new SecurityException("clearDeviceOwner can only be called by the device owner"); 4666 } 4667 synchronized (this) { 4668 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 4669 if (admin != null) { 4670 admin.disableCamera = false; 4671 admin.userRestrictions = null; 4672 } 4673 clearUserPoliciesLocked(new UserHandle(UserHandle.USER_SYSTEM)); 4674 4675 mOwners.clearDeviceOwner(); 4676 mOwners.writeDeviceOwner(); 4677 updateDeviceOwnerLocked(); 4678 // Reactivate backup service. 4679 long ident = mInjector.binderClearCallingIdentity(); 4680 try { 4681 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true); 4682 } catch (RemoteException e) { 4683 throw new IllegalStateException("Failed reactivating backup service.", e); 4684 } finally { 4685 mInjector.binderRestoreCallingIdentity(ident); 4686 } 4687 } 4688 } 4689 4690 @Override 4691 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) { 4692 if (!mHasFeature) { 4693 return false; 4694 } 4695 if (who == null 4696 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) { 4697 throw new IllegalArgumentException("Component " + who 4698 + " not installed for userId:" + userHandle); 4699 } 4700 synchronized (this) { 4701 enforceCanSetProfileOwner(userHandle); 4702 mOwners.setProfileOwner(who, ownerName, userHandle); 4703 mOwners.writeProfileOwner(userHandle); 4704 return true; 4705 } 4706 } 4707 4708 @Override 4709 public void clearProfileOwner(ComponentName who) { 4710 if (!mHasFeature) { 4711 return; 4712 } 4713 UserHandle callingUser = mInjector.binderGetCallingUserHandle(); 4714 // Check if this is the profile owner who is calling 4715 final ActiveAdmin admin = 4716 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4717 synchronized (this) { 4718 admin.disableCamera = false; 4719 admin.userRestrictions = null; 4720 clearUserPoliciesLocked(callingUser); 4721 final int userId = callingUser.getIdentifier(); 4722 mOwners.removeProfileOwner(userId); 4723 mOwners.writeProfileOwner(userId); 4724 } 4725 } 4726 4727 @Override 4728 public boolean setDeviceOwnerLockScreenInfo(ComponentName who, String info) { 4729 Preconditions.checkNotNull(who, "ComponentName is null"); 4730 if (!mHasFeature) { 4731 return false; 4732 } 4733 4734 synchronized (this) { 4735 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 4736 long token = mInjector.binderClearCallingIdentity(); 4737 try { 4738 new LockPatternUtils(mContext).setDeviceOwnerInfo(info); 4739 } finally { 4740 mInjector.binderRestoreCallingIdentity(token); 4741 } 4742 return true; 4743 } 4744 } 4745 4746 @Override 4747 public String getDeviceOwnerLockScreenInfo() { 4748 return new LockPatternUtils(mContext).getDeviceOwnerInfo(); 4749 } 4750 4751 private void clearUserPoliciesLocked(UserHandle userHandle) { 4752 int userId = userHandle.getIdentifier(); 4753 // Reset some of the user-specific policies 4754 DevicePolicyData policy = getUserData(userId); 4755 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT; 4756 policy.mDelegatedCertInstallerPackage = null; 4757 policy.mStatusBarDisabled = false; 4758 saveSettingsLocked(userId); 4759 4760 final long ident = mInjector.binderClearCallingIdentity(); 4761 try { 4762 mIPackageManager.updatePermissionFlagsForAllApps( 4763 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 4764 0 /* flagValues */, userHandle.getIdentifier()); 4765 pushUserRestrictions(userHandle.getIdentifier()); 4766 } catch (RemoteException re) { 4767 } finally { 4768 mInjector.binderRestoreCallingIdentity(ident); 4769 } 4770 } 4771 4772 @Override 4773 public boolean hasUserSetupCompleted() { 4774 return hasUserSetupCompleted(UserHandle.getCallingUserId()); 4775 } 4776 4777 private boolean hasUserSetupCompleted(int userHandle) { 4778 if (!mHasFeature) { 4779 return true; 4780 } 4781 return getUserData(userHandle).mUserSetupComplete; 4782 } 4783 4784 @Override 4785 public void setProfileEnabled(ComponentName who) { 4786 if (!mHasFeature) { 4787 return; 4788 } 4789 Preconditions.checkNotNull(who, "ComponentName is null"); 4790 final int userHandle = UserHandle.getCallingUserId(); 4791 synchronized (this) { 4792 // Check if this is the profile owner who is calling 4793 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4794 int userId = UserHandle.getCallingUserId(); 4795 4796 long id = mInjector.binderClearCallingIdentity(); 4797 try { 4798 mUserManager.setUserEnabled(userId); 4799 UserInfo parent = mUserManager.getProfileParent(userId); 4800 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 4801 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle)); 4802 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 4803 Intent.FLAG_RECEIVER_FOREGROUND); 4804 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id)); 4805 } finally { 4806 mInjector.binderRestoreCallingIdentity(id); 4807 } 4808 } 4809 } 4810 4811 @Override 4812 public void setProfileName(ComponentName who, String profileName) { 4813 Preconditions.checkNotNull(who, "ComponentName is null"); 4814 int userId = UserHandle.getCallingUserId(); 4815 // Check if this is the profile owner (includes device owner). 4816 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4817 4818 long id = mInjector.binderClearCallingIdentity(); 4819 try { 4820 mUserManager.setUserName(userId, profileName); 4821 } finally { 4822 mInjector.binderRestoreCallingIdentity(id); 4823 } 4824 } 4825 4826 @Override 4827 public ComponentName getProfileOwner(int userHandle) { 4828 if (!mHasFeature) { 4829 return null; 4830 } 4831 4832 synchronized (this) { 4833 return mOwners.getProfileOwnerComponent(userHandle); 4834 } 4835 } 4836 4837 // Returns the active profile owner for this user or null if the current user has no 4838 // profile owner. 4839 @VisibleForTesting 4840 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) { 4841 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle); 4842 if (profileOwner == null) { 4843 return null; 4844 } 4845 DevicePolicyData policy = getUserData(userHandle); 4846 final int n = policy.mAdminList.size(); 4847 for (int i = 0; i < n; i++) { 4848 ActiveAdmin admin = policy.mAdminList.get(i); 4849 if (profileOwner.equals(admin.info.getComponent())) { 4850 return admin; 4851 } 4852 } 4853 return null; 4854 } 4855 4856 @Override 4857 public String getProfileOwnerName(int userHandle) { 4858 if (!mHasFeature) { 4859 return null; 4860 } 4861 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 4862 ComponentName profileOwner = getProfileOwner(userHandle); 4863 if (profileOwner == null) { 4864 return null; 4865 } 4866 return getApplicationLabel(profileOwner.getPackageName(), userHandle); 4867 } 4868 4869 /** 4870 * Canonical name for a given package. 4871 */ 4872 private String getApplicationLabel(String packageName, int userHandle) { 4873 long token = mInjector.binderClearCallingIdentity(); 4874 try { 4875 final Context userContext; 4876 try { 4877 UserHandle handle = new UserHandle(userHandle); 4878 userContext = mContext.createPackageContextAsUser(packageName, 0, handle); 4879 } catch (PackageManager.NameNotFoundException nnfe) { 4880 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe); 4881 return null; 4882 } 4883 ApplicationInfo appInfo = userContext.getApplicationInfo(); 4884 CharSequence result = null; 4885 if (appInfo != null) { 4886 PackageManager pm = userContext.getPackageManager(); 4887 result = pm.getApplicationLabel(appInfo); 4888 } 4889 return result != null ? result.toString() : null; 4890 } finally { 4891 mInjector.binderRestoreCallingIdentity(token); 4892 } 4893 } 4894 4895 /** 4896 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 4897 * permission. 4898 * The profile owner can only be set before the user setup phase has completed, 4899 * except for: 4900 * - SYSTEM_UID 4901 * - adb if there are not accounts. 4902 */ 4903 private void enforceCanSetProfileOwner(int userHandle) { 4904 UserInfo info = mUserManager.getUserInfo(userHandle); 4905 if (info == null) { 4906 // User doesn't exist. 4907 throw new IllegalArgumentException( 4908 "Attempted to set profile owner for invalid userId: " + userHandle); 4909 } 4910 if (info.isGuest()) { 4911 throw new IllegalStateException("Cannot set a profile owner on a guest"); 4912 } 4913 if (mOwners.hasProfileOwner(userHandle)) { 4914 throw new IllegalStateException("Trying to set the profile owner, but profile owner " 4915 + "is already set."); 4916 } 4917 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) { 4918 throw new IllegalStateException("Trying to set the profile owner, but the user " 4919 + "already has a device owner."); 4920 } 4921 int callingUid = mInjector.binderGetCallingUid(); 4922 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) { 4923 if (hasUserSetupCompleted(userHandle) && 4924 AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) { 4925 throw new IllegalStateException("Not allowed to set the profile owner because " 4926 + "there are already some accounts on the profile"); 4927 } 4928 return; 4929 } 4930 mContext.enforceCallingOrSelfPermission( 4931 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null); 4932 if (hasUserSetupCompleted(userHandle) 4933 && UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) { 4934 throw new IllegalStateException("Cannot set the profile owner on a user which is " 4935 + "already set-up"); 4936 } 4937 } 4938 4939 /** 4940 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 4941 * permission. 4942 * The device owner can only be set before the setup phase of the primary user has completed, 4943 * except for adb if no accounts or additional users are present on the device. 4944 */ 4945 private void enforceCanSetDeviceOwner(int userId) { 4946 if (mOwners.hasDeviceOwner()) { 4947 throw new IllegalStateException("Trying to set the device owner, but device owner " 4948 + "is already set."); 4949 } 4950 if (mOwners.hasProfileOwner(userId)) { 4951 throw new IllegalStateException("Trying to set the device owner, but the user already " 4952 + "has a profile owner."); 4953 } 4954 if (!mUserManager.isUserRunning(new UserHandle(userId))) { 4955 throw new IllegalStateException("User not running: " + userId); 4956 } 4957 4958 int callingUid = mInjector.binderGetCallingUid(); 4959 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) { 4960 if (!hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 4961 return; 4962 } 4963 // STOPSHIP Do proper check in split user mode 4964 if (!mInjector.userManagerIsSplitSystemUser()) { 4965 if (mUserManager.getUserCount() > 1) { 4966 throw new IllegalStateException( 4967 "Not allowed to set the device owner because there " 4968 + "are already several users on the device"); 4969 } 4970 if (AccountManager.get(mContext).getAccounts().length > 0) { 4971 throw new IllegalStateException( 4972 "Not allowed to set the device owner because there " 4973 + "are already some accounts on the device"); 4974 } 4975 } 4976 return; 4977 } 4978 // STOPSHIP check the caller UID with userId 4979 4980 mContext.enforceCallingOrSelfPermission( 4981 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null); 4982 // STOPSHIP Do proper check in split user mode 4983 if (!mInjector.userManagerIsSplitSystemUser()) { 4984 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 4985 throw new IllegalStateException("Cannot set the device owner if the device is " 4986 + "already set-up"); 4987 } 4988 } 4989 } 4990 4991 private void enforceCrossUserPermission(int userHandle) { 4992 if (userHandle < 0) { 4993 throw new IllegalArgumentException("Invalid userId " + userHandle); 4994 } 4995 final int callingUid = mInjector.binderGetCallingUid(); 4996 if (userHandle == UserHandle.getUserId(callingUid)) return; 4997 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4998 mContext.enforceCallingOrSelfPermission( 4999 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have" 5000 + " INTERACT_ACROSS_USERS_FULL permission"); 5001 } 5002 } 5003 5004 private void enforceNotManagedProfile(int userHandle, String message) { 5005 if(isManagedProfile(userHandle)) { 5006 throw new SecurityException("You can not " + message + " for a managed profile. "); 5007 } 5008 } 5009 5010 private UserInfo getProfileParent(int userHandle) { 5011 long ident = mInjector.binderClearCallingIdentity(); 5012 try { 5013 return mUserManager.getProfileParent(userHandle); 5014 } finally { 5015 mInjector.binderRestoreCallingIdentity(ident); 5016 } 5017 } 5018 5019 private boolean isManagedProfile(int userHandle) { 5020 long ident = mInjector.binderClearCallingIdentity(); 5021 try { 5022 return mUserManager.getUserInfo(userHandle).isManagedProfile(); 5023 } finally { 5024 mInjector.binderRestoreCallingIdentity(ident); 5025 } 5026 } 5027 5028 private void enableIfNecessary(String packageName, int userId) { 5029 try { 5030 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName, 5031 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS, 5032 userId); 5033 if (ai.enabledSetting 5034 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 5035 mIPackageManager.setApplicationEnabledSetting(packageName, 5036 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 5037 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 5038 } 5039 } catch (RemoteException e) { 5040 } 5041 } 5042 5043 @Override 5044 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 5045 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 5046 != PackageManager.PERMISSION_GRANTED) { 5047 5048 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid=" 5049 + mInjector.binderGetCallingPid() 5050 + ", uid=" + mInjector.binderGetCallingUid()); 5051 return; 5052 } 5053 5054 synchronized (this) { 5055 pw.println("Current Device Policy Manager state:"); 5056 mOwners.dump(" ", pw); 5057 int userCount = mUserData.size(); 5058 for (int u = 0; u < userCount; u++) { 5059 DevicePolicyData policy = getUserData(mUserData.keyAt(u)); 5060 pw.println(); 5061 pw.println(" Enabled Device Admins (User " + policy.mUserHandle + "):"); 5062 final int N = policy.mAdminList.size(); 5063 for (int i=0; i<N; i++) { 5064 ActiveAdmin ap = policy.mAdminList.get(i); 5065 if (ap != null) { 5066 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString()); 5067 pw.println(":"); 5068 ap.dump(" ", pw); 5069 } 5070 } 5071 if (!policy.mRemovingAdmins.isEmpty()) { 5072 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): " 5073 + policy.mRemovingAdmins); 5074 } 5075 5076 pw.println(" "); 5077 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner); 5078 } 5079 } 5080 } 5081 5082 @Override 5083 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 5084 ComponentName activity) { 5085 Preconditions.checkNotNull(who, "ComponentName is null"); 5086 final int userHandle = UserHandle.getCallingUserId(); 5087 synchronized (this) { 5088 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5089 5090 long id = mInjector.binderClearCallingIdentity(); 5091 try { 5092 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle); 5093 } catch (RemoteException re) { 5094 // Shouldn't happen 5095 } finally { 5096 mInjector.binderRestoreCallingIdentity(id); 5097 } 5098 } 5099 } 5100 5101 @Override 5102 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 5103 Preconditions.checkNotNull(who, "ComponentName is null"); 5104 final int userHandle = UserHandle.getCallingUserId(); 5105 synchronized (this) { 5106 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5107 5108 long id = mInjector.binderClearCallingIdentity(); 5109 try { 5110 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle); 5111 } catch (RemoteException re) { 5112 // Shouldn't happen 5113 } finally { 5114 mInjector.binderRestoreCallingIdentity(id); 5115 } 5116 } 5117 } 5118 5119 @Override 5120 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) { 5121 Preconditions.checkNotNull(who, "ComponentName is null"); 5122 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 5123 synchronized (this) { 5124 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5125 5126 long id = mInjector.binderClearCallingIdentity(); 5127 try { 5128 mUserManager.setApplicationRestrictions(packageName, settings, userHandle); 5129 } finally { 5130 mInjector.binderRestoreCallingIdentity(id); 5131 } 5132 } 5133 } 5134 5135 @Override 5136 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent, 5137 PersistableBundle args) { 5138 if (!mHasFeature) { 5139 return; 5140 } 5141 Preconditions.checkNotNull(admin, "admin is null"); 5142 Preconditions.checkNotNull(agent, "agent is null"); 5143 final int userHandle = UserHandle.getCallingUserId(); 5144 enforceNotManagedProfile(userHandle, "set trust agent configuration"); 5145 synchronized (this) { 5146 ActiveAdmin ap = getActiveAdminForCallerLocked(admin, 5147 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES); 5148 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args)); 5149 saveSettingsLocked(userHandle); 5150 } 5151 } 5152 5153 @Override 5154 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, 5155 ComponentName agent, int userHandle) { 5156 if (!mHasFeature) { 5157 return null; 5158 } 5159 Preconditions.checkNotNull(agent, "agent null"); 5160 enforceCrossUserPermission(userHandle); 5161 5162 synchronized (this) { 5163 final String componentName = agent.flattenToString(); 5164 if (admin != null) { 5165 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle); 5166 if (ap == null) return null; 5167 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName); 5168 if (trustAgentInfo == null || trustAgentInfo.options == null) return null; 5169 List<PersistableBundle> result = new ArrayList<PersistableBundle>(); 5170 result.add(trustAgentInfo.options); 5171 return result; 5172 } 5173 5174 // Return strictest policy for this user and profiles that are visible from this user. 5175 final List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 5176 List<PersistableBundle> result = null; 5177 5178 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track 5179 // of the options. If any admin doesn't have options, discard options for the rest 5180 // and return null. 5181 boolean allAdminsHaveOptions = true; 5182 for (UserInfo userInfo : profiles) { 5183 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 5184 final int N = policy.mAdminList.size(); 5185 for (int i=0; i < N; i++) { 5186 final ActiveAdmin active = policy.mAdminList.get(i); 5187 final boolean disablesTrust = (active.disabledKeyguardFeatures 5188 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 5189 final TrustAgentInfo info = active.trustAgentInfos.get(componentName); 5190 if (info != null && info.options != null && !info.options.isEmpty()) { 5191 if (disablesTrust) { 5192 if (result == null) { 5193 result = new ArrayList<PersistableBundle>(); 5194 } 5195 result.add(info.options); 5196 } else { 5197 Log.w(LOG_TAG, "Ignoring admin " + active.info 5198 + " because it has trust options but doesn't declare " 5199 + "KEYGUARD_DISABLE_TRUST_AGENTS"); 5200 } 5201 } else if (disablesTrust) { 5202 allAdminsHaveOptions = false; 5203 break; 5204 } 5205 } 5206 } 5207 return allAdminsHaveOptions ? result : null; 5208 } 5209 } 5210 5211 @Override 5212 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 5213 Preconditions.checkNotNull(who, "ComponentName is null"); 5214 synchronized (this) { 5215 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5216 5217 int userHandle = UserHandle.getCallingUserId(); 5218 DevicePolicyData userData = getUserData(userHandle); 5219 userData.mRestrictionsProvider = permissionProvider; 5220 saveSettingsLocked(userHandle); 5221 } 5222 } 5223 5224 @Override 5225 public ComponentName getRestrictionsProvider(int userHandle) { 5226 synchronized (this) { 5227 if (mInjector.binderGetCallingUid() != Process.SYSTEM_UID) { 5228 throw new SecurityException("Only the system can query the permission provider"); 5229 } 5230 DevicePolicyData userData = getUserData(userHandle); 5231 return userData != null ? userData.mRestrictionsProvider : null; 5232 } 5233 } 5234 5235 @Override 5236 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 5237 Preconditions.checkNotNull(who, "ComponentName is null"); 5238 int callingUserId = UserHandle.getCallingUserId(); 5239 synchronized (this) { 5240 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5241 5242 long id = mInjector.binderClearCallingIdentity(); 5243 try { 5244 UserInfo parent = mUserManager.getProfileParent(callingUserId); 5245 if (parent == null) { 5246 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no " 5247 + "parent"); 5248 return; 5249 } 5250 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 5251 mIPackageManager.addCrossProfileIntentFilter( 5252 filter, who.getPackageName(), callingUserId, parent.id, 0); 5253 } 5254 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 5255 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(), 5256 parent.id, callingUserId, 0); 5257 } 5258 } catch (RemoteException re) { 5259 // Shouldn't happen 5260 } finally { 5261 mInjector.binderRestoreCallingIdentity(id); 5262 } 5263 } 5264 } 5265 5266 @Override 5267 public void clearCrossProfileIntentFilters(ComponentName who) { 5268 Preconditions.checkNotNull(who, "ComponentName is null"); 5269 int callingUserId = UserHandle.getCallingUserId(); 5270 synchronized (this) { 5271 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5272 long id = mInjector.binderClearCallingIdentity(); 5273 try { 5274 UserInfo parent = mUserManager.getProfileParent(callingUserId); 5275 if (parent == null) { 5276 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no " 5277 + "parent"); 5278 return; 5279 } 5280 // Removing those that go from the managed profile to the parent. 5281 mIPackageManager.clearCrossProfileIntentFilters( 5282 callingUserId, who.getPackageName()); 5283 // And those that go from the parent to the managed profile. 5284 // If we want to support multiple managed profiles, we will have to only remove 5285 // those that have callingUserId as their target. 5286 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName()); 5287 } catch (RemoteException re) { 5288 // Shouldn't happen 5289 } finally { 5290 mInjector.binderRestoreCallingIdentity(id); 5291 } 5292 } 5293 } 5294 5295 /** 5296 * @return true if all packages in enabledPackages are either in the list 5297 * permittedList or are a system app. 5298 */ 5299 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages, 5300 List<String> permittedList) { 5301 int userIdToCheck = UserHandle.getCallingUserId(); 5302 long id = mInjector.binderClearCallingIdentity(); 5303 try { 5304 // If we have an enabled packages list for a managed profile the packages 5305 // we should check are installed for the parent user. 5306 UserInfo user = mUserManager.getUserInfo(userIdToCheck); 5307 if (user.isManagedProfile()) { 5308 userIdToCheck = user.profileGroupId; 5309 } 5310 5311 for (String enabledPackage : enabledPackages) { 5312 boolean systemService = false; 5313 try { 5314 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo( 5315 enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck); 5316 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 5317 } catch (RemoteException e) { 5318 Log.i(LOG_TAG, "Can't talk to package managed", e); 5319 } 5320 if (!systemService && !permittedList.contains(enabledPackage)) { 5321 return false; 5322 } 5323 } 5324 } finally { 5325 mInjector.binderRestoreCallingIdentity(id); 5326 } 5327 return true; 5328 } 5329 5330 private AccessibilityManager getAccessibilityManagerForUser(int userId) { 5331 // Not using AccessibilityManager.getInstance because that guesses 5332 // at the user you require based on callingUid and caches for a given 5333 // process. 5334 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); 5335 IAccessibilityManager service = iBinder == null 5336 ? null : IAccessibilityManager.Stub.asInterface(iBinder); 5337 return new AccessibilityManager(mContext, service, userId); 5338 } 5339 5340 @Override 5341 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) { 5342 if (!mHasFeature) { 5343 return false; 5344 } 5345 Preconditions.checkNotNull(who, "ComponentName is null"); 5346 5347 if (packageList != null) { 5348 int userId = UserHandle.getCallingUserId(); 5349 List<AccessibilityServiceInfo> enabledServices = null; 5350 long id = mInjector.binderClearCallingIdentity(); 5351 try { 5352 UserInfo user = mUserManager.getUserInfo(userId); 5353 if (user.isManagedProfile()) { 5354 userId = user.profileGroupId; 5355 } 5356 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId); 5357 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList( 5358 AccessibilityServiceInfo.FEEDBACK_ALL_MASK); 5359 } finally { 5360 mInjector.binderRestoreCallingIdentity(id); 5361 } 5362 5363 if (enabledServices != null) { 5364 List<String> enabledPackages = new ArrayList<String>(); 5365 for (AccessibilityServiceInfo service : enabledServices) { 5366 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName); 5367 } 5368 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) { 5369 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, " 5370 + "because it contains already enabled accesibility services."); 5371 return false; 5372 } 5373 } 5374 } 5375 5376 synchronized (this) { 5377 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5378 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5379 admin.permittedAccessiblityServices = packageList; 5380 saveSettingsLocked(UserHandle.getCallingUserId()); 5381 } 5382 return true; 5383 } 5384 5385 @Override 5386 public List getPermittedAccessibilityServices(ComponentName who) { 5387 if (!mHasFeature) { 5388 return null; 5389 } 5390 Preconditions.checkNotNull(who, "ComponentName is null"); 5391 5392 synchronized (this) { 5393 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5394 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5395 return admin.permittedAccessiblityServices; 5396 } 5397 } 5398 5399 @Override 5400 public List getPermittedAccessibilityServicesForUser(int userId) { 5401 if (!mHasFeature) { 5402 return null; 5403 } 5404 synchronized (this) { 5405 List<String> result = null; 5406 // If we have multiple profiles we return the intersection of the 5407 // permitted lists. This can happen in cases where we have a device 5408 // and profile owner. 5409 List<UserInfo> profiles = mUserManager.getProfiles(userId); 5410 final int PROFILES_SIZE = profiles.size(); 5411 for (int i = 0; i < PROFILES_SIZE; ++i) { 5412 // Just loop though all admins, only device or profiles 5413 // owners can have permitted lists set. 5414 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id); 5415 final int N = policy.mAdminList.size(); 5416 for (int j = 0; j < N; j++) { 5417 ActiveAdmin admin = policy.mAdminList.get(j); 5418 List<String> fromAdmin = admin.permittedAccessiblityServices; 5419 if (fromAdmin != null) { 5420 if (result == null) { 5421 result = new ArrayList<String>(fromAdmin); 5422 } else { 5423 result.retainAll(fromAdmin); 5424 } 5425 } 5426 } 5427 } 5428 5429 // If we have a permitted list add all system accessibility services. 5430 if (result != null) { 5431 long id = mInjector.binderClearCallingIdentity(); 5432 try { 5433 UserInfo user = mUserManager.getUserInfo(userId); 5434 if (user.isManagedProfile()) { 5435 userId = user.profileGroupId; 5436 } 5437 AccessibilityManager accessibilityManager = 5438 getAccessibilityManagerForUser(userId); 5439 List<AccessibilityServiceInfo> installedServices = 5440 accessibilityManager.getInstalledAccessibilityServiceList(); 5441 5442 if (installedServices != null) { 5443 for (AccessibilityServiceInfo service : installedServices) { 5444 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo; 5445 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 5446 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 5447 result.add(serviceInfo.packageName); 5448 } 5449 } 5450 } 5451 } finally { 5452 mInjector.binderRestoreCallingIdentity(id); 5453 } 5454 } 5455 5456 return result; 5457 } 5458 } 5459 5460 private boolean checkCallerIsCurrentUserOrProfile() { 5461 int callingUserId = UserHandle.getCallingUserId(); 5462 long token = mInjector.binderClearCallingIdentity(); 5463 try { 5464 UserInfo currentUser; 5465 UserInfo callingUser = mUserManager.getUserInfo(callingUserId); 5466 try { 5467 currentUser = mInjector.getIActivityManager().getCurrentUser(); 5468 } catch (RemoteException e) { 5469 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e); 5470 return false; 5471 } 5472 5473 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) { 5474 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile " 5475 + "of a user that isn't the foreground user."); 5476 return false; 5477 } 5478 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) { 5479 Slog.e(LOG_TAG, "Cannot set permitted input methods " 5480 + "of a user that isn't the foreground user."); 5481 return false; 5482 } 5483 } finally { 5484 mInjector.binderRestoreCallingIdentity(token); 5485 } 5486 return true; 5487 } 5488 5489 @Override 5490 public boolean setPermittedInputMethods(ComponentName who, List packageList) { 5491 if (!mHasFeature) { 5492 return false; 5493 } 5494 Preconditions.checkNotNull(who, "ComponentName is null"); 5495 5496 // TODO When InputMethodManager supports per user calls remove 5497 // this restriction. 5498 if (!checkCallerIsCurrentUserOrProfile()) { 5499 return false; 5500 } 5501 5502 if (packageList != null) { 5503 // InputMethodManager fetches input methods for current user. 5504 // So this can only be set when calling user is the current user 5505 // or parent is current user in case of managed profiles. 5506 InputMethodManager inputMethodManager = (InputMethodManager) mContext 5507 .getSystemService(Context.INPUT_METHOD_SERVICE); 5508 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList(); 5509 5510 if (enabledImes != null) { 5511 List<String> enabledPackages = new ArrayList<String>(); 5512 for (InputMethodInfo ime : enabledImes) { 5513 enabledPackages.add(ime.getPackageName()); 5514 } 5515 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) { 5516 Slog.e(LOG_TAG, "Cannot set permitted input methods, " 5517 + "because it contains already enabled input method."); 5518 return false; 5519 } 5520 } 5521 } 5522 5523 synchronized (this) { 5524 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5525 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5526 admin.permittedInputMethods = packageList; 5527 saveSettingsLocked(UserHandle.getCallingUserId()); 5528 } 5529 return true; 5530 } 5531 5532 @Override 5533 public List getPermittedInputMethods(ComponentName who) { 5534 if (!mHasFeature) { 5535 return null; 5536 } 5537 Preconditions.checkNotNull(who, "ComponentName is null"); 5538 5539 synchronized (this) { 5540 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5541 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5542 return admin.permittedInputMethods; 5543 } 5544 } 5545 5546 @Override 5547 public List getPermittedInputMethodsForCurrentUser() { 5548 UserInfo currentUser; 5549 try { 5550 currentUser = mInjector.getIActivityManager().getCurrentUser(); 5551 } catch (RemoteException e) { 5552 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e); 5553 // Activity managed is dead, just allow all IMEs 5554 return null; 5555 } 5556 5557 int userId = currentUser.id; 5558 synchronized (this) { 5559 List<String> result = null; 5560 // If we have multiple profiles we return the intersection of the 5561 // permitted lists. This can happen in cases where we have a device 5562 // and profile owner. 5563 List<UserInfo> profiles = mUserManager.getProfiles(userId); 5564 final int PROFILES_SIZE = profiles.size(); 5565 for (int i = 0; i < PROFILES_SIZE; ++i) { 5566 // Just loop though all admins, only device or profiles 5567 // owners can have permitted lists set. 5568 DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id); 5569 final int N = policy.mAdminList.size(); 5570 for (int j = 0; j < N; j++) { 5571 ActiveAdmin admin = policy.mAdminList.get(j); 5572 List<String> fromAdmin = admin.permittedInputMethods; 5573 if (fromAdmin != null) { 5574 if (result == null) { 5575 result = new ArrayList<String>(fromAdmin); 5576 } else { 5577 result.retainAll(fromAdmin); 5578 } 5579 } 5580 } 5581 } 5582 5583 // If we have a permitted list add all system input methods. 5584 if (result != null) { 5585 InputMethodManager inputMethodManager = (InputMethodManager) mContext 5586 .getSystemService(Context.INPUT_METHOD_SERVICE); 5587 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList(); 5588 long id = mInjector.binderClearCallingIdentity(); 5589 try { 5590 if (imes != null) { 5591 for (InputMethodInfo ime : imes) { 5592 ServiceInfo serviceInfo = ime.getServiceInfo(); 5593 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 5594 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 5595 result.add(serviceInfo.packageName); 5596 } 5597 } 5598 } 5599 } finally { 5600 mInjector.binderRestoreCallingIdentity(id); 5601 } 5602 } 5603 return result; 5604 } 5605 } 5606 5607 @Override 5608 public UserHandle createUser(ComponentName who, String name) { 5609 Preconditions.checkNotNull(who, "ComponentName is null"); 5610 synchronized (this) { 5611 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5612 5613 long id = mInjector.binderClearCallingIdentity(); 5614 try { 5615 UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */); 5616 if (userInfo != null) { 5617 return userInfo.getUserHandle(); 5618 } 5619 return null; 5620 } finally { 5621 mInjector.binderRestoreCallingIdentity(id); 5622 } 5623 } 5624 } 5625 5626 @Override 5627 public UserHandle createAndInitializeUser(ComponentName who, String name, 5628 String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) { 5629 UserHandle user = createUser(who, name); 5630 if (user == null) { 5631 return null; 5632 } 5633 long id = mInjector.binderClearCallingIdentity(); 5634 try { 5635 String profileOwnerPkg = profileOwnerComponent.getPackageName(); 5636 5637 final int userHandle = user.getIdentifier(); 5638 try { 5639 // Install the profile owner if not present. 5640 if (!mIPackageManager.isPackageAvailable(profileOwnerPkg, userHandle)) { 5641 mIPackageManager.installExistingPackageAsUser(profileOwnerPkg, userHandle); 5642 } 5643 5644 // Start user in background. 5645 mInjector.getIActivityManager().startUserInBackground(userHandle); 5646 } catch (RemoteException e) { 5647 Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e); 5648 } 5649 5650 setActiveAdmin(profileOwnerComponent, true, userHandle, adminExtras); 5651 setProfileOwner(profileOwnerComponent, ownerName, userHandle); 5652 return user; 5653 } finally { 5654 mInjector.binderRestoreCallingIdentity(id); 5655 } 5656 } 5657 5658 @Override 5659 public boolean removeUser(ComponentName who, UserHandle userHandle) { 5660 Preconditions.checkNotNull(who, "ComponentName is null"); 5661 synchronized (this) { 5662 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5663 5664 long id = mInjector.binderClearCallingIdentity(); 5665 try { 5666 return mUserManager.removeUser(userHandle.getIdentifier()); 5667 } finally { 5668 mInjector.binderRestoreCallingIdentity(id); 5669 } 5670 } 5671 } 5672 5673 @Override 5674 public boolean switchUser(ComponentName who, UserHandle userHandle) { 5675 Preconditions.checkNotNull(who, "ComponentName is null"); 5676 synchronized (this) { 5677 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5678 5679 long id = mInjector.binderClearCallingIdentity(); 5680 try { 5681 int userId = UserHandle.USER_SYSTEM; 5682 if (userHandle != null) { 5683 userId = userHandle.getIdentifier(); 5684 } 5685 return mInjector.getIActivityManager().switchUser(userId); 5686 } catch (RemoteException e) { 5687 Log.e(LOG_TAG, "Couldn't switch user", e); 5688 return false; 5689 } finally { 5690 mInjector.binderRestoreCallingIdentity(id); 5691 } 5692 } 5693 } 5694 5695 @Override 5696 public Bundle getApplicationRestrictions(ComponentName who, String packageName) { 5697 Preconditions.checkNotNull(who, "ComponentName is null"); 5698 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 5699 5700 synchronized (this) { 5701 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5702 5703 long id = mInjector.binderClearCallingIdentity(); 5704 try { 5705 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle); 5706 // if no restrictions were saved, mUserManager.getApplicationRestrictions 5707 // returns null, but DPM method should return an empty Bundle as per JavaDoc 5708 return bundle != null ? bundle : Bundle.EMPTY; 5709 } finally { 5710 mInjector.binderRestoreCallingIdentity(id); 5711 } 5712 } 5713 } 5714 5715 @Override 5716 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) { 5717 Preconditions.checkNotNull(who, "ComponentName is null"); 5718 final int userHandle = mInjector.userHandleGetCallingUserId(); 5719 synchronized (this) { 5720 ActiveAdmin activeAdmin = 5721 getActiveAdminForCallerLocked(who, 5722 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5723 final boolean isDeviceOwner = isDeviceOwner(who, userHandle); 5724 if (isDeviceOwner) { 5725 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) { 5726 throw new SecurityException("Device owner cannot set user restriction " + key); 5727 } 5728 } else { // profile owner 5729 if (!UserRestrictionsUtils.canProfileOwnerChange(key)) { 5730 throw new SecurityException("Profile owner cannot set user restriction " + key); 5731 } 5732 } 5733 5734 // Save the restriction to ActiveAdmin. 5735 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner); 5736 saveSettingsLocked(userHandle); 5737 5738 pushUserRestrictions(userHandle); 5739 5740 sendChangedNotification(userHandle); 5741 } 5742 } 5743 5744 private void pushUserRestrictions(int userId) { 5745 synchronized (this) { 5746 final Bundle global; 5747 final Bundle local = new Bundle(); 5748 if (mOwners.isDeviceOwnerUserId(userId)) { 5749 global = new Bundle(); 5750 5751 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 5752 if (deviceOwner == null) { 5753 return; // Shouldn't happen. 5754 } 5755 5756 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions, 5757 global, local); 5758 // DO can disable camera globally. 5759 if (deviceOwner.disableCamera) { 5760 global.putBoolean(UserManager.DISALLOW_CAMERA, true); 5761 } 5762 } else { 5763 global = null; 5764 5765 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 5766 if (profileOwner != null) { 5767 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions); 5768 } 5769 } 5770 // Also merge in *local* camera restriction. 5771 if (getCameraDisabled(/* who= */ null, 5772 userId, /* mergeDeviceOwnerRestriction= */ false)) { 5773 local.putBoolean(UserManager.DISALLOW_CAMERA, true); 5774 } 5775 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global); 5776 } 5777 } 5778 5779 @Override 5780 public Bundle getUserRestrictions(ComponentName who) { 5781 Preconditions.checkNotNull(who, "ComponentName is null"); 5782 synchronized (this) { 5783 final ActiveAdmin activeAdmin = 5784 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5785 return activeAdmin.userRestrictions; 5786 } 5787 } 5788 5789 @Override 5790 public boolean setApplicationHidden(ComponentName who, String packageName, 5791 boolean hidden) { 5792 Preconditions.checkNotNull(who, "ComponentName is null"); 5793 int callingUserId = UserHandle.getCallingUserId(); 5794 synchronized (this) { 5795 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5796 5797 long id = mInjector.binderClearCallingIdentity(); 5798 try { 5799 return mIPackageManager.setApplicationHiddenSettingAsUser( 5800 packageName, hidden, callingUserId); 5801 } catch (RemoteException re) { 5802 // shouldn't happen 5803 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re); 5804 } finally { 5805 mInjector.binderRestoreCallingIdentity(id); 5806 } 5807 return false; 5808 } 5809 } 5810 5811 @Override 5812 public boolean isApplicationHidden(ComponentName who, String packageName) { 5813 Preconditions.checkNotNull(who, "ComponentName is null"); 5814 int callingUserId = UserHandle.getCallingUserId(); 5815 synchronized (this) { 5816 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5817 5818 long id = mInjector.binderClearCallingIdentity(); 5819 try { 5820 return mIPackageManager.getApplicationHiddenSettingAsUser( 5821 packageName, callingUserId); 5822 } catch (RemoteException re) { 5823 // shouldn't happen 5824 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re); 5825 } finally { 5826 mInjector.binderRestoreCallingIdentity(id); 5827 } 5828 return false; 5829 } 5830 } 5831 5832 @Override 5833 public void enableSystemApp(ComponentName who, String packageName) { 5834 Preconditions.checkNotNull(who, "ComponentName is null"); 5835 synchronized (this) { 5836 // This API can only be called by an active device admin, 5837 // so try to retrieve it to check that the caller is one. 5838 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5839 5840 int userId = UserHandle.getCallingUserId(); 5841 long id = mInjector.binderClearCallingIdentity(); 5842 5843 try { 5844 if (VERBOSE_LOG) { 5845 Slog.v(LOG_TAG, "installing " + packageName + " for " 5846 + userId); 5847 } 5848 5849 UserManager um = UserManager.get(mContext); 5850 UserInfo primaryUser = um.getProfileParent(userId); 5851 5852 // Call did not come from a managed profile 5853 if (primaryUser == null) { 5854 primaryUser = um.getUserInfo(userId); 5855 } 5856 5857 if (!isSystemApp(mIPackageManager, packageName, primaryUser.id)) { 5858 throw new IllegalArgumentException("Only system apps can be enabled this way."); 5859 } 5860 5861 // Install the app. 5862 mIPackageManager.installExistingPackageAsUser(packageName, userId); 5863 5864 } catch (RemoteException re) { 5865 // shouldn't happen 5866 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re); 5867 } finally { 5868 mInjector.binderRestoreCallingIdentity(id); 5869 } 5870 } 5871 } 5872 5873 @Override 5874 public int enableSystemAppWithIntent(ComponentName who, Intent intent) { 5875 Preconditions.checkNotNull(who, "ComponentName is null"); 5876 synchronized (this) { 5877 // This API can only be called by an active device admin, 5878 // so try to retrieve it to check that the caller is one. 5879 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5880 5881 int userId = UserHandle.getCallingUserId(); 5882 long id = mInjector.binderClearCallingIdentity(); 5883 5884 try { 5885 UserManager um = UserManager.get(mContext); 5886 UserInfo primaryUser = um.getProfileParent(userId); 5887 5888 // Call did not come from a managed profile. 5889 if (primaryUser == null) { 5890 primaryUser = um.getUserInfo(userId); 5891 } 5892 5893 List<ResolveInfo> activitiesToEnable = mIPackageManager.queryIntentActivities( 5894 intent, 5895 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 5896 0, // no flags 5897 primaryUser.id); 5898 5899 if (VERBOSE_LOG) { 5900 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable); 5901 } 5902 int numberOfAppsInstalled = 0; 5903 if (activitiesToEnable != null) { 5904 for (ResolveInfo info : activitiesToEnable) { 5905 if (info.activityInfo != null) { 5906 String packageName = info.activityInfo.packageName; 5907 if (isSystemApp(mIPackageManager, packageName, primaryUser.id)) { 5908 numberOfAppsInstalled++; 5909 mIPackageManager.installExistingPackageAsUser(packageName, userId); 5910 } else { 5911 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a" 5912 + " system app"); 5913 } 5914 } 5915 } 5916 } 5917 return numberOfAppsInstalled; 5918 } catch (RemoteException e) { 5919 // shouldn't happen 5920 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent); 5921 return 0; 5922 } finally { 5923 mInjector.binderRestoreCallingIdentity(id); 5924 } 5925 } 5926 } 5927 5928 private boolean isSystemApp(IPackageManager pm, String packageName, int userId) 5929 throws RemoteException { 5930 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES, 5931 userId); 5932 if (appInfo == null) { 5933 throw new IllegalArgumentException("The application " + packageName + 5934 " is not present on this device"); 5935 } 5936 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 5937 } 5938 5939 @Override 5940 public void setAccountManagementDisabled(ComponentName who, String accountType, 5941 boolean disabled) { 5942 if (!mHasFeature) { 5943 return; 5944 } 5945 Preconditions.checkNotNull(who, "ComponentName is null"); 5946 synchronized (this) { 5947 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5948 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5949 if (disabled) { 5950 ap.accountTypesWithManagementDisabled.add(accountType); 5951 } else { 5952 ap.accountTypesWithManagementDisabled.remove(accountType); 5953 } 5954 saveSettingsLocked(UserHandle.getCallingUserId()); 5955 } 5956 } 5957 5958 @Override 5959 public String[] getAccountTypesWithManagementDisabled() { 5960 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId()); 5961 } 5962 5963 @Override 5964 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) { 5965 enforceCrossUserPermission(userId); 5966 if (!mHasFeature) { 5967 return null; 5968 } 5969 synchronized (this) { 5970 DevicePolicyData policy = getUserData(userId); 5971 final int N = policy.mAdminList.size(); 5972 ArraySet<String> resultSet = new ArraySet<>(); 5973 for (int i = 0; i < N; i++) { 5974 ActiveAdmin admin = policy.mAdminList.get(i); 5975 resultSet.addAll(admin.accountTypesWithManagementDisabled); 5976 } 5977 return resultSet.toArray(new String[resultSet.size()]); 5978 } 5979 } 5980 5981 @Override 5982 public void setUninstallBlocked(ComponentName who, String packageName, 5983 boolean uninstallBlocked) { 5984 Preconditions.checkNotNull(who, "ComponentName is null"); 5985 final int userId = UserHandle.getCallingUserId(); 5986 synchronized (this) { 5987 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5988 5989 long id = mInjector.binderClearCallingIdentity(); 5990 try { 5991 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId); 5992 } catch (RemoteException re) { 5993 // Shouldn't happen. 5994 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 5995 } finally { 5996 mInjector.binderRestoreCallingIdentity(id); 5997 } 5998 } 5999 } 6000 6001 @Override 6002 public boolean isUninstallBlocked(ComponentName who, String packageName) { 6003 // This function should return true if and only if the package is blocked by 6004 // setUninstallBlocked(). It should still return false for other cases of blocks, such as 6005 // when the package is a system app, or when it is an active device admin. 6006 final int userId = UserHandle.getCallingUserId(); 6007 6008 synchronized (this) { 6009 if (who != null) { 6010 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6011 } 6012 6013 long id = mInjector.binderClearCallingIdentity(); 6014 try { 6015 return mIPackageManager.getBlockUninstallForUser(packageName, userId); 6016 } catch (RemoteException re) { 6017 // Shouldn't happen. 6018 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 6019 } finally { 6020 mInjector.binderRestoreCallingIdentity(id); 6021 } 6022 } 6023 return false; 6024 } 6025 6026 @Override 6027 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { 6028 if (!mHasFeature) { 6029 return; 6030 } 6031 Preconditions.checkNotNull(who, "ComponentName is null"); 6032 synchronized (this) { 6033 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 6034 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6035 if (admin.disableCallerId != disabled) { 6036 admin.disableCallerId = disabled; 6037 saveSettingsLocked(UserHandle.getCallingUserId()); 6038 } 6039 } 6040 } 6041 6042 @Override 6043 public boolean getCrossProfileCallerIdDisabled(ComponentName who) { 6044 if (!mHasFeature) { 6045 return false; 6046 } 6047 Preconditions.checkNotNull(who, "ComponentName is null"); 6048 synchronized (this) { 6049 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 6050 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6051 return admin.disableCallerId; 6052 } 6053 } 6054 6055 @Override 6056 public boolean getCrossProfileCallerIdDisabledForUser(int userId) { 6057 // TODO: Should there be a check to make sure this relationship is within a profile group? 6058 //enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 6059 synchronized (this) { 6060 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 6061 return (admin != null) ? admin.disableCallerId : false; 6062 } 6063 } 6064 6065 @Override 6066 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 6067 Intent originalIntent) { 6068 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent( 6069 actualLookupKey, actualContactId, originalIntent); 6070 final int callingUserId = UserHandle.getCallingUserId(); 6071 6072 final long ident = mInjector.binderClearCallingIdentity(); 6073 try { 6074 synchronized (this) { 6075 final int managedUserId = getManagedUserId(callingUserId); 6076 if (managedUserId < 0) { 6077 return; 6078 } 6079 if (getCrossProfileCallerIdDisabledForUser(managedUserId)) { 6080 if (VERBOSE_LOG) { 6081 Log.v(LOG_TAG, 6082 "Cross-profile contacts access disabled for user " + managedUserId); 6083 } 6084 return; 6085 } 6086 ContactsInternal.startQuickContactWithErrorToastForUser( 6087 mContext, intent, new UserHandle(managedUserId)); 6088 } 6089 } finally { 6090 mInjector.binderRestoreCallingIdentity(ident); 6091 } 6092 } 6093 6094 /** 6095 * @return the user ID of the managed user that is linked to the current user, if any. 6096 * Otherwise -1. 6097 */ 6098 public int getManagedUserId(int callingUserId) { 6099 if (VERBOSE_LOG) { 6100 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId); 6101 } 6102 6103 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) { 6104 if (ui.id == callingUserId || !ui.isManagedProfile()) { 6105 continue; // Caller user self, or not a managed profile. Skip. 6106 } 6107 if (VERBOSE_LOG) { 6108 Log.v(LOG_TAG, "Managed user=" + ui.id); 6109 } 6110 return ui.id; 6111 } 6112 if (VERBOSE_LOG) { 6113 Log.v(LOG_TAG, "Managed user not found."); 6114 } 6115 return -1; 6116 } 6117 6118 @Override 6119 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { 6120 if (!mHasFeature) { 6121 return; 6122 } 6123 Preconditions.checkNotNull(who, "ComponentName is null"); 6124 synchronized (this) { 6125 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 6126 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6127 if (admin.disableBluetoothContactSharing != disabled) { 6128 admin.disableBluetoothContactSharing = disabled; 6129 saveSettingsLocked(UserHandle.getCallingUserId()); 6130 } 6131 } 6132 } 6133 6134 @Override 6135 public boolean getBluetoothContactSharingDisabled(ComponentName who) { 6136 if (!mHasFeature) { 6137 return false; 6138 } 6139 Preconditions.checkNotNull(who, "ComponentName is null"); 6140 synchronized (this) { 6141 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 6142 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6143 return admin.disableBluetoothContactSharing; 6144 } 6145 } 6146 6147 @Override 6148 public boolean getBluetoothContactSharingDisabledForUser(int userId) { 6149 // TODO: Should there be a check to make sure this relationship is 6150 // within a profile group? 6151 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 6152 synchronized (this) { 6153 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 6154 return (admin != null) ? admin.disableBluetoothContactSharing : false; 6155 } 6156 } 6157 6158 /** 6159 * Sets which packages may enter lock task mode. 6160 * 6161 * This function can only be called by the device owner. 6162 * @param packages The list of packages allowed to enter lock task mode. 6163 */ 6164 @Override 6165 public void setLockTaskPackages(ComponentName who, String[] packages) 6166 throws SecurityException { 6167 Preconditions.checkNotNull(who, "ComponentName is null"); 6168 synchronized (this) { 6169 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6170 6171 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier(); 6172 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages))); 6173 } 6174 } 6175 6176 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) { 6177 DevicePolicyData policy = getUserData(userHandle); 6178 policy.mLockTaskPackages = packages; 6179 6180 // Store the settings persistently. 6181 saveSettingsLocked(userHandle); 6182 updateLockTaskPackagesLocked(packages, userHandle); 6183 } 6184 6185 /** 6186 * This function returns the list of components allowed to start the task lock mode. 6187 */ 6188 @Override 6189 public String[] getLockTaskPackages(ComponentName who) { 6190 Preconditions.checkNotNull(who, "ComponentName is null"); 6191 synchronized (this) { 6192 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6193 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier(); 6194 final List<String> packages = getLockTaskPackagesLocked(userHandle); 6195 return packages.toArray(new String[packages.size()]); 6196 } 6197 } 6198 6199 private List<String> getLockTaskPackagesLocked(int userHandle) { 6200 final DevicePolicyData policy = getUserData(userHandle); 6201 return policy.mLockTaskPackages; 6202 } 6203 6204 /** 6205 * This function lets the caller know whether the given package is allowed to start the 6206 * lock task mode. 6207 * @param pkg The package to check 6208 */ 6209 @Override 6210 public boolean isLockTaskPermitted(String pkg) { 6211 // Get current user's devicepolicy 6212 int uid = mInjector.binderGetCallingUid(); 6213 int userHandle = UserHandle.getUserId(uid); 6214 DevicePolicyData policy = getUserData(userHandle); 6215 synchronized (this) { 6216 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) { 6217 String lockTaskPackage = policy.mLockTaskPackages.get(i); 6218 6219 // If the given package equals one of the packages stored our list, 6220 // we allow this package to start lock task mode. 6221 if (lockTaskPackage.equals(pkg)) { 6222 return true; 6223 } 6224 } 6225 } 6226 return false; 6227 } 6228 6229 @Override 6230 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 6231 if (mInjector.binderGetCallingUid() != Process.SYSTEM_UID) { 6232 throw new SecurityException("notifyLockTaskModeChanged can only be called by system"); 6233 } 6234 synchronized (this) { 6235 final DevicePolicyData policy = getUserData(userHandle); 6236 Bundle adminExtras = new Bundle(); 6237 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 6238 for (ActiveAdmin admin : policy.mAdminList) { 6239 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle); 6240 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle); 6241 if (ownsDevice || ownsProfile) { 6242 if (isEnabled) { 6243 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING, 6244 adminExtras, null); 6245 } else { 6246 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING); 6247 } 6248 } 6249 } 6250 } 6251 } 6252 6253 @Override 6254 public void setGlobalSetting(ComponentName who, String setting, String value) { 6255 Preconditions.checkNotNull(who, "ComponentName is null"); 6256 6257 synchronized (this) { 6258 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6259 6260 // Some settings are no supported any more. However we do not want to throw a 6261 // SecurityException to avoid breaking apps. 6262 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) { 6263 Log.i(LOG_TAG, "Global setting no longer supported: " + setting); 6264 return; 6265 } 6266 6267 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) { 6268 throw new SecurityException(String.format( 6269 "Permission denial: device owners cannot update %1$s", setting)); 6270 } 6271 6272 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) { 6273 // ignore if it contradicts an existing policy 6274 long timeMs = getMaximumTimeToLock(who, UserHandle.getCallingUserId()); 6275 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) { 6276 return; 6277 } 6278 } 6279 6280 long id = mInjector.binderClearCallingIdentity(); 6281 try { 6282 mInjector.settingsGlobalPutString(setting, value); 6283 } finally { 6284 mInjector.binderRestoreCallingIdentity(id); 6285 } 6286 } 6287 } 6288 6289 @Override 6290 public void setSecureSetting(ComponentName who, String setting, String value) { 6291 Preconditions.checkNotNull(who, "ComponentName is null"); 6292 int callingUserId = mInjector.userHandleGetCallingUserId(); 6293 6294 synchronized (this) { 6295 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6296 6297 if (isDeviceOwner(who, mInjector.userHandleGetCallingUserId())) { 6298 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) { 6299 throw new SecurityException(String.format( 6300 "Permission denial: Device owners cannot update %1$s", setting)); 6301 } 6302 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) { 6303 throw new SecurityException(String.format( 6304 "Permission denial: Profile owners cannot update %1$s", setting)); 6305 } 6306 6307 long id = mInjector.binderClearCallingIdentity(); 6308 try { 6309 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId); 6310 } finally { 6311 mInjector.binderRestoreCallingIdentity(id); 6312 } 6313 } 6314 } 6315 6316 @Override 6317 public void setMasterVolumeMuted(ComponentName who, boolean on) { 6318 Preconditions.checkNotNull(who, "ComponentName is null"); 6319 synchronized (this) { 6320 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6321 int userId = UserHandle.getCallingUserId(); 6322 long identity = mInjector.binderClearCallingIdentity(); 6323 try { 6324 IAudioService iAudioService = IAudioService.Stub.asInterface( 6325 ServiceManager.getService(Context.AUDIO_SERVICE)); 6326 iAudioService.setMasterMute(on, 0, mContext.getPackageName(), userId); 6327 } catch (RemoteException re) { 6328 Slog.e(LOG_TAG, "Failed to setMasterMute", re); 6329 } finally { 6330 mInjector.binderRestoreCallingIdentity(identity); 6331 } 6332 } 6333 } 6334 6335 @Override 6336 public boolean isMasterVolumeMuted(ComponentName who) { 6337 Preconditions.checkNotNull(who, "ComponentName is null"); 6338 synchronized (this) { 6339 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6340 6341 AudioManager audioManager = 6342 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 6343 return audioManager.isMasterMute(); 6344 } 6345 } 6346 6347 @Override 6348 public void setUserIcon(ComponentName who, Bitmap icon) { 6349 synchronized (this) { 6350 Preconditions.checkNotNull(who, "ComponentName is null"); 6351 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6352 6353 int userId = UserHandle.getCallingUserId(); 6354 long id = mInjector.binderClearCallingIdentity(); 6355 try { 6356 mUserManager.setUserIcon(userId, icon); 6357 } finally { 6358 mInjector.binderRestoreCallingIdentity(id); 6359 } 6360 } 6361 } 6362 6363 @Override 6364 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) { 6365 Preconditions.checkNotNull(who, "ComponentName is null"); 6366 synchronized (this) { 6367 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6368 } 6369 final int userId = UserHandle.getCallingUserId(); 6370 LockPatternUtils utils = new LockPatternUtils(mContext); 6371 6372 long ident = mInjector.binderClearCallingIdentity(); 6373 try { 6374 // disallow disabling the keyguard if a password is currently set 6375 if (disabled && utils.isSecure(userId)) { 6376 return false; 6377 } 6378 utils.setLockScreenDisabled(disabled, userId); 6379 } finally { 6380 mInjector.binderRestoreCallingIdentity(ident); 6381 } 6382 return true; 6383 } 6384 6385 @Override 6386 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) { 6387 int userId = UserHandle.getCallingUserId(); 6388 synchronized (this) { 6389 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6390 DevicePolicyData policy = getUserData(userId); 6391 if (policy.mStatusBarDisabled != disabled) { 6392 if (!setStatusBarDisabledInternal(disabled, userId)) { 6393 return false; 6394 } 6395 policy.mStatusBarDisabled = disabled; 6396 saveSettingsLocked(userId); 6397 } 6398 } 6399 return true; 6400 } 6401 6402 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) { 6403 long ident = mInjector.binderClearCallingIdentity(); 6404 try { 6405 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 6406 ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); 6407 if (statusBarService != null) { 6408 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE; 6409 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE; 6410 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId); 6411 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId); 6412 return true; 6413 } 6414 } catch (RemoteException e) { 6415 Slog.e(LOG_TAG, "Failed to disable the status bar", e); 6416 } finally { 6417 mInjector.binderRestoreCallingIdentity(ident); 6418 } 6419 return false; 6420 } 6421 6422 /** 6423 * We need to update the internal state of whether a user has completed setup once. After 6424 * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes 6425 * as we don't trust any apps that might try to reset it. 6426 * <p> 6427 * Unfortunately, we don't know which user's setup state was changed, so we write all of 6428 * them. 6429 */ 6430 void updateUserSetupComplete() { 6431 List<UserInfo> users = mUserManager.getUsers(true); 6432 final int N = users.size(); 6433 for (int i = 0; i < N; i++) { 6434 int userHandle = users.get(i).id; 6435 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 6436 userHandle) != 0) { 6437 DevicePolicyData policy = getUserData(userHandle); 6438 if (!policy.mUserSetupComplete) { 6439 policy.mUserSetupComplete = true; 6440 synchronized (this) { 6441 saveSettingsLocked(userHandle); 6442 } 6443 } 6444 } 6445 } 6446 } 6447 6448 private class SetupContentObserver extends ContentObserver { 6449 6450 private final Uri mUserSetupComplete = Settings.Secure.getUriFor( 6451 Settings.Secure.USER_SETUP_COMPLETE); 6452 6453 public SetupContentObserver(Handler handler) { 6454 super(handler); 6455 } 6456 6457 void register(ContentResolver resolver) { 6458 resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL); 6459 } 6460 6461 @Override 6462 public void onChange(boolean selfChange, Uri uri) { 6463 if (mUserSetupComplete.equals(uri)) { 6464 updateUserSetupComplete(); 6465 } 6466 } 6467 } 6468 6469 @VisibleForTesting 6470 final class LocalService extends DevicePolicyManagerInternal { 6471 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners; 6472 6473 @Override 6474 public List<String> getCrossProfileWidgetProviders(int profileId) { 6475 synchronized (DevicePolicyManagerService.this) { 6476 if (mOwners == null) { 6477 return Collections.emptyList(); 6478 } 6479 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId); 6480 if (ownerComponent == null) { 6481 return Collections.emptyList(); 6482 } 6483 6484 DevicePolicyData policy = getUserDataUnchecked(profileId); 6485 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent); 6486 6487 if (admin == null || admin.crossProfileWidgetProviders == null 6488 || admin.crossProfileWidgetProviders.isEmpty()) { 6489 return Collections.emptyList(); 6490 } 6491 6492 return admin.crossProfileWidgetProviders; 6493 } 6494 } 6495 6496 @Override 6497 public void addOnCrossProfileWidgetProvidersChangeListener( 6498 OnCrossProfileWidgetProvidersChangeListener listener) { 6499 synchronized (DevicePolicyManagerService.this) { 6500 if (mWidgetProviderListeners == null) { 6501 mWidgetProviderListeners = new ArrayList<>(); 6502 } 6503 if (!mWidgetProviderListeners.contains(listener)) { 6504 mWidgetProviderListeners.add(listener); 6505 } 6506 } 6507 } 6508 6509 @Override 6510 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) { 6511 final int userId = UserHandle.getUserId(uid); 6512 synchronized(DevicePolicyManagerService.this) { 6513 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null; 6514 } 6515 } 6516 6517 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) { 6518 final List<OnCrossProfileWidgetProvidersChangeListener> listeners; 6519 synchronized (DevicePolicyManagerService.this) { 6520 listeners = new ArrayList<>(mWidgetProviderListeners); 6521 } 6522 final int listenerCount = listeners.size(); 6523 for (int i = 0; i < listenerCount; i++) { 6524 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i); 6525 listener.onCrossProfileWidgetProvidersChanged(userId, packages); 6526 } 6527 } 6528 } 6529 6530 /** 6531 * Returns true if specified admin is allowed to limit passwords and has a 6532 * {@code passwordQuality} of at least {@code minPasswordQuality} 6533 */ 6534 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) { 6535 if (admin.passwordQuality < minPasswordQuality) { 6536 return false; 6537 } 6538 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 6539 } 6540 6541 @Override 6542 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) { 6543 if (policy != null && !policy.isValid()) { 6544 throw new IllegalArgumentException("Invalid system update policy."); 6545 } 6546 synchronized (this) { 6547 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6548 if (policy == null) { 6549 mOwners.clearSystemUpdatePolicy(); 6550 } else { 6551 mOwners.setSystemUpdatePolicy(policy); 6552 } 6553 mOwners.writeDeviceOwner(); 6554 } 6555 mContext.sendBroadcastAsUser( 6556 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED), 6557 UserHandle.SYSTEM); 6558 } 6559 6560 @Override 6561 public SystemUpdatePolicy getSystemUpdatePolicy() { 6562 synchronized (this) { 6563 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 6564 if (policy != null && !policy.isValid()) { 6565 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead."); 6566 return null; 6567 } 6568 return policy; 6569 } 6570 } 6571 6572 /** 6573 * Checks if the caller of the method is the device owner app. 6574 * 6575 * @param callerUid UID of the caller. 6576 * @return true if the caller is the device owner app 6577 */ 6578 @VisibleForTesting 6579 boolean isCallerDeviceOwner(int callerUid) { 6580 synchronized (this) { 6581 if (!mOwners.hasDeviceOwner()) { 6582 return false; 6583 } 6584 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) { 6585 return false; 6586 } 6587 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent() 6588 .getPackageName(); 6589 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid); 6590 6591 for (String pkg : pkgs) { 6592 if (deviceOwnerPackageName.equals(pkg)) { 6593 return true; 6594 } 6595 } 6596 } 6597 6598 return false; 6599 } 6600 6601 @Override 6602 public void notifyPendingSystemUpdate(long updateReceivedTime) { 6603 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE, 6604 "Only the system update service can broadcast update information"); 6605 6606 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 6607 Slog.w(LOG_TAG, "Only the system update service in the system user " + 6608 "can broadcast update information."); 6609 return; 6610 } 6611 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE); 6612 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME, 6613 updateReceivedTime); 6614 6615 synchronized (this) { 6616 final String deviceOwnerPackage = getDeviceOwner() == null ? null : 6617 getDeviceOwner().getPackageName(); 6618 if (deviceOwnerPackage == null) { 6619 return; 6620 } 6621 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId()); 6622 6623 ActivityInfo[] receivers = null; 6624 try { 6625 receivers = mContext.getPackageManager().getPackageInfo( 6626 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers; 6627 } catch (NameNotFoundException e) { 6628 Log.e(LOG_TAG, "Cannot find device owner package", e); 6629 } 6630 if (receivers != null) { 6631 long ident = mInjector.binderClearCallingIdentity(); 6632 try { 6633 for (int i = 0; i < receivers.length; i++) { 6634 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) { 6635 intent.setComponent(new ComponentName(deviceOwnerPackage, 6636 receivers[i].name)); 6637 mContext.sendBroadcastAsUser(intent, deviceOwnerUser); 6638 } 6639 } 6640 } finally { 6641 mInjector.binderRestoreCallingIdentity(ident); 6642 } 6643 } 6644 } 6645 } 6646 6647 @Override 6648 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException { 6649 int userId = UserHandle.getCallingUserId(); 6650 synchronized (this) { 6651 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6652 DevicePolicyData userPolicy = getUserData(userId); 6653 if (userPolicy.mPermissionPolicy != policy) { 6654 userPolicy.mPermissionPolicy = policy; 6655 saveSettingsLocked(userId); 6656 } 6657 } 6658 } 6659 6660 @Override 6661 public int getPermissionPolicy(ComponentName admin) throws RemoteException { 6662 int userId = UserHandle.getCallingUserId(); 6663 synchronized (this) { 6664 DevicePolicyData userPolicy = getUserData(userId); 6665 return userPolicy.mPermissionPolicy; 6666 } 6667 } 6668 6669 @Override 6670 public boolean setPermissionGrantState(ComponentName admin, String packageName, 6671 String permission, int grantState) throws RemoteException { 6672 UserHandle user = mInjector.binderGetCallingUserHandle(); 6673 synchronized (this) { 6674 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6675 long ident = mInjector.binderClearCallingIdentity(); 6676 try { 6677 if (getTargetSdk(packageName, user.getIdentifier()) 6678 < android.os.Build.VERSION_CODES.M) { 6679 return false; 6680 } 6681 final PackageManager packageManager = mContext.getPackageManager(); 6682 switch (grantState) { 6683 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: { 6684 packageManager.grantRuntimePermission(packageName, permission, user); 6685 packageManager.updatePermissionFlags(permission, packageName, 6686 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 6687 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 6688 } break; 6689 6690 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: { 6691 packageManager.revokeRuntimePermission(packageName, 6692 permission, user); 6693 packageManager.updatePermissionFlags(permission, packageName, 6694 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 6695 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 6696 } break; 6697 6698 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: { 6699 packageManager.updatePermissionFlags(permission, packageName, 6700 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user); 6701 } break; 6702 } 6703 return true; 6704 } catch (SecurityException se) { 6705 return false; 6706 } finally { 6707 mInjector.binderRestoreCallingIdentity(ident); 6708 } 6709 } 6710 } 6711 6712 @Override 6713 public int getPermissionGrantState(ComponentName admin, String packageName, 6714 String permission) throws RemoteException { 6715 PackageManager packageManager = mContext.getPackageManager(); 6716 6717 UserHandle user = mInjector.binderGetCallingUserHandle(); 6718 synchronized (this) { 6719 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6720 long ident = mInjector.binderClearCallingIdentity(); 6721 try { 6722 int granted = mIPackageManager.checkPermission(permission, 6723 packageName, user.getIdentifier()); 6724 int permFlags = packageManager.getPermissionFlags(permission, packageName, user); 6725 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) 6726 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) { 6727 // Not controlled by policy 6728 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT; 6729 } else { 6730 // Policy controlled so return result based on permission grant state 6731 return granted == PackageManager.PERMISSION_GRANTED 6732 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 6733 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED; 6734 } 6735 } finally { 6736 mInjector.binderRestoreCallingIdentity(ident); 6737 } 6738 } 6739 } 6740 6741 boolean isPackageInstalledForUser(String packageName, int userHandle) { 6742 try { 6743 PackageInfo pi = mIPackageManager.getPackageInfo(packageName, 0, userHandle); 6744 return (pi != null) && (pi.applicationInfo.flags != 0); 6745 } catch (RemoteException re) { 6746 throw new RuntimeException("Package manager has died", re); 6747 } 6748 } 6749 6750 @Override 6751 public boolean isProvisioningAllowed(String action) { 6752 final int callingUserId = mInjector.userHandleGetCallingUserId(); 6753 if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) { 6754 if (mOwners.hasDeviceOwner()) { 6755 if (!mInjector.userManagerIsSplitSystemUser()) { 6756 // Only split-system-user systems support managed-profiles in combination with 6757 // device-owner. 6758 return false; 6759 } 6760 if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) { 6761 // Only system device-owner supports managed-profiles. Non-system device-owner 6762 // doesn't. 6763 return false; 6764 } 6765 if (callingUserId == UserHandle.USER_SYSTEM) { 6766 // Managed-profiles cannot be setup on the system user, only regular users. 6767 return false; 6768 } 6769 } 6770 if (getProfileOwner(callingUserId) != null) { 6771 // Managed user cannot have a managed profile. 6772 return false; 6773 } 6774 try { 6775 if (!mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS)) { 6776 return false; 6777 } 6778 } catch (RemoteException e) { 6779 return false; 6780 } 6781 final long ident = mInjector.binderClearCallingIdentity(); 6782 try { 6783 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) { 6784 return false; 6785 } 6786 } finally { 6787 mInjector.binderRestoreCallingIdentity(ident); 6788 } 6789 return true; 6790 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) { 6791 return isDeviceOwnerProvisioningAllowed(callingUserId); 6792 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) { 6793 if (!mInjector.userManagerIsSplitSystemUser()) { 6794 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems. 6795 return false; 6796 } 6797 if (hasUserSetupCompleted(callingUserId)) { 6798 return false; 6799 } 6800 return true; 6801 } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) { 6802 if (!mInjector.userManagerIsSplitSystemUser()) { 6803 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems. 6804 return false; 6805 } 6806 return isDeviceOwnerProvisioningAllowed(callingUserId); 6807 } 6808 throw new IllegalArgumentException("Unknown provisioning action " + action); 6809 } 6810 6811 private boolean isDeviceOwnerProvisioningAllowed(int callingUserId) { 6812 if (mOwners.hasDeviceOwner()) { 6813 return false; 6814 } 6815 if (getProfileOwner(callingUserId) != null) { 6816 return false; 6817 } 6818 if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0) { 6819 return false; 6820 } 6821 if (callingUserId != UserHandle.USER_SYSTEM) { 6822 // Device owner provisioning can only be initiated from system user. 6823 return false; 6824 } 6825 return true; 6826 } 6827 6828 /** 6829 * Returns the target sdk version number that the given packageName was built for 6830 * in the given user. 6831 */ 6832 private int getTargetSdk(String packageName, int userId) throws RemoteException { 6833 final ApplicationInfo ai = mIPackageManager 6834 .getApplicationInfo(packageName, 0, userId); 6835 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion; 6836 return targetSdkVersion; 6837 } 6838} 6839