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                             android.provider.Settings.Global.putStringForUser(cr,
566                                     android.provider.Settings.Global.ADB_WIFI_ENABLED, "0",
567                                     userId);
568                         }
569                     }
570                     break;
571                 case UserManager.ENSURE_VERIFY_APPS:
572                     if (newValue) {
573                         android.provider.Settings.Global.putStringForUser(
574                                 context.getContentResolver(),
575                                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, "1",
576                                 userId);
577                         android.provider.Settings.Global.putStringForUser(
578                                 context.getContentResolver(),
579                                 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1",
580                                 userId);
581                     }
582                     break;
583                 case UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY:
584                     setInstallMarketAppsRestriction(cr, userId, getNewUserRestrictionSetting(
585                             context, userId, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
586                             newValue));
587                     break;
588                 case UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES:
589                     // Since Android O, the secure setting is not available to be changed by the
590                     // user. Hence, when the restriction is cleared, we need to reset the state of
591                     // the setting to its default value which is now 1.
592                     setInstallMarketAppsRestriction(cr, userId, getNewUserRestrictionSetting(
593                             context, userId, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY,
594                             newValue));
595                     break;
596                 case UserManager.DISALLOW_RUN_IN_BACKGROUND:
597                     if (newValue) {
598                         int currentUser = ActivityManager.getCurrentUser();
599                         if (currentUser != userId && userId != UserHandle.USER_SYSTEM) {
600                             try {
601                                 ActivityManager.getService().stopUser(userId, false, null);
602                             } catch (RemoteException e) {
603                                 throw e.rethrowAsRuntimeException();
604                             }
605                         }
606                     }
607                     break;
608                 case UserManager.DISALLOW_SAFE_BOOT:
609                     // Unlike with the other restrictions, we want to propagate the new value to
610                     // the system settings even if it is false. The other restrictions modify
611                     // settings which could be manually changed by the user from the Settings app
612                     // after the policies enforcing these restrictions have been revoked, so we
613                     // leave re-setting of those settings to the user.
614                     android.provider.Settings.Global.putInt(
615                             context.getContentResolver(),
616                             android.provider.Settings.Global.SAFE_BOOT_DISALLOWED,
617                             newValue ? 1 : 0);
618                     break;
619                 case UserManager.DISALLOW_AIRPLANE_MODE:
620                     if (newValue) {
621                         final boolean airplaneMode = Settings.Global.getInt(
622                                 context.getContentResolver(),
623                                 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
624                         if (airplaneMode) {
625                             android.provider.Settings.Global.putInt(
626                                     context.getContentResolver(),
627                                     android.provider.Settings.Global.AIRPLANE_MODE_ON, 0);
628                             // Post the intent.
629                             Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
630                             intent.putExtra("state", false);
631                             context.sendBroadcastAsUser(intent, UserHandle.ALL);
632                         }
633                     }
634                     break;
635                 case UserManager.DISALLOW_AMBIENT_DISPLAY:
636                     if (newValue) {
637                         android.provider.Settings.Secure.putIntForUser(
638                                 context.getContentResolver(),
639                                 Settings.Secure.DOZE_ENABLED, 0, userId);
640                         android.provider.Settings.Secure.putIntForUser(
641                                 context.getContentResolver(),
642                                 Settings.Secure.DOZE_ALWAYS_ON, 0, userId);
643                         android.provider.Settings.Secure.putIntForUser(
644                                 context.getContentResolver(),
645                                 Settings.Secure.DOZE_PICK_UP_GESTURE, 0, userId);
646                         android.provider.Settings.Secure.putIntForUser(
647                                 context.getContentResolver(),
648                                 Settings.Secure.DOZE_PULSE_ON_LONG_PRESS, 0, userId);
649                         android.provider.Settings.Secure.putIntForUser(
650                                 context.getContentResolver(),
651                                 Settings.Secure.DOZE_DOUBLE_TAP_GESTURE, 0, userId);
652                     }
653                     break;
654                 case UserManager.DISALLOW_CONFIG_LOCATION:
655                     // When DISALLOW_CONFIG_LOCATION is set on any user, we undo the global
656                     // kill switch.
657                     if (newValue) {
658                         android.provider.Settings.Global.putString(
659                                 context.getContentResolver(),
660                                 Global.LOCATION_GLOBAL_KILL_SWITCH, "0");
661                     }
662                     break;
663             }
664         } finally {
665             Binder.restoreCallingIdentity(id);
666         }
667     }
668 
isSettingRestrictedForUser(Context context, @NonNull String setting, int userId, String value, int callingUid)669     public static boolean isSettingRestrictedForUser(Context context, @NonNull String setting,
670             int userId, String value, int callingUid) {
671         Preconditions.checkNotNull(setting);
672         final UserManager mUserManager = context.getSystemService(UserManager.class);
673         String restriction;
674         boolean checkAllUser = false;
675         switch (setting) {
676             case android.provider.Settings.Secure.LOCATION_MODE:
677                 if (mUserManager.hasUserRestriction(
678                         UserManager.DISALLOW_CONFIG_LOCATION, UserHandle.of(userId))
679                         && callingUid != Process.SYSTEM_UID) {
680                     return true;
681                 } else if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) {
682                     return false;
683                 }
684                 restriction = UserManager.DISALLOW_SHARE_LOCATION;
685                 break;
686 
687             case android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
688                 if (mUserManager.hasUserRestriction(
689                         UserManager.DISALLOW_CONFIG_LOCATION, UserHandle.of(userId))
690                         && callingUid != Process.SYSTEM_UID) {
691                     return true;
692                 } else if (value != null && value.startsWith("-")) {
693                     // See SettingsProvider.updateLocationProvidersAllowedLocked.  "-" is to disable
694                     // a provider, which should be allowed even if the user restriction is set.
695                     return false;
696                 }
697                 restriction = UserManager.DISALLOW_SHARE_LOCATION;
698                 break;
699 
700             case android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS:
701                 if ("0".equals(value)) {
702                     return false;
703                 }
704                 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
705                 break;
706 
707             case android.provider.Settings.Global.ADB_ENABLED:
708             case android.provider.Settings.Global.ADB_WIFI_ENABLED:
709                 if ("0".equals(value)) {
710                     return false;
711                 }
712                 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
713                 break;
714 
715             case android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE:
716             case android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
717                 if ("1".equals(value)) {
718                     return false;
719                 }
720                 restriction = UserManager.ENSURE_VERIFY_APPS;
721                 break;
722 
723             case android.provider.Settings.Global.PREFERRED_NETWORK_MODE:
724                 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
725                 break;
726 
727             case android.provider.Settings.Secure.ALWAYS_ON_VPN_APP:
728             case android.provider.Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
729             case android.provider.Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN_WHITELIST:
730                 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
731                 final int appId = UserHandle.getAppId(callingUid);
732                 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
733                     return false;
734                 }
735                 restriction = UserManager.DISALLOW_CONFIG_VPN;
736                 break;
737 
738             case android.provider.Settings.Global.SAFE_BOOT_DISALLOWED:
739                 if ("1".equals(value)) {
740                     return false;
741                 }
742                 restriction = UserManager.DISALLOW_SAFE_BOOT;
743                 break;
744 
745             case android.provider.Settings.Global.AIRPLANE_MODE_ON:
746                 if ("0".equals(value)) {
747                     return false;
748                 }
749                 restriction = UserManager.DISALLOW_AIRPLANE_MODE;
750                 break;
751 
752             case android.provider.Settings.Secure.DOZE_ENABLED:
753             case android.provider.Settings.Secure.DOZE_ALWAYS_ON:
754             case android.provider.Settings.Secure.DOZE_PICK_UP_GESTURE:
755             case android.provider.Settings.Secure.DOZE_PULSE_ON_LONG_PRESS:
756             case android.provider.Settings.Secure.DOZE_DOUBLE_TAP_GESTURE:
757                 if ("0".equals(value)) {
758                     return false;
759                 }
760                 restriction = UserManager.DISALLOW_AMBIENT_DISPLAY;
761                 break;
762 
763             case android.provider.Settings.Global.LOCATION_GLOBAL_KILL_SWITCH:
764                 if ("0".equals(value)) {
765                     return false;
766                 }
767                 restriction = UserManager.DISALLOW_CONFIG_LOCATION;
768                 checkAllUser = true;
769                 break;
770 
771             case android.provider.Settings.System.SCREEN_BRIGHTNESS:
772             case android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE:
773                 if (callingUid == Process.SYSTEM_UID) {
774                     return false;
775                 }
776                 restriction = UserManager.DISALLOW_CONFIG_BRIGHTNESS;
777                 break;
778 
779             case android.provider.Settings.Global.AUTO_TIME:
780                 DevicePolicyManager dpm = context.getSystemService(DevicePolicyManager.class);
781                 if (dpm != null && dpm.getAutoTimeRequired()
782                         && "0".equals(value)) {
783                     return true;
784                 } else if (callingUid == Process.SYSTEM_UID) {
785                     return false;
786                 }
787                 restriction = UserManager.DISALLOW_CONFIG_DATE_TIME;
788                 break;
789 
790             case android.provider.Settings.Global.AUTO_TIME_ZONE:
791                 if (callingUid == Process.SYSTEM_UID) {
792                     return false;
793                 }
794                 restriction = UserManager.DISALLOW_CONFIG_DATE_TIME;
795                 break;
796 
797             case android.provider.Settings.System.SCREEN_OFF_TIMEOUT:
798                 if (callingUid == Process.SYSTEM_UID) {
799                     return false;
800                 }
801                 restriction = UserManager.DISALLOW_CONFIG_SCREEN_TIMEOUT;
802                 break;
803 
804             case android.provider.Settings.Global.PRIVATE_DNS_MODE:
805             case android.provider.Settings.Global.PRIVATE_DNS_SPECIFIER:
806                 if (callingUid == Process.SYSTEM_UID) {
807                     return false;
808                 }
809                 restriction = UserManager.DISALLOW_CONFIG_PRIVATE_DNS;
810                 break;
811             default:
812                 if (setting.startsWith(Settings.Global.DATA_ROAMING)) {
813                     if ("0".equals(value)) {
814                         return false;
815                     }
816                     restriction = UserManager.DISALLOW_DATA_ROAMING;
817                     break;
818                 }
819                 return false;
820         }
821 
822         if (checkAllUser) {
823             return mUserManager.hasUserRestrictionOnAnyUser(restriction);
824         } else {
825             return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
826         }
827     }
828 
dumpRestrictions(PrintWriter pw, String prefix, Bundle restrictions)829     public static void dumpRestrictions(PrintWriter pw, String prefix, Bundle restrictions) {
830         boolean noneSet = true;
831         if (restrictions != null) {
832             for (String key : restrictions.keySet()) {
833                 if (restrictions.getBoolean(key, false)) {
834                     pw.println(prefix + key);
835                     noneSet = false;
836                 }
837             }
838             if (noneSet) {
839                 pw.println(prefix + "none");
840             }
841         } else {
842             pw.println(prefix + "null");
843         }
844     }
845 
846     /**
847      * Moves a particular restriction from one array of bundles to another, e.g. for all users.
848      */
moveRestriction(String restrictionKey, SparseArray<Bundle> srcRestrictions, SparseArray<Bundle> destRestrictions)849     public static void moveRestriction(String restrictionKey, SparseArray<Bundle> srcRestrictions,
850             SparseArray<Bundle> destRestrictions) {
851         for (int i = 0; i < srcRestrictions.size(); i++) {
852             final int key = srcRestrictions.keyAt(i);
853             final Bundle from = srcRestrictions.valueAt(i);
854             if (contains(from, restrictionKey)) {
855                 from.remove(restrictionKey);
856                 Bundle to = destRestrictions.get(key);
857                 if (to == null) {
858                     to = new Bundle();
859                     destRestrictions.append(key, to);
860                 }
861                 to.putBoolean(restrictionKey, true);
862                 // Don't keep empty bundles.
863                 if (from.isEmpty()) {
864                     srcRestrictions.removeAt(i);
865                     i--;
866                 }
867             }
868         }
869     }
870 
871     /**
872      * Returns whether restrictions differ between two bundles.
873      * @param oldRestrictions old bundle of restrictions.
874      * @param newRestrictions new bundle of restrictions
875      * @param restrictions restrictions of interest, if empty, all restrictions are checked.
876      */
restrictionsChanged(Bundle oldRestrictions, Bundle newRestrictions, String... restrictions)877     public static boolean restrictionsChanged(Bundle oldRestrictions, Bundle newRestrictions,
878             String... restrictions) {
879         if (restrictions.length == 0) {
880             return areEqual(oldRestrictions, newRestrictions);
881         }
882         for (final String restriction : restrictions) {
883             if (oldRestrictions.getBoolean(restriction, false) !=
884                     newRestrictions.getBoolean(restriction, false)) {
885                 return true;
886             }
887         }
888         return false;
889     }
890 
setInstallMarketAppsRestriction(ContentResolver cr, int userId, int settingValue)891     private static void setInstallMarketAppsRestriction(ContentResolver cr, int userId,
892             int settingValue) {
893         android.provider.Settings.Secure.putIntForUser(
894                 cr, android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, settingValue, userId);
895     }
896 
getNewUserRestrictionSetting(Context context, int userId, String userRestriction, boolean newValue)897     private static int getNewUserRestrictionSetting(Context context, int userId,
898                 String userRestriction, boolean newValue) {
899         return (newValue || UserManager.get(context).hasUserRestriction(userRestriction,
900                 UserHandle.of(userId))) ? 0 : 1;
901     }
902 }
903