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 com.google.android.collect.Sets;
20 
21 import com.android.internal.util.Preconditions;
22 
23 import android.annotation.NonNull;
24 import android.annotation.Nullable;
25 import android.app.ActivityManager;
26 import android.app.ActivityManagerNative;
27 import android.content.ContentResolver;
28 import android.content.Context;
29 import android.net.Uri;
30 import android.os.Binder;
31 import android.os.Bundle;
32 import android.os.RemoteException;
33 import android.os.SystemProperties;
34 import android.os.UserHandle;
35 import android.os.UserManager;
36 import android.telephony.SubscriptionInfo;
37 import android.telephony.SubscriptionManager;
38 import android.util.Log;
39 import android.util.Slog;
40 
41 import org.xmlpull.v1.XmlPullParser;
42 import org.xmlpull.v1.XmlSerializer;
43 
44 import java.io.IOException;
45 import java.io.PrintWriter;
46 import java.util.List;
47 import java.util.Set;
48 
49 /**
50  * Utility methods for user restrictions.
51  *
52  * <p>See {@link UserManagerService} for the method suffixes.
53  */
54 public class UserRestrictionsUtils {
55     private static final String TAG = "UserRestrictionsUtils";
56 
UserRestrictionsUtils()57     private UserRestrictionsUtils() {
58     }
59 
newSetWithUniqueCheck(String[] strings)60     private static Set<String> newSetWithUniqueCheck(String[] strings) {
61         final Set<String> ret = Sets.newArraySet(strings);
62 
63         // Make sure there's no overlap.
64         Preconditions.checkState(ret.size() == strings.length);
65         return ret;
66     }
67 
68     public static final Set<String> USER_RESTRICTIONS = newSetWithUniqueCheck(new String[] {
69             UserManager.DISALLOW_CONFIG_WIFI,
70             UserManager.DISALLOW_MODIFY_ACCOUNTS,
71             UserManager.DISALLOW_INSTALL_APPS,
72             UserManager.DISALLOW_UNINSTALL_APPS,
73             UserManager.DISALLOW_SHARE_LOCATION,
74             UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
75             UserManager.DISALLOW_CONFIG_BLUETOOTH,
76             UserManager.DISALLOW_USB_FILE_TRANSFER,
77             UserManager.DISALLOW_CONFIG_CREDENTIALS,
78             UserManager.DISALLOW_REMOVE_USER,
79             UserManager.DISALLOW_DEBUGGING_FEATURES,
80             UserManager.DISALLOW_CONFIG_VPN,
81             UserManager.DISALLOW_CONFIG_TETHERING,
82             UserManager.DISALLOW_NETWORK_RESET,
83             UserManager.DISALLOW_FACTORY_RESET,
84             UserManager.DISALLOW_ADD_USER,
85             UserManager.ENSURE_VERIFY_APPS,
86             UserManager.DISALLOW_CONFIG_CELL_BROADCASTS,
87             UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS,
88             UserManager.DISALLOW_APPS_CONTROL,
89             UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
90             UserManager.DISALLOW_UNMUTE_MICROPHONE,
91             UserManager.DISALLOW_ADJUST_VOLUME,
92             UserManager.DISALLOW_OUTGOING_CALLS,
93             UserManager.DISALLOW_SMS,
94             UserManager.DISALLOW_FUN,
95             UserManager.DISALLOW_CREATE_WINDOWS,
96             UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE,
97             UserManager.DISALLOW_OUTGOING_BEAM,
98             UserManager.DISALLOW_WALLPAPER,
99             UserManager.DISALLOW_SAFE_BOOT,
100             UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
101             UserManager.DISALLOW_RECORD_AUDIO,
102             UserManager.DISALLOW_CAMERA,
103             UserManager.DISALLOW_RUN_IN_BACKGROUND,
104             UserManager.DISALLOW_DATA_ROAMING,
105             UserManager.DISALLOW_SET_USER_ICON,
106             UserManager.DISALLOW_SET_WALLPAPER
107     });
108 
109     /**
110      * Set of user restriction which we don't want to persist.
111      */
112     private static final Set<String> NON_PERSIST_USER_RESTRICTIONS = Sets.newArraySet(
113             UserManager.DISALLOW_RECORD_AUDIO
114     );
115 
116     /**
117      * User restrictions that can not be set by profile owners.
118      */
119     private static final Set<String> DEVICE_OWNER_ONLY_RESTRICTIONS = Sets.newArraySet(
120             UserManager.DISALLOW_USB_FILE_TRANSFER,
121             UserManager.DISALLOW_CONFIG_TETHERING,
122             UserManager.DISALLOW_NETWORK_RESET,
123             UserManager.DISALLOW_FACTORY_RESET,
124             UserManager.DISALLOW_ADD_USER,
125             UserManager.DISALLOW_CONFIG_CELL_BROADCASTS,
126             UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS,
127             UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
128             UserManager.DISALLOW_SMS,
129             UserManager.DISALLOW_FUN,
130             UserManager.DISALLOW_SAFE_BOOT,
131             UserManager.DISALLOW_CREATE_WINDOWS,
132             UserManager.DISALLOW_DATA_ROAMING
133     );
134 
135     /**
136      * User restrictions that can't be changed by device owner or profile owner.
137      */
138     private static final Set<String> IMMUTABLE_BY_OWNERS = Sets.newArraySet(
139             UserManager.DISALLOW_RECORD_AUDIO,
140             UserManager.DISALLOW_WALLPAPER
141     );
142 
143     /**
144      * Special user restrictions that can be applied to a user as well as to all users globally,
145      * depending on callers.  When device owner sets them, they'll be applied to all users.
146      */
147     private static final Set<String> GLOBAL_RESTRICTIONS = Sets.newArraySet(
148             UserManager.DISALLOW_ADJUST_VOLUME,
149             UserManager.DISALLOW_RUN_IN_BACKGROUND,
150             UserManager.DISALLOW_UNMUTE_MICROPHONE
151     );
152 
153     /**
154      * Throws {@link IllegalArgumentException} if the given restriction name is invalid.
155      */
isValidRestriction(@onNull String restriction)156     public static boolean isValidRestriction(@NonNull String restriction) {
157         if (!USER_RESTRICTIONS.contains(restriction)) {
158             Slog.e(TAG, "Unknown restriction: " + restriction);
159             return false;
160         }
161         return true;
162     }
163 
writeRestrictions(@onNull XmlSerializer serializer, @Nullable Bundle restrictions, @NonNull String tag)164     public static void writeRestrictions(@NonNull XmlSerializer serializer,
165             @Nullable Bundle restrictions, @NonNull String tag) throws IOException {
166         if (restrictions == null) {
167             return;
168         }
169 
170         serializer.startTag(null, tag);
171         for (String key : restrictions.keySet()) {
172             if (NON_PERSIST_USER_RESTRICTIONS.contains(key)) {
173                 continue; // Don't persist.
174             }
175             if (USER_RESTRICTIONS.contains(key)) {
176                 if (restrictions.getBoolean(key)) {
177                     serializer.attribute(null, key, "true");
178                 }
179                 continue;
180             }
181             Log.w(TAG, "Unknown user restriction detected: " + key);
182         }
183         serializer.endTag(null, tag);
184     }
185 
readRestrictions(XmlPullParser parser, Bundle restrictions)186     public static void readRestrictions(XmlPullParser parser, Bundle restrictions)
187             throws IOException {
188         for (String key : USER_RESTRICTIONS) {
189             final String value = parser.getAttributeValue(null, key);
190             if (value != null) {
191                 restrictions.putBoolean(key, Boolean.parseBoolean(value));
192             }
193         }
194     }
195 
196     /**
197      * @return {@code in} itself when it's not null, or an empty bundle (which can writable).
198      */
nonNull(@ullable Bundle in)199     public static Bundle nonNull(@Nullable Bundle in) {
200         return in != null ? in : new Bundle();
201     }
202 
isEmpty(@ullable Bundle in)203     public static boolean isEmpty(@Nullable Bundle in) {
204         return (in == null) || (in.size() == 0);
205     }
206 
207     /**
208      * Creates a copy of the {@code in} Bundle.  If {@code in} is null, it'll return an empty
209      * bundle.
210      *
211      * <p>The resulting {@link Bundle} is always writable. (i.e. it won't return
212      * {@link Bundle#EMPTY})
213      */
clone(@ullable Bundle in)214     public static @NonNull Bundle clone(@Nullable Bundle in) {
215         return (in != null) ? new Bundle(in) : new Bundle();
216     }
217 
merge(@onNull Bundle dest, @Nullable Bundle in)218     public static void merge(@NonNull Bundle dest, @Nullable Bundle in) {
219         Preconditions.checkNotNull(dest);
220         Preconditions.checkArgument(dest != in);
221         if (in == null) {
222             return;
223         }
224         for (String key : in.keySet()) {
225             if (in.getBoolean(key, false)) {
226                 dest.putBoolean(key, true);
227             }
228         }
229     }
230 
231     /**
232      * @return true if a restriction is settable by device owner.
233      */
canDeviceOwnerChange(String restriction)234     public static boolean canDeviceOwnerChange(String restriction) {
235         return !IMMUTABLE_BY_OWNERS.contains(restriction);
236     }
237 
238     /**
239      * @return true if a restriction is settable by profile owner.  Note it takes a user ID because
240      * some restrictions can be changed by PO only when it's running on the system user.
241      */
canProfileOwnerChange(String restriction, int userId)242     public static boolean canProfileOwnerChange(String restriction, int userId) {
243         return !IMMUTABLE_BY_OWNERS.contains(restriction)
244                 && !(userId != UserHandle.USER_SYSTEM
245                     && DEVICE_OWNER_ONLY_RESTRICTIONS.contains(restriction));
246     }
247 
248     /**
249      * Takes restrictions that can be set by device owner, and sort them into what should be applied
250      * globally and what should be applied only on the current user.
251      */
sortToGlobalAndLocal(@ullable Bundle in, @NonNull Bundle global, @NonNull Bundle local)252     public static void sortToGlobalAndLocal(@Nullable Bundle in, @NonNull Bundle global,
253             @NonNull Bundle local) {
254         if (in == null || in.size() == 0) {
255             return;
256         }
257         for (String key : in.keySet()) {
258             if (!in.getBoolean(key)) {
259                 continue;
260             }
261             if (DEVICE_OWNER_ONLY_RESTRICTIONS.contains(key) || GLOBAL_RESTRICTIONS.contains(key)) {
262                 global.putBoolean(key, true);
263             } else {
264                 local.putBoolean(key, true);
265             }
266         }
267     }
268 
269     /**
270      * @return true if two Bundles contain the same user restriction.
271      * A null bundle and an empty bundle are considered to be equal.
272      */
areEqual(@ullable Bundle a, @Nullable Bundle b)273     public static boolean areEqual(@Nullable Bundle a, @Nullable Bundle b) {
274         if (a == b) {
275             return true;
276         }
277         if (isEmpty(a)) {
278             return isEmpty(b);
279         }
280         if (isEmpty(b)) {
281             return false;
282         }
283         for (String key : a.keySet()) {
284             if (a.getBoolean(key) != b.getBoolean(key)) {
285                 return false;
286             }
287         }
288         for (String key : b.keySet()) {
289             if (a.getBoolean(key) != b.getBoolean(key)) {
290                 return false;
291             }
292         }
293         return true;
294     }
295 
296     /**
297      * Takes a new use restriction set and the previous set, and apply the restrictions that have
298      * changed.
299      *
300      * <p>Note this method is called by {@link UserManagerService} without holding any locks.
301      */
applyUserRestrictions(Context context, int userId, Bundle newRestrictions, Bundle prevRestrictions)302     public static void applyUserRestrictions(Context context, int userId,
303             Bundle newRestrictions, Bundle prevRestrictions) {
304         for (String key : USER_RESTRICTIONS) {
305             final boolean newValue = newRestrictions.getBoolean(key);
306             final boolean prevValue = prevRestrictions.getBoolean(key);
307 
308             if (newValue != prevValue) {
309                 applyUserRestriction(context, userId, key, newValue);
310             }
311         }
312     }
313 
314     /**
315      * Apply each user restriction.
316      *
317      * <p>See also {@link
318      * com.android.providers.settings.SettingsProvider#isGlobalOrSecureSettingRestrictedForUser},
319      * which should be in sync with this method.
320      */
applyUserRestriction(Context context, int userId, String key, boolean newValue)321     private static void applyUserRestriction(Context context, int userId, String key,
322             boolean newValue) {
323         if (UserManagerService.DBG) {
324             Log.d(TAG, "Applying user restriction: userId=" + userId
325                     + " key=" + key + " value=" + newValue);
326         }
327         // When certain restrictions are cleared, we don't update the system settings,
328         // because these settings are changeable on the Settings UI and we don't know the original
329         // value -- for example LOCATION_MODE might have been off already when the restriction was
330         // set, and in that case even if the restriction is lifted, changing it to ON would be
331         // wrong.  So just don't do anything in such a case.  If the user hopes to enable location
332         // later, they can do it on the Settings UI.
333 
334         final ContentResolver cr = context.getContentResolver();
335         final long id = Binder.clearCallingIdentity();
336         try {
337             switch (key) {
338                 case UserManager.DISALLOW_CONFIG_WIFI:
339                     if (newValue) {
340                         android.provider.Settings.Secure.putIntForUser(cr,
341                                 android.provider.Settings.Global
342                                         .WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0, userId);
343                     }
344                     break;
345                 case UserManager.DISALLOW_DATA_ROAMING:
346                     if (newValue) {
347                         // DISALLOW_DATA_ROAMING user restriction is set.
348 
349                         // Multi sim device.
350                         SubscriptionManager subscriptionManager = new SubscriptionManager(context);
351                         final List<SubscriptionInfo> subscriptionInfoList =
352                             subscriptionManager.getActiveSubscriptionInfoList();
353                         if (subscriptionInfoList != null) {
354                             for (SubscriptionInfo subInfo : subscriptionInfoList) {
355                                 android.provider.Settings.Global.putStringForUser(cr,
356                                     android.provider.Settings.Global.DATA_ROAMING
357                                     + subInfo.getSubscriptionId(), "0", userId);
358                             }
359                         }
360 
361                         // Single sim device.
362                         android.provider.Settings.Global.putStringForUser(cr,
363                             android.provider.Settings.Global.DATA_ROAMING, "0", userId);
364                     }
365                     break;
366                 case UserManager.DISALLOW_SHARE_LOCATION:
367                     if (newValue) {
368                         android.provider.Settings.Secure.putIntForUser(cr,
369                                 android.provider.Settings.Secure.LOCATION_MODE,
370                                 android.provider.Settings.Secure.LOCATION_MODE_OFF,
371                                 userId);
372                     }
373                     break;
374                 case UserManager.DISALLOW_DEBUGGING_FEATURES:
375                     if (newValue) {
376                         // Only disable adb if changing for system user, since it is global
377                         // TODO: should this be admin user?
378                         if (userId == UserHandle.USER_SYSTEM) {
379                             android.provider.Settings.Global.putStringForUser(cr,
380                                     android.provider.Settings.Global.ADB_ENABLED, "0",
381                                     userId);
382                         }
383                     }
384                     break;
385                 case UserManager.ENSURE_VERIFY_APPS:
386                     if (newValue) {
387                         android.provider.Settings.Global.putStringForUser(
388                                 context.getContentResolver(),
389                                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, "1",
390                                 userId);
391                         android.provider.Settings.Global.putStringForUser(
392                                 context.getContentResolver(),
393                                 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1",
394                                 userId);
395                     }
396                     break;
397                 case UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES:
398                     if (newValue) {
399                         android.provider.Settings.Secure.putIntForUser(cr,
400                                 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 0,
401                                 userId);
402                     }
403                     break;
404                 case UserManager.DISALLOW_RUN_IN_BACKGROUND:
405                     if (newValue) {
406                         int currentUser = ActivityManager.getCurrentUser();
407                         if (currentUser != userId && userId != UserHandle.USER_SYSTEM) {
408                             try {
409                                 ActivityManagerNative.getDefault().stopUser(userId, false, null);
410                             } catch (RemoteException e) {
411                                 throw e.rethrowAsRuntimeException();
412                             }
413                         }
414                     }
415                     break;
416                 case UserManager.DISALLOW_SAFE_BOOT:
417                     // Unlike with the other restrictions, we want to propagate the new value to
418                     // the system settings even if it is false. The other restrictions modify
419                     // settings which could be manually changed by the user from the Settings app
420                     // after the policies enforcing these restrictions have been revoked, so we
421                     // leave re-setting of those settings to the user.
422                     android.provider.Settings.Global.putInt(
423                             context.getContentResolver(),
424                             android.provider.Settings.Global.SAFE_BOOT_DISALLOWED,
425                             newValue ? 1 : 0);
426                     break;
427             }
428         } finally {
429             Binder.restoreCallingIdentity(id);
430         }
431     }
432 
dumpRestrictions(PrintWriter pw, String prefix, Bundle restrictions)433     public static void dumpRestrictions(PrintWriter pw, String prefix, Bundle restrictions) {
434         boolean noneSet = true;
435         if (restrictions != null) {
436             for (String key : restrictions.keySet()) {
437                 if (restrictions.getBoolean(key, false)) {
438                     pw.println(prefix + key);
439                     noneSet = false;
440                 }
441             }
442             if (noneSet) {
443                 pw.println(prefix + "none");
444             }
445         } else {
446             pw.println(prefix + "null");
447         }
448     }
449 }
450