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