1 /* 2 * Copyright (C) 2015 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 17 package com.android.server.pm; 18 19 import android.annotation.NonNull; 20 import android.annotation.Nullable; 21 import android.app.ActivityManager; 22 import android.app.AppGlobals; 23 import android.content.ContentResolver; 24 import android.content.Context; 25 import android.content.Intent; 26 import android.content.pm.ApplicationInfo; 27 import android.content.pm.IPackageManager; 28 import android.content.pm.PackageManager; 29 import android.content.pm.PackageManagerInternal; 30 import android.hardware.display.AmbientDisplayConfiguration; 31 import android.os.Binder; 32 import android.os.Bundle; 33 import android.os.Process; 34 import android.os.RemoteException; 35 import android.os.UserHandle; 36 import android.os.UserManager; 37 import android.provider.Settings; 38 import android.telephony.SubscriptionInfo; 39 import android.telephony.SubscriptionManager; 40 import android.util.Log; 41 import android.util.Slog; 42 import android.util.SparseArray; 43 44 import com.android.internal.util.Preconditions; 45 import com.android.internal.util.XmlUtils; 46 import com.android.modules.utils.TypedXmlPullParser; 47 import com.android.modules.utils.TypedXmlSerializer; 48 import com.android.server.BundleUtils; 49 import com.android.server.LocalServices; 50 51 import com.google.android.collect.Sets; 52 53 import org.xmlpull.v1.XmlPullParser; 54 import org.xmlpull.v1.XmlSerializer; 55 56 import java.io.IOException; 57 import java.io.PrintWriter; 58 import java.util.List; 59 import java.util.Objects; 60 import java.util.Set; 61 62 /** 63 * Utility methods for user restrictions. 64 * 65 * <p>See {@link UserManagerService} for the method suffixes. 66 */ 67 public class UserRestrictionsUtils { 68 private static final String TAG = "UserRestrictionsUtils"; 69 UserRestrictionsUtils()70 private UserRestrictionsUtils() { 71 } 72 newSetWithUniqueCheck(String[] strings)73 private static Set<String> newSetWithUniqueCheck(String[] strings) { 74 final Set<String> ret = Sets.newArraySet(strings); 75 76 // Make sure there's no overlap. 77 Preconditions.checkState(ret.size() == strings.length); 78 return ret; 79 } 80 81 public static final Set<String> USER_RESTRICTIONS = newSetWithUniqueCheck(new String[] { 82 UserManager.DISALLOW_CONFIG_WIFI, 83 UserManager.DISALLOW_CONFIG_LOCALE, 84 UserManager.DISALLOW_MODIFY_ACCOUNTS, 85 UserManager.DISALLOW_INSTALL_APPS, 86 UserManager.DISALLOW_UNINSTALL_APPS, 87 UserManager.DISALLOW_SHARE_LOCATION, 88 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 89 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, 90 UserManager.DISALLOW_CONFIG_BLUETOOTH, 91 UserManager.DISALLOW_BLUETOOTH, 92 UserManager.DISALLOW_BLUETOOTH_SHARING, 93 UserManager.DISALLOW_USB_FILE_TRANSFER, 94 UserManager.DISALLOW_CONFIG_CREDENTIALS, 95 UserManager.DISALLOW_REMOVE_USER, 96 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 97 UserManager.DISALLOW_DEBUGGING_FEATURES, 98 UserManager.DISALLOW_CONFIG_VPN, 99 UserManager.DISALLOW_CONFIG_DATE_TIME, 100 UserManager.DISALLOW_CONFIG_TETHERING, 101 UserManager.DISALLOW_NETWORK_RESET, 102 UserManager.DISALLOW_FACTORY_RESET, 103 UserManager.DISALLOW_ADD_USER, 104 UserManager.DISALLOW_ADD_MANAGED_PROFILE, 105 UserManager.DISALLOW_ADD_CLONE_PROFILE, 106 UserManager.ENSURE_VERIFY_APPS, 107 UserManager.DISALLOW_CONFIG_CELL_BROADCASTS, 108 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS, 109 UserManager.DISALLOW_APPS_CONTROL, 110 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA, 111 UserManager.DISALLOW_UNMUTE_MICROPHONE, 112 UserManager.DISALLOW_ADJUST_VOLUME, 113 UserManager.DISALLOW_OUTGOING_CALLS, 114 UserManager.DISALLOW_SMS, 115 UserManager.DISALLOW_FUN, 116 UserManager.DISALLOW_CREATE_WINDOWS, 117 UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS, 118 UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE, 119 UserManager.DISALLOW_OUTGOING_BEAM, 120 UserManager.DISALLOW_WALLPAPER, 121 UserManager.DISALLOW_SAFE_BOOT, 122 UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 123 UserManager.DISALLOW_RECORD_AUDIO, 124 UserManager.DISALLOW_CAMERA, 125 UserManager.DISALLOW_RUN_IN_BACKGROUND, 126 UserManager.DISALLOW_DATA_ROAMING, 127 UserManager.DISALLOW_SET_USER_ICON, 128 UserManager.DISALLOW_SET_WALLPAPER, 129 UserManager.DISALLOW_OEM_UNLOCK, 130 UserManager.DISALLOW_UNMUTE_DEVICE, 131 UserManager.DISALLOW_AUTOFILL, 132 UserManager.DISALLOW_CONTENT_CAPTURE, 133 UserManager.DISALLOW_CONTENT_SUGGESTIONS, 134 UserManager.DISALLOW_USER_SWITCH, 135 UserManager.DISALLOW_UNIFIED_PASSWORD, 136 UserManager.DISALLOW_CONFIG_LOCATION, 137 UserManager.DISALLOW_AIRPLANE_MODE, 138 UserManager.DISALLOW_CONFIG_BRIGHTNESS, 139 UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, 140 UserManager.DISALLOW_AMBIENT_DISPLAY, 141 UserManager.DISALLOW_CONFIG_SCREEN_TIMEOUT, 142 UserManager.DISALLOW_PRINTING, 143 UserManager.DISALLOW_CONFIG_PRIVATE_DNS, 144 UserManager.DISALLOW_MICROPHONE_TOGGLE, 145 UserManager.DISALLOW_CAMERA_TOGGLE, 146 UserManager.DISALLOW_CHANGE_WIFI_STATE, 147 UserManager.DISALLOW_WIFI_TETHERING, 148 UserManager.DISALLOW_GRANT_ADMIN, 149 UserManager.DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI, 150 UserManager.DISALLOW_WIFI_DIRECT, 151 UserManager.DISALLOW_ADD_WIFI_CONFIG, 152 UserManager.DISALLOW_CELLULAR_2G, 153 UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO, 154 UserManager.DISALLOW_CONFIG_DEFAULT_APPS 155 }); 156 157 public static final Set<String> DEPRECATED_USER_RESTRICTIONS = Sets.newArraySet( 158 UserManager.DISALLOW_ADD_MANAGED_PROFILE, 159 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE 160 ); 161 162 /** 163 * Set of user restriction which we don't want to persist. 164 */ 165 private static final Set<String> NON_PERSIST_USER_RESTRICTIONS = Sets.newArraySet( 166 UserManager.DISALLOW_RECORD_AUDIO 167 ); 168 169 /** 170 * User restrictions that can only be set by profile owners on the main user, or by device 171 * owners. When set by DO they will be applied to all users. 172 */ 173 private static final Set<String> MAIN_USER_ONLY_RESTRICTIONS = Sets.newArraySet( 174 UserManager.DISALLOW_BLUETOOTH, 175 UserManager.DISALLOW_USB_FILE_TRANSFER, 176 UserManager.DISALLOW_CONFIG_TETHERING, 177 UserManager.DISALLOW_NETWORK_RESET, 178 UserManager.DISALLOW_FACTORY_RESET, 179 UserManager.DISALLOW_ADD_USER, 180 UserManager.DISALLOW_CONFIG_CELL_BROADCASTS, 181 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS, 182 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA, 183 UserManager.DISALLOW_SMS, 184 UserManager.DISALLOW_FUN, 185 UserManager.DISALLOW_SAFE_BOOT, 186 UserManager.DISALLOW_CREATE_WINDOWS, 187 UserManager.DISALLOW_DATA_ROAMING, 188 UserManager.DISALLOW_AIRPLANE_MODE 189 ); 190 191 /** 192 * User restrictions that cannot be set by profile owners. Applied to all users. 193 */ 194 private static final Set<String> DEVICE_OWNER_ONLY_RESTRICTIONS = Sets.newArraySet( 195 UserManager.DISALLOW_USER_SWITCH, 196 UserManager.DISALLOW_CONFIG_PRIVATE_DNS, 197 UserManager.DISALLOW_MICROPHONE_TOGGLE, 198 UserManager.DISALLOW_CAMERA_TOGGLE, 199 UserManager.DISALLOW_CHANGE_WIFI_STATE, 200 UserManager.DISALLOW_WIFI_TETHERING, 201 UserManager.DISALLOW_WIFI_DIRECT, 202 UserManager.DISALLOW_ADD_WIFI_CONFIG, 203 UserManager.DISALLOW_CELLULAR_2G, 204 UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO 205 ); 206 207 /** 208 * User restrictions that can't be changed by device owner or profile owner. 209 */ 210 private static final Set<String> IMMUTABLE_BY_OWNERS = Sets.newArraySet( 211 UserManager.DISALLOW_RECORD_AUDIO, 212 UserManager.DISALLOW_WALLPAPER, 213 UserManager.DISALLOW_OEM_UNLOCK 214 ); 215 216 /** 217 * Special user restrictions that can be applied to a user as well as to all users globally, 218 * depending on callers. When device owner sets them, they'll be applied to all users. 219 */ 220 private static final Set<String> GLOBAL_RESTRICTIONS = Sets.newArraySet( 221 UserManager.DISALLOW_ADJUST_VOLUME, 222 UserManager.DISALLOW_BLUETOOTH_SHARING, 223 UserManager.DISALLOW_CONFIG_DATE_TIME, 224 UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS, 225 UserManager.DISALLOW_RUN_IN_BACKGROUND, 226 UserManager.DISALLOW_UNMUTE_MICROPHONE, 227 UserManager.DISALLOW_UNMUTE_DEVICE, 228 UserManager.DISALLOW_CAMERA 229 ); 230 231 /** 232 * Special user restrictions that profile owner of an organization-owned managed profile can 233 * set on the parent profile instance to apply them globally. 234 */ 235 private static final Set<String> PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS = 236 Sets.newArraySet( 237 UserManager.DISALLOW_AIRPLANE_MODE, 238 UserManager.DISALLOW_CONFIG_DATE_TIME, 239 UserManager.DISALLOW_CONFIG_PRIVATE_DNS, 240 UserManager.DISALLOW_CHANGE_WIFI_STATE, 241 UserManager.DISALLOW_DEBUGGING_FEATURES, 242 UserManager.DISALLOW_WIFI_TETHERING, 243 UserManager.DISALLOW_WIFI_DIRECT, 244 UserManager.DISALLOW_ADD_WIFI_CONFIG, 245 UserManager.DISALLOW_CELLULAR_2G, 246 UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO 247 ); 248 249 /** 250 * Special user restrictions that profile owner of an organization-owned managed profile can 251 * set on the parent profile instance to apply them on the personal profile. 252 */ 253 private static final Set<String> PROFILE_OWNER_ORGANIZATION_OWNED_LOCAL_RESTRICTIONS = 254 Sets.newArraySet( 255 UserManager.DISALLOW_CONFIG_BLUETOOTH, 256 UserManager.DISALLOW_CONFIG_LOCATION, 257 UserManager.DISALLOW_CONFIG_WIFI, 258 UserManager.DISALLOW_CONTENT_CAPTURE, 259 UserManager.DISALLOW_CONTENT_SUGGESTIONS, 260 UserManager.DISALLOW_DEBUGGING_FEATURES, 261 UserManager.DISALLOW_SHARE_LOCATION, 262 UserManager.DISALLOW_OUTGOING_CALLS, 263 UserManager.DISALLOW_CAMERA, 264 UserManager.DISALLOW_BLUETOOTH, 265 UserManager.DISALLOW_BLUETOOTH_SHARING, 266 UserManager.DISALLOW_CONFIG_CELL_BROADCASTS, 267 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS, 268 UserManager.DISALLOW_CONFIG_TETHERING, 269 UserManager.DISALLOW_DATA_ROAMING, 270 UserManager.DISALLOW_SAFE_BOOT, 271 UserManager.DISALLOW_SMS, 272 UserManager.DISALLOW_USB_FILE_TRANSFER, 273 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA, 274 UserManager.DISALLOW_UNMUTE_MICROPHONE 275 ); 276 277 /** 278 * User restrictions that default to {@code true} for managed profile owners. 279 * 280 * NB: {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} is also set by default but it is 281 * not set to existing profile owners unless they used to have INSTALL_NON_MARKET_APPS disabled 282 * in settings. So it is handled separately. 283 */ 284 private static final Set<String> DEFAULT_ENABLED_FOR_MANAGED_PROFILES = Sets.newArraySet( 285 UserManager.DISALLOW_BLUETOOTH_SHARING 286 ); 287 288 /** 289 * Special user restrictions that are always applied to all users no matter who sets them. 290 */ 291 private static final Set<String> PROFILE_GLOBAL_RESTRICTIONS = Sets.newArraySet( 292 UserManager.ENSURE_VERIFY_APPS, 293 UserManager.DISALLOW_AIRPLANE_MODE, 294 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY 295 ); 296 297 /** 298 * User restrictions available to a device owner whose type is 299 * {@link android.app.admin.DevicePolicyManager#DEVICE_OWNER_TYPE_FINANCED}. 300 */ 301 private static final Set<String> FINANCED_DEVICE_OWNER_RESTRICTIONS = Sets.newArraySet( 302 UserManager.DISALLOW_ADD_USER, 303 UserManager.DISALLOW_DEBUGGING_FEATURES, 304 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 305 UserManager.DISALLOW_SAFE_BOOT, 306 UserManager.DISALLOW_CONFIG_DATE_TIME, 307 UserManager.DISALLOW_OUTGOING_CALLS 308 ); 309 310 /** 311 * Returns whether the given restriction name is valid (and logs it if it isn't). 312 */ isValidRestriction(@onNull String restriction)313 public static boolean isValidRestriction(@NonNull String restriction) { 314 if (!USER_RESTRICTIONS.contains(restriction)) { 315 // Log this, with severity depending on the source. 316 final int uid = Binder.getCallingUid(); 317 String[] pkgs = null; 318 try { 319 pkgs = AppGlobals.getPackageManager().getPackagesForUid(uid); 320 } catch (RemoteException e) { 321 // Ignore 322 } 323 StringBuilder msg = new StringBuilder("Unknown restriction queried by uid "); 324 msg.append(uid); 325 if (pkgs != null && pkgs.length > 0) { 326 msg.append(" ("); 327 msg.append(pkgs[0]); 328 if (pkgs.length > 1) { 329 msg.append(" et al"); 330 } 331 msg.append(")"); 332 } 333 msg.append(": "); 334 msg.append(restriction); 335 if (restriction != null && isSystemApp(uid, pkgs)) { 336 Slog.wtf(TAG, msg.toString()); 337 } else { 338 Slog.e(TAG, msg.toString()); 339 } 340 return false; 341 } 342 return true; 343 } 344 345 /** Returns whether the given uid (or corresponding packageList) is for a System app. */ isSystemApp(int uid, String[] packageList)346 private static boolean isSystemApp(int uid, String[] packageList) { 347 if (UserHandle.isCore(uid)) { 348 return true; 349 } 350 if (packageList == null) { 351 return false; 352 } 353 final IPackageManager pm = AppGlobals.getPackageManager(); 354 for (int i = 0; i < packageList.length; i++) { 355 try { 356 final int flags = PackageManager.MATCH_UNINSTALLED_PACKAGES 357 | PackageManager.MATCH_DIRECT_BOOT_AWARE 358 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 359 final ApplicationInfo appInfo = 360 pm.getApplicationInfo(packageList[i], flags, UserHandle.getUserId(uid)); 361 if (appInfo != null && appInfo.isSystemApp()) { 362 return true; 363 } 364 } catch (RemoteException e) { 365 // Ignore 366 } 367 } 368 return false; 369 } 370 writeRestrictions(@onNull XmlSerializer serializer, @Nullable Bundle restrictions, @NonNull String tag)371 public static void writeRestrictions(@NonNull XmlSerializer serializer, 372 @Nullable Bundle restrictions, @NonNull String tag) throws IOException { 373 writeRestrictions(XmlUtils.makeTyped(serializer), restrictions, tag); 374 } 375 writeRestrictions(@onNull TypedXmlSerializer serializer, @Nullable Bundle restrictions, @NonNull String tag)376 public static void writeRestrictions(@NonNull TypedXmlSerializer serializer, 377 @Nullable Bundle restrictions, @NonNull String tag) throws IOException { 378 if (restrictions == null) { 379 return; 380 } 381 382 serializer.startTag(null, tag); 383 for (String key : restrictions.keySet()) { 384 if (NON_PERSIST_USER_RESTRICTIONS.contains(key)) { 385 continue; // Don't persist. 386 } 387 if (USER_RESTRICTIONS.contains(key)) { 388 if (restrictions.getBoolean(key)) { 389 serializer.attributeBoolean(null, key, true); 390 } 391 continue; 392 } 393 Log.w(TAG, "Unknown user restriction detected: " + key); 394 } 395 serializer.endTag(null, tag); 396 } 397 readRestrictions(XmlPullParser parser, Bundle restrictions)398 public static void readRestrictions(XmlPullParser parser, Bundle restrictions) { 399 readRestrictions(XmlUtils.makeTyped(parser), restrictions); 400 } 401 readRestrictions(TypedXmlPullParser parser, Bundle restrictions)402 public static void readRestrictions(TypedXmlPullParser parser, Bundle restrictions) { 403 restrictions.clear(); 404 for (String key : USER_RESTRICTIONS) { 405 final boolean value = parser.getAttributeBoolean(null, key, false); 406 if (value) { 407 restrictions.putBoolean(key, true); 408 } 409 } 410 } 411 readRestrictions(XmlPullParser parser)412 public static Bundle readRestrictions(XmlPullParser parser) { 413 return readRestrictions(XmlUtils.makeTyped(parser)); 414 } 415 readRestrictions(TypedXmlPullParser parser)416 public static Bundle readRestrictions(TypedXmlPullParser parser) { 417 final Bundle result = new Bundle(); 418 readRestrictions(parser, result); 419 return result; 420 } 421 422 /** 423 * @return {@code in} itself when it's not null, or an empty bundle (which can writable). 424 */ nonNull(@ullable Bundle in)425 public static Bundle nonNull(@Nullable Bundle in) { 426 return in != null ? in : new Bundle(); 427 } 428 429 /** 430 * Returns {@code true} if given bundle is not null and contains {@code true} for a given 431 * restriction. 432 */ contains(@ullable Bundle in, String restriction)433 public static boolean contains(@Nullable Bundle in, String restriction) { 434 return in != null && in.getBoolean(restriction); 435 } 436 merge(@onNull Bundle dest, @Nullable Bundle in)437 public static void merge(@NonNull Bundle dest, @Nullable Bundle in) { 438 Objects.requireNonNull(dest); 439 Preconditions.checkArgument(dest != in); 440 if (in == null) { 441 return; 442 } 443 for (String key : in.keySet()) { 444 if (in.getBoolean(key, false)) { 445 dest.putBoolean(key, true); 446 } 447 } 448 } 449 450 /** 451 * @return true if a restriction is settable by device owner. 452 */ canDeviceOwnerChange(String restriction)453 public static boolean canDeviceOwnerChange(String restriction) { 454 return !IMMUTABLE_BY_OWNERS.contains(restriction); 455 } 456 457 /** 458 * @return true if a restriction is settable by profile owner. Note it takes a boolean to say 459 * if the relevant user is the {@link UserManager#isMainUser() MainUser}, because some 460 * restrictions can be changed by PO only when it's running on the main user. 461 */ canProfileOwnerChange(String restriction, boolean isMainUser)462 public static boolean canProfileOwnerChange(String restriction, boolean isMainUser) { 463 return !IMMUTABLE_BY_OWNERS.contains(restriction) 464 && !DEVICE_OWNER_ONLY_RESTRICTIONS.contains(restriction) 465 && !(!isMainUser && MAIN_USER_ONLY_RESTRICTIONS.contains(restriction)); 466 } 467 468 /** 469 * @return true if a restriction is settable by profile owner of an organization owned device. 470 */ canProfileOwnerOfOrganizationOwnedDeviceChange(String restriction)471 public static boolean canProfileOwnerOfOrganizationOwnedDeviceChange(String restriction) { 472 return PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS.contains(restriction) 473 || PROFILE_OWNER_ORGANIZATION_OWNED_LOCAL_RESTRICTIONS.contains(restriction); 474 } 475 476 /** 477 * Returns the user restrictions that default to {@code true} for managed profile owners. 478 */ getDefaultEnabledForManagedProfiles()479 public static @NonNull Set<String> getDefaultEnabledForManagedProfiles() { 480 return DEFAULT_ENABLED_FOR_MANAGED_PROFILES; 481 } 482 483 /** 484 * @return {@code true} only if the restriction is allowed for financed devices and can be set 485 * by a device owner. Otherwise, {@code false} would be returned. 486 */ canFinancedDeviceOwnerChange(String restriction)487 public static boolean canFinancedDeviceOwnerChange(String restriction) { 488 return FINANCED_DEVICE_OWNER_RESTRICTIONS.contains(restriction) 489 && canDeviceOwnerChange(restriction); 490 } 491 492 /** 493 * Whether given user restriction should be enforced globally. 494 */ isGlobal(@serManagerInternal.OwnerType int restrictionOwnerType, String key)495 public static boolean isGlobal(@UserManagerInternal.OwnerType int restrictionOwnerType, 496 String key) { 497 return ((restrictionOwnerType == UserManagerInternal.OWNER_TYPE_DEVICE_OWNER) && ( 498 MAIN_USER_ONLY_RESTRICTIONS.contains(key) || GLOBAL_RESTRICTIONS.contains(key))) 499 || ((restrictionOwnerType 500 == UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE) 501 && PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS.contains(key)) 502 || PROFILE_GLOBAL_RESTRICTIONS.contains(key) 503 || DEVICE_OWNER_ONLY_RESTRICTIONS.contains(key); 504 } 505 506 /** 507 * Whether given user restriction should be enforced locally. 508 */ isLocal(@serManagerInternal.OwnerType int restrictionOwnerType, String key)509 public static boolean isLocal(@UserManagerInternal.OwnerType int restrictionOwnerType, 510 String key) { 511 return !isGlobal(restrictionOwnerType, key); 512 } 513 514 /** 515 * @return true if two Bundles contain the same user restriction. 516 * A null bundle and an empty bundle are considered to be equal. 517 */ areEqual(@ullable Bundle a, @Nullable Bundle b)518 public static boolean areEqual(@Nullable Bundle a, @Nullable Bundle b) { 519 if (a == b) { 520 return true; 521 } 522 if (BundleUtils.isEmpty(a)) { 523 return BundleUtils.isEmpty(b); 524 } 525 if (BundleUtils.isEmpty(b)) { 526 return false; 527 } 528 for (String key : a.keySet()) { 529 if (a.getBoolean(key) != b.getBoolean(key)) { 530 return false; 531 } 532 } 533 for (String key : b.keySet()) { 534 if (a.getBoolean(key) != b.getBoolean(key)) { 535 return false; 536 } 537 } 538 return true; 539 } 540 541 /** 542 * Takes a new use restriction set and the previous set, and apply the restrictions that have 543 * changed. 544 * 545 * <p>Note this method is called by {@link UserManagerService} without holding any locks. 546 */ applyUserRestrictions(Context context, int userId, Bundle newRestrictions, Bundle prevRestrictions)547 public static void applyUserRestrictions(Context context, int userId, 548 Bundle newRestrictions, Bundle prevRestrictions) { 549 for (String key : USER_RESTRICTIONS) { 550 final boolean newValue = newRestrictions.getBoolean(key); 551 final boolean prevValue = prevRestrictions.getBoolean(key); 552 553 if (newValue != prevValue) { 554 applyUserRestriction(context, userId, key, newValue); 555 } 556 } 557 } 558 559 /** 560 * Apply each user restriction. 561 * 562 * <p>See also {@link #isSettingRestrictedForUser()}, 563 * which should be in sync with this method. 564 */ applyUserRestriction(Context context, int userId, String key, boolean newValue)565 private static void applyUserRestriction(Context context, int userId, String key, 566 boolean newValue) { 567 if (UserManagerService.DBG) { 568 Log.d(TAG, "Applying user restriction: userId=" + userId 569 + " key=" + key + " value=" + newValue); 570 } 571 // When certain restrictions are cleared, we don't update the system settings, 572 // because these settings are changeable on the Settings UI and we don't know the original 573 // value -- for example LOCATION_MODE might have been off already when the restriction was 574 // set, and in that case even if the restriction is lifted, changing it to ON would be 575 // wrong. So just don't do anything in such a case. If the user hopes to enable location 576 // later, they can do it on the Settings UI. 577 // WARNING: Remember that Settings.Global and Settings.Secure are changeable via adb. 578 // To prevent this from happening for a given user restriction, you have to add a check to 579 // SettingsProvider.isGlobalOrSecureSettingRestrictedForUser. 580 581 final ContentResolver cr = context.getContentResolver(); 582 final long id = Binder.clearCallingIdentity(); 583 try { 584 switch (key) { 585 case UserManager.DISALLOW_DATA_ROAMING: 586 if (newValue) { 587 // DISALLOW_DATA_ROAMING user restriction is set. 588 589 // Multi sim device. 590 SubscriptionManager subscriptionManager = context 591 .getSystemService(SubscriptionManager.class); 592 final List<SubscriptionInfo> subscriptionInfoList = 593 subscriptionManager.getActiveSubscriptionInfoList(); 594 if (subscriptionInfoList != null) { 595 for (SubscriptionInfo subInfo : subscriptionInfoList) { 596 android.provider.Settings.Global.putStringForUser(cr, 597 android.provider.Settings.Global.DATA_ROAMING 598 + subInfo.getSubscriptionId(), "0", userId); 599 } 600 } 601 602 // Single sim device. 603 android.provider.Settings.Global.putStringForUser(cr, 604 android.provider.Settings.Global.DATA_ROAMING, "0", userId); 605 } 606 break; 607 case UserManager.DISALLOW_SHARE_LOCATION: 608 if (newValue) { 609 android.provider.Settings.Secure.putIntForUser(cr, 610 android.provider.Settings.Secure.LOCATION_MODE, 611 android.provider.Settings.Secure.LOCATION_MODE_OFF, 612 userId); 613 } 614 break; 615 case UserManager.DISALLOW_DEBUGGING_FEATURES: 616 if (newValue) { 617 // Only disable adb if changing for system user, since it is global 618 // TODO: should this be admin user? 619 if (userId == UserHandle.USER_SYSTEM) { 620 android.provider.Settings.Global.putStringForUser(cr, 621 android.provider.Settings.Global.ADB_ENABLED, "0", 622 userId); 623 android.provider.Settings.Global.putStringForUser(cr, 624 android.provider.Settings.Global.ADB_WIFI_ENABLED, "0", 625 userId); 626 } 627 } 628 break; 629 case UserManager.ENSURE_VERIFY_APPS: 630 if (newValue) { 631 android.provider.Settings.Global.putStringForUser( 632 context.getContentResolver(), 633 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1", 634 userId); 635 } 636 break; 637 case UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY: 638 setInstallMarketAppsRestriction(cr, userId, getNewUserRestrictionSetting( 639 context, userId, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 640 newValue)); 641 break; 642 case UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES: 643 // Since Android O, the secure setting is not available to be changed by the 644 // user. Hence, when the restriction is cleared, we need to reset the state of 645 // the setting to its default value which is now 1. 646 setInstallMarketAppsRestriction(cr, userId, getNewUserRestrictionSetting( 647 context, userId, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, 648 newValue)); 649 break; 650 case UserManager.DISALLOW_RUN_IN_BACKGROUND: 651 if (newValue) { 652 int currentUser = ActivityManager.getCurrentUser(); 653 if (currentUser != userId && userId != UserHandle.USER_SYSTEM) { 654 try { 655 ActivityManager.getService().stopUser(userId, false, null); 656 } catch (RemoteException e) { 657 throw e.rethrowAsRuntimeException(); 658 } 659 } 660 } 661 break; 662 case UserManager.DISALLOW_SAFE_BOOT: 663 // Unlike with the other restrictions, we want to propagate the new value to 664 // the system settings even if it is false. The other restrictions modify 665 // settings which could be manually changed by the user from the Settings app 666 // after the policies enforcing these restrictions have been revoked, so we 667 // leave re-setting of those settings to the user. 668 android.provider.Settings.Global.putInt( 669 context.getContentResolver(), 670 android.provider.Settings.Global.SAFE_BOOT_DISALLOWED, 671 newValue ? 1 : 0); 672 break; 673 case UserManager.DISALLOW_AIRPLANE_MODE: 674 if (newValue) { 675 final boolean airplaneMode = Settings.Global.getInt( 676 context.getContentResolver(), 677 Settings.Global.AIRPLANE_MODE_ON, 0) == 1; 678 if (airplaneMode) { 679 android.provider.Settings.Global.putInt( 680 context.getContentResolver(), 681 android.provider.Settings.Global.AIRPLANE_MODE_ON, 0); 682 // Post the intent. 683 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 684 intent.putExtra("state", false); 685 context.sendBroadcastAsUser(intent, UserHandle.ALL); 686 } 687 } 688 break; 689 case UserManager.DISALLOW_AMBIENT_DISPLAY: 690 if (newValue) { 691 final AmbientDisplayConfiguration config = 692 new AmbientDisplayConfiguration(context); 693 config.disableDozeSettings(userId); 694 } 695 break; 696 case UserManager.DISALLOW_APPS_CONTROL: 697 // Intentional fall-through 698 case UserManager.DISALLOW_UNINSTALL_APPS: 699 final PackageManagerInternal pmi = LocalServices.getService( 700 PackageManagerInternal.class); 701 pmi.removeAllNonSystemPackageSuspensions(userId); 702 pmi.removeAllDistractingPackageRestrictions(userId); 703 pmi.flushPackageRestrictions(userId); 704 break; 705 } 706 } finally { 707 Binder.restoreCallingIdentity(id); 708 } 709 } 710 isSettingRestrictedForUser(Context context, @NonNull String setting, int userId, String value, int callingUid)711 public static boolean isSettingRestrictedForUser(Context context, @NonNull String setting, 712 int userId, String value, int callingUid) { 713 Objects.requireNonNull(setting); 714 final UserManager mUserManager = context.getSystemService(UserManager.class); 715 String restriction; 716 boolean checkAllUser = false; 717 switch (setting) { 718 case android.provider.Settings.Secure.LOCATION_MODE: 719 if (mUserManager.hasUserRestriction( 720 UserManager.DISALLOW_CONFIG_LOCATION, UserHandle.of(userId)) 721 && callingUid != Process.SYSTEM_UID) { 722 return true; 723 } else if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) { 724 return false; 725 } 726 restriction = UserManager.DISALLOW_SHARE_LOCATION; 727 break; 728 729 case android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS: 730 if ("0".equals(value)) { 731 return false; 732 } 733 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES; 734 break; 735 736 case android.provider.Settings.Global.ADB_ENABLED: 737 case android.provider.Settings.Global.ADB_WIFI_ENABLED: 738 if ("0".equals(value)) { 739 return false; 740 } 741 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES; 742 break; 743 744 case android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB: 745 if ("1".equals(value)) { 746 return false; 747 } 748 restriction = UserManager.ENSURE_VERIFY_APPS; 749 break; 750 751 case android.provider.Settings.Global.PREFERRED_NETWORK_MODE: 752 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS; 753 break; 754 755 case android.provider.Settings.Secure.ALWAYS_ON_VPN_APP: 756 case android.provider.Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN: 757 case android.provider.Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN_WHITELIST: 758 // Allowlist system uid (ConnectivityService) and root uid to change always-on vpn 759 final int appId = UserHandle.getAppId(callingUid); 760 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) { 761 return false; 762 } 763 restriction = UserManager.DISALLOW_CONFIG_VPN; 764 break; 765 766 case android.provider.Settings.Global.SAFE_BOOT_DISALLOWED: 767 if ("1".equals(value)) { 768 return false; 769 } 770 restriction = UserManager.DISALLOW_SAFE_BOOT; 771 break; 772 773 case android.provider.Settings.Global.AIRPLANE_MODE_ON: 774 if ("0".equals(value)) { 775 return false; 776 } 777 restriction = UserManager.DISALLOW_AIRPLANE_MODE; 778 break; 779 780 case android.provider.Settings.Secure.DOZE_ENABLED: 781 case android.provider.Settings.Secure.DOZE_ALWAYS_ON: 782 case android.provider.Settings.Secure.DOZE_PICK_UP_GESTURE: 783 case android.provider.Settings.Secure.DOZE_PULSE_ON_LONG_PRESS: 784 case android.provider.Settings.Secure.DOZE_DOUBLE_TAP_GESTURE: 785 if ("0".equals(value)) { 786 return false; 787 } 788 restriction = UserManager.DISALLOW_AMBIENT_DISPLAY; 789 break; 790 791 case android.provider.Settings.System.SCREEN_BRIGHTNESS: 792 case android.provider.Settings.System.SCREEN_BRIGHTNESS_FLOAT: 793 case android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE: 794 if (callingUid == Process.SYSTEM_UID) { 795 return false; 796 } 797 restriction = UserManager.DISALLOW_CONFIG_BRIGHTNESS; 798 break; 799 800 case android.provider.Settings.Global.AUTO_TIME: 801 case android.provider.Settings.Global.AUTO_TIME_ZONE: 802 if (callingUid == Process.SYSTEM_UID) { 803 return false; 804 } 805 restriction = UserManager.DISALLOW_CONFIG_DATE_TIME; 806 break; 807 808 case android.provider.Settings.System.SCREEN_OFF_TIMEOUT: 809 if (callingUid == Process.SYSTEM_UID) { 810 return false; 811 } 812 restriction = UserManager.DISALLOW_CONFIG_SCREEN_TIMEOUT; 813 break; 814 815 case android.provider.Settings.Global.PRIVATE_DNS_MODE: 816 case android.provider.Settings.Global.PRIVATE_DNS_SPECIFIER: 817 if (callingUid == Process.SYSTEM_UID) { 818 return false; 819 } 820 restriction = UserManager.DISALLOW_CONFIG_PRIVATE_DNS; 821 break; 822 default: 823 if (setting.startsWith(Settings.Global.DATA_ROAMING)) { 824 if ("0".equals(value)) { 825 return false; 826 } 827 restriction = UserManager.DISALLOW_DATA_ROAMING; 828 break; 829 } 830 return false; 831 } 832 833 if (checkAllUser) { 834 return mUserManager.hasUserRestrictionOnAnyUser(restriction); 835 } else { 836 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId)); 837 } 838 } 839 dumpRestrictions(PrintWriter pw, String prefix, Bundle restrictions)840 public static void dumpRestrictions(PrintWriter pw, String prefix, Bundle restrictions) { 841 boolean noneSet = true; 842 if (restrictions != null) { 843 for (String key : restrictions.keySet()) { 844 if (restrictions.getBoolean(key, false)) { 845 pw.println(prefix + key); 846 noneSet = false; 847 } 848 } 849 if (noneSet) { 850 pw.println(prefix + "none"); 851 } 852 } else { 853 pw.println(prefix + "null"); 854 } 855 } 856 857 /** 858 * Moves a particular restriction from one array of restrictions sets to a restriction set, 859 * e.g. for all users. 860 */ moveRestriction(String restrictionKey, SparseArray<RestrictionsSet> sourceRestrictionsSets, RestrictionsSet destRestrictionSet)861 public static void moveRestriction(String restrictionKey, 862 SparseArray<RestrictionsSet> sourceRestrictionsSets, 863 RestrictionsSet destRestrictionSet) { 864 for (int i = 0; i < sourceRestrictionsSets.size(); i++) { 865 final RestrictionsSet sourceRestrictionsSet = sourceRestrictionsSets.valueAt(i); 866 sourceRestrictionsSet.moveRestriction(destRestrictionSet, restrictionKey); 867 } 868 } 869 870 /** 871 * Returns whether restrictions differ between two bundles. 872 * @param oldRestrictions old bundle of restrictions. 873 * @param newRestrictions new bundle of restrictions 874 * @param restrictions restrictions of interest, if empty, all restrictions are checked. 875 */ restrictionsChanged(Bundle oldRestrictions, Bundle newRestrictions, String... restrictions)876 public static boolean restrictionsChanged(Bundle oldRestrictions, Bundle newRestrictions, 877 String... restrictions) { 878 if (restrictions.length == 0) { 879 return areEqual(oldRestrictions, newRestrictions); 880 } 881 for (final String restriction : restrictions) { 882 if (oldRestrictions.getBoolean(restriction, false) != 883 newRestrictions.getBoolean(restriction, false)) { 884 return true; 885 } 886 } 887 return false; 888 } 889 setInstallMarketAppsRestriction(ContentResolver cr, int userId, int settingValue)890 private static void setInstallMarketAppsRestriction(ContentResolver cr, int userId, 891 int settingValue) { 892 android.provider.Settings.Secure.putIntForUser( 893 cr, android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, settingValue, userId); 894 } 895 getNewUserRestrictionSetting(Context context, int userId, String userRestriction, boolean newValue)896 private static int getNewUserRestrictionSetting(Context context, int userId, 897 String userRestriction, boolean newValue) { 898 return (newValue || UserManager.get(context).hasUserRestriction(userRestriction, 899 UserHandle.of(userId))) ? 0 : 1; 900 } 901 } 902