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