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