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