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