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 
17 package android.net;
18 
19 import static android.content.pm.PackageManager.GET_SIGNATURES;
20 
21 import android.annotation.SystemService;
22 import android.app.ActivityManager;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.pm.PackageManager;
26 import android.content.pm.PackageManager.NameNotFoundException;
27 import android.content.pm.Signature;
28 import android.net.wifi.WifiConfiguration;
29 import android.net.wifi.WifiInfo;
30 import android.os.RemoteException;
31 import android.os.UserHandle;
32 import android.util.DebugUtils;
33 import android.util.Pair;
34 import android.util.Range;
35 
36 import com.google.android.collect.Sets;
37 
38 import java.time.ZonedDateTime;
39 import java.util.HashSet;
40 import java.util.Iterator;
41 
42 /**
43  * Manager for creating and modifying network policy rules.
44  *
45  * {@hide}
46  */
47 @SystemService(Context.NETWORK_POLICY_SERVICE)
48 public 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 
NetworkPolicyManager(Context context, INetworkPolicyManager service)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 
from(Context context)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      */
setUidPolicy(int uid, int policy)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      */
addUidPolicy(int uid, int policy)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      */
removeUidPolicy(int uid, int policy)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 
getUidPolicy(int uid)184     public int getUidPolicy(int uid) {
185         try {
186             return mService.getUidPolicy(uid);
187         } catch (RemoteException e) {
188             throw e.rethrowFromSystemServer();
189         }
190     }
191 
getUidsWithPolicy(int policy)192     public int[] getUidsWithPolicy(int policy) {
193         try {
194             return mService.getUidsWithPolicy(policy);
195         } catch (RemoteException e) {
196             throw e.rethrowFromSystemServer();
197         }
198     }
199 
registerListener(INetworkPolicyListener listener)200     public void registerListener(INetworkPolicyListener listener) {
201         try {
202             mService.registerListener(listener);
203         } catch (RemoteException e) {
204             throw e.rethrowFromSystemServer();
205         }
206     }
207 
unregisterListener(INetworkPolicyListener listener)208     public void unregisterListener(INetworkPolicyListener listener) {
209         try {
210             mService.unregisterListener(listener);
211         } catch (RemoteException e) {
212             throw e.rethrowFromSystemServer();
213         }
214     }
215 
setNetworkPolicies(NetworkPolicy[] policies)216     public void setNetworkPolicies(NetworkPolicy[] policies) {
217         try {
218             mService.setNetworkPolicies(policies);
219         } catch (RemoteException e) {
220             throw e.rethrowFromSystemServer();
221         }
222     }
223 
getNetworkPolicies()224     public NetworkPolicy[] getNetworkPolicies() {
225         try {
226             return mService.getNetworkPolicies(mContext.getOpPackageName());
227         } catch (RemoteException e) {
228             throw e.rethrowFromSystemServer();
229         }
230     }
231 
setRestrictBackground(boolean restrictBackground)232     public void setRestrictBackground(boolean restrictBackground) {
233         try {
234             mService.setRestrictBackground(restrictBackground);
235         } catch (RemoteException e) {
236             throw e.rethrowFromSystemServer();
237         }
238     }
239 
getRestrictBackground()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      */
factoryReset(String subscriber)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
cycleIterator(NetworkPolicy policy)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                 if (hasNext()) {
274                     final Range<ZonedDateTime> r = it.next();
275                     return Pair.create(r.getLower(), r.getUpper());
276                 } else {
277                     return Pair.create(null, null);
278                 }
279             }
280         };
281     }
282 
283     /**
284      * Check if given UID can have a {@link #setUidPolicy(int, int)} defined,
285      * usually to protect critical system services.
286      */
287     @Deprecated
288     public static boolean isUidValidForPolicy(Context context, int uid) {
289         // first, quick-reject non-applications
290         if (!UserHandle.isApp(uid)) {
291             return false;
292         }
293 
294         if (!ALLOW_PLATFORM_APP_POLICY) {
295             final PackageManager pm = context.getPackageManager();
296             final HashSet<Signature> systemSignature;
297             try {
298                 systemSignature = Sets.newHashSet(
299                         pm.getPackageInfo("android", GET_SIGNATURES).signatures);
300             } catch (NameNotFoundException e) {
301                 throw new RuntimeException("problem finding system signature", e);
302             }
303 
304             try {
305                 // reject apps signed with platform cert
306                 for (String packageName : pm.getPackagesForUid(uid)) {
307                     final HashSet<Signature> packageSignature = Sets.newHashSet(
308                             pm.getPackageInfo(packageName, GET_SIGNATURES).signatures);
309                     if (packageSignature.containsAll(systemSignature)) {
310                         return false;
311                     }
312                 }
313             } catch (NameNotFoundException e) {
314             }
315         }
316 
317         // nothing found above; we can apply policy to UID
318         return true;
319     }
320 
321     /**
322      * @hide
323      */
324     public static String uidRulesToString(int uidRules) {
325         final StringBuilder string = new StringBuilder().append(uidRules).append(" (");
326         if (uidRules == RULE_NONE) {
327             string.append("NONE");
328         } else {
329             string.append(DebugUtils.flagsToString(NetworkPolicyManager.class, "RULE_", uidRules));
330         }
331         string.append(")");
332         return string.toString();
333     }
334 
335     /**
336      * @hide
337      */
338     public static String uidPoliciesToString(int uidPolicies) {
339         final StringBuilder string = new StringBuilder().append(uidPolicies).append(" (");
340         if (uidPolicies == POLICY_NONE) {
341             string.append("NONE");
342         } else {
343             string.append(DebugUtils.flagsToString(NetworkPolicyManager.class,
344                     "POLICY_", uidPolicies));
345         }
346         string.append(")");
347         return string.toString();
348     }
349 
350     /**
351      * Returns true if {@param procState} is considered foreground and as such will be allowed
352      * to access network when the device is idle or in battery saver mode. Otherwise, false.
353      */
354     public static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
355         return procState <= FOREGROUND_THRESHOLD_STATE;
356     }
357 
358     /**
359      * Returns true if {@param procState} is considered foreground and as such will be allowed
360      * to access network when the device is in data saver mode. Otherwise, false.
361      */
362     public static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
363         return procState <= FOREGROUND_THRESHOLD_STATE;
364     }
365 
366     public static String resolveNetworkId(WifiConfiguration config) {
367         return WifiInfo.removeDoubleQuotes(config.isPasspoint()
368                 ? config.providerFriendlyName : config.SSID);
369     }
370 
371     public static String resolveNetworkId(String ssid) {
372         return WifiInfo.removeDoubleQuotes(ssid);
373     }
374 
375     /** {@hide} */
376     public static class Listener extends INetworkPolicyListener.Stub {
377         @Override public void onUidRulesChanged(int uid, int uidRules) { }
378         @Override public void onMeteredIfacesChanged(String[] meteredIfaces) { }
379         @Override public void onRestrictBackgroundChanged(boolean restrictBackground) { }
380         @Override public void onUidPoliciesChanged(int uid, int uidPolicies) { }
381         @Override public void onSubscriptionOverride(int subId, int overrideMask, int overrideValue) { }
382     }
383 }
384