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