NetworkPolicyManager.java revision 0fc6d03b628c8cbe80e3c2c14aaf8c6944b32d1e
1/*
2 * Copyright (C) 2011 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 android.net;
18
19import static android.content.pm.PackageManager.GET_SIGNATURES;
20
21import android.annotation.SystemService;
22import android.app.ActivityManager;
23import android.content.Context;
24import android.content.Intent;
25import android.content.pm.PackageManager;
26import android.content.pm.PackageManager.NameNotFoundException;
27import android.content.pm.Signature;
28import android.net.wifi.WifiConfiguration;
29import android.net.wifi.WifiInfo;
30import android.os.RemoteException;
31import android.os.UserHandle;
32import android.util.DebugUtils;
33import android.util.Pair;
34import android.util.Range;
35
36import com.google.android.collect.Sets;
37
38import java.time.ZonedDateTime;
39import java.util.HashSet;
40import java.util.Iterator;
41
42/**
43 * Manager for creating and modifying network policy rules.
44 *
45 * {@hide}
46 */
47@SystemService(Context.NETWORK_POLICY_SERVICE)
48public class NetworkPolicyManager {
49
50    /* POLICY_* are masks and can be ORed, although currently they are not.*/
51    /** No specific network policy, use system default. */
52    public static final int POLICY_NONE = 0x0;
53    /** Reject network usage on metered networks when application in background. */
54    public static final int POLICY_REJECT_METERED_BACKGROUND = 0x1;
55    /** Allow metered network use in the background even when in data usage save mode. */
56    public static final int POLICY_ALLOW_METERED_BACKGROUND = 0x4;
57
58    /*
59     * Rules defining whether an uid has access to a network given its type (metered / non-metered).
60     *
61     * These rules are bits and can be used in bitmask operations; in particular:
62     * - rule & RULE_MASK_METERED: returns the metered-networks status.
63     * - rule & RULE_MASK_ALL: returns the all-networks status.
64     *
65     * The RULE_xxx_ALL rules applies to all networks (metered or non-metered), but on
66     * metered networks, the RULE_xxx_METERED rules should be checked first. For example,
67     * if the device is on Battery Saver Mode and Data Saver Mode simulatenously, and a uid
68     * is whitelisted for the former but not the latter, its status would be
69     * RULE_REJECT_METERED | RULE_ALLOW_ALL, meaning it could have access to non-metered
70     * networks but not to metered networks.
71     *
72     * See network-policy-restrictions.md for more info.
73     */
74    /** No specific rule was set */
75    public static final int RULE_NONE = 0;
76    /** Allow traffic on metered networks. */
77    public static final int RULE_ALLOW_METERED = 1 << 0;
78    /** Temporarily allow traffic on metered networks because app is on foreground. */
79    public static final int RULE_TEMPORARY_ALLOW_METERED = 1 << 1;
80    /** Reject traffic on metered networks. */
81    public static final int RULE_REJECT_METERED = 1 << 2;
82    /** Network traffic should be allowed on all networks (metered or non-metered), although
83     * metered-network restrictions could still apply. */
84    public static final int RULE_ALLOW_ALL = 1 << 5;
85    /** Reject traffic on all networks. */
86    public static final int RULE_REJECT_ALL = 1 << 6;
87    /** Mask used to get the {@code RULE_xxx_METERED} rules */
88    public static final int MASK_METERED_NETWORKS = 0b00001111;
89    /** Mask used to get the {@code RULE_xxx_ALL} rules */
90    public static final int MASK_ALL_NETWORKS     = 0b11110000;
91
92    public static final int FIREWALL_RULE_DEFAULT = 0;
93    public static final int FIREWALL_RULE_ALLOW = 1;
94    public static final int FIREWALL_RULE_DENY = 2;
95
96    public static final int FIREWALL_TYPE_WHITELIST = 0;
97    public static final int FIREWALL_TYPE_BLACKLIST = 1;
98
99    public static final int FIREWALL_CHAIN_NONE = 0;
100    public static final int FIREWALL_CHAIN_DOZABLE = 1;
101    public static final int FIREWALL_CHAIN_STANDBY = 2;
102    public static final int FIREWALL_CHAIN_POWERSAVE = 3;
103
104    public static final String FIREWALL_CHAIN_NAME_NONE = "none";
105    public static final String FIREWALL_CHAIN_NAME_DOZABLE = "dozable";
106    public static final String FIREWALL_CHAIN_NAME_STANDBY = "standby";
107    public static final String FIREWALL_CHAIN_NAME_POWERSAVE = "powersave";
108
109    private static final boolean ALLOW_PLATFORM_APP_POLICY = true;
110
111    public static final int FOREGROUND_THRESHOLD_STATE =
112            ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
113
114    /**
115     * {@link Intent} extra that indicates which {@link NetworkTemplate} rule it
116     * applies to.
117     */
118    public static final String EXTRA_NETWORK_TEMPLATE = "android.net.NETWORK_TEMPLATE";
119
120    public static final int OVERRIDE_UNMETERED = 1 << 0;
121    public static final int OVERRIDE_CONGESTED = 1 << 1;
122
123    private final Context mContext;
124    private INetworkPolicyManager mService;
125
126    public NetworkPolicyManager(Context context, INetworkPolicyManager service) {
127        if (service == null) {
128            throw new IllegalArgumentException("missing INetworkPolicyManager");
129        }
130        mContext = context;
131        mService = service;
132    }
133
134    public static NetworkPolicyManager from(Context context) {
135        return (NetworkPolicyManager) context.getSystemService(Context.NETWORK_POLICY_SERVICE);
136    }
137
138    /**
139     * Set policy flags for specific UID.
140     *
141     * @param policy should be {@link #POLICY_NONE} or any combination of {@code POLICY_} flags,
142     *     although it is not validated.
143     */
144    public void setUidPolicy(int uid, int policy) {
145        try {
146            mService.setUidPolicy(uid, policy);
147        } catch (RemoteException e) {
148            throw e.rethrowFromSystemServer();
149        }
150    }
151
152    /**
153     * Add policy flags for specific UID.
154     *
155     * <p>The given policy bits will be set for the uid.
156     *
157     * @param policy should be {@link #POLICY_NONE} or any combination of {@code POLICY_} flags,
158     *     although it is not validated.
159     */
160    public void addUidPolicy(int uid, int policy) {
161        try {
162            mService.addUidPolicy(uid, policy);
163        } catch (RemoteException e) {
164            throw e.rethrowFromSystemServer();
165        }
166    }
167
168    /**
169     * Clear/remove policy flags for specific UID.
170     *
171     * <p>The given policy bits will be set for the uid.
172     *
173     * @param policy should be {@link #POLICY_NONE} or any combination of {@code POLICY_} flags,
174     *     although it is not validated.
175     */
176    public void removeUidPolicy(int uid, int policy) {
177        try {
178            mService.removeUidPolicy(uid, policy);
179        } catch (RemoteException e) {
180            throw e.rethrowFromSystemServer();
181        }
182    }
183
184    public int getUidPolicy(int uid) {
185        try {
186            return mService.getUidPolicy(uid);
187        } catch (RemoteException e) {
188            throw e.rethrowFromSystemServer();
189        }
190    }
191
192    public int[] getUidsWithPolicy(int policy) {
193        try {
194            return mService.getUidsWithPolicy(policy);
195        } catch (RemoteException e) {
196            throw e.rethrowFromSystemServer();
197        }
198    }
199
200    public void registerListener(INetworkPolicyListener listener) {
201        try {
202            mService.registerListener(listener);
203        } catch (RemoteException e) {
204            throw e.rethrowFromSystemServer();
205        }
206    }
207
208    public void unregisterListener(INetworkPolicyListener listener) {
209        try {
210            mService.unregisterListener(listener);
211        } catch (RemoteException e) {
212            throw e.rethrowFromSystemServer();
213        }
214    }
215
216    public void setNetworkPolicies(NetworkPolicy[] policies) {
217        try {
218            mService.setNetworkPolicies(policies);
219        } catch (RemoteException e) {
220            throw e.rethrowFromSystemServer();
221        }
222    }
223
224    public NetworkPolicy[] getNetworkPolicies() {
225        try {
226            return mService.getNetworkPolicies(mContext.getOpPackageName());
227        } catch (RemoteException e) {
228            throw e.rethrowFromSystemServer();
229        }
230    }
231
232    public void setRestrictBackground(boolean restrictBackground) {
233        try {
234            mService.setRestrictBackground(restrictBackground);
235        } catch (RemoteException e) {
236            throw e.rethrowFromSystemServer();
237        }
238    }
239
240    public boolean getRestrictBackground() {
241        try {
242            return mService.getRestrictBackground();
243        } catch (RemoteException e) {
244            throw e.rethrowFromSystemServer();
245        }
246    }
247
248    /**
249     * Resets network policy settings back to factory defaults.
250     *
251     * @hide
252     */
253    public void factoryReset(String subscriber) {
254        try {
255            mService.factoryReset(subscriber);
256        } catch (RemoteException e) {
257            throw e.rethrowFromSystemServer();
258        }
259    }
260
261    /** {@hide} */
262    @Deprecated
263    public static Iterator<Pair<ZonedDateTime, ZonedDateTime>> cycleIterator(NetworkPolicy policy) {
264        final Iterator<Range<ZonedDateTime>> it = policy.cycleIterator();
265        return new Iterator<Pair<ZonedDateTime, ZonedDateTime>>() {
266            @Override
267            public boolean hasNext() {
268                return it.hasNext();
269            }
270
271            @Override
272            public Pair<ZonedDateTime, ZonedDateTime> next() {
273                final Range<ZonedDateTime> r = it.next();
274                return Pair.create(r.getLower(), r.getUpper());
275            }
276        };
277    }
278
279    /**
280     * Check if given UID can have a {@link #setUidPolicy(int, int)} defined,
281     * usually to protect critical system services.
282     */
283    @Deprecated
284    public static boolean isUidValidForPolicy(Context context, int uid) {
285        // first, quick-reject non-applications
286        if (!UserHandle.isApp(uid)) {
287            return false;
288        }
289
290        if (!ALLOW_PLATFORM_APP_POLICY) {
291            final PackageManager pm = context.getPackageManager();
292            final HashSet<Signature> systemSignature;
293            try {
294                systemSignature = Sets.newHashSet(
295                        pm.getPackageInfo("android", GET_SIGNATURES).signatures);
296            } catch (NameNotFoundException e) {
297                throw new RuntimeException("problem finding system signature", e);
298            }
299
300            try {
301                // reject apps signed with platform cert
302                for (String packageName : pm.getPackagesForUid(uid)) {
303                    final HashSet<Signature> packageSignature = Sets.newHashSet(
304                            pm.getPackageInfo(packageName, GET_SIGNATURES).signatures);
305                    if (packageSignature.containsAll(systemSignature)) {
306                        return false;
307                    }
308                }
309            } catch (NameNotFoundException e) {
310            }
311        }
312
313        // nothing found above; we can apply policy to UID
314        return true;
315    }
316
317    /**
318     * @hide
319     */
320    public static String uidRulesToString(int uidRules) {
321        final StringBuilder string = new StringBuilder().append(uidRules).append(" (");
322        if (uidRules == RULE_NONE) {
323            string.append("NONE");
324        } else {
325            string.append(DebugUtils.flagsToString(NetworkPolicyManager.class, "RULE_", uidRules));
326        }
327        string.append(")");
328        return string.toString();
329    }
330
331    /**
332     * @hide
333     */
334    public static String uidPoliciesToString(int uidPolicies) {
335        final StringBuilder string = new StringBuilder().append(uidPolicies).append(" (");
336        if (uidPolicies == POLICY_NONE) {
337            string.append("NONE");
338        } else {
339            string.append(DebugUtils.flagsToString(NetworkPolicyManager.class,
340                    "POLICY_", uidPolicies));
341        }
342        string.append(")");
343        return string.toString();
344    }
345
346    /**
347     * Returns true if {@param procState} is considered foreground and as such will be allowed
348     * to access network when the device is idle or in battery saver mode. Otherwise, false.
349     */
350    public static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
351        return procState <= FOREGROUND_THRESHOLD_STATE;
352    }
353
354    /**
355     * Returns true if {@param procState} is considered foreground and as such will be allowed
356     * to access network when the device is in data saver mode. Otherwise, false.
357     */
358    public static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
359        return procState <= FOREGROUND_THRESHOLD_STATE;
360    }
361
362    public static String resolveNetworkId(WifiConfiguration config) {
363        return WifiInfo.removeDoubleQuotes(config.isPasspoint()
364                ? config.providerFriendlyName : config.SSID);
365    }
366
367    public static String resolveNetworkId(String ssid) {
368        return WifiInfo.removeDoubleQuotes(ssid);
369    }
370
371    /** {@hide} */
372    public static class Listener extends INetworkPolicyListener.Stub {
373        @Override public void onUidRulesChanged(int uid, int uidRules) { }
374        @Override public void onMeteredIfacesChanged(String[] meteredIfaces) { }
375        @Override public void onRestrictBackgroundChanged(boolean restrictBackground) { }
376        @Override public void onUidPoliciesChanged(int uid, int uidPolicies) { }
377        @Override public void onSubscriptionOverride(int subId, int overrideMask, int overrideValue) { }
378    }
379}
380