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