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