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