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 android.app.Activity; 20import android.app.PendingIntent; 21import android.app.Service; 22import android.content.Context; 23import android.content.Intent; 24import android.os.Binder; 25import android.os.IBinder; 26import android.os.Parcel; 27import android.os.ParcelFileDescriptor; 28import android.os.RemoteException; 29import android.os.ServiceManager; 30 31import com.android.internal.net.VpnConfig; 32 33import java.net.DatagramSocket; 34import java.net.Inet4Address; 35import java.net.Inet6Address; 36import java.net.InetAddress; 37import java.net.Socket; 38import java.util.ArrayList; 39import java.util.List; 40 41/** 42 * VpnService is a base class for applications to extend and build their 43 * own VPN solutions. In general, it creates a virtual network interface, 44 * configures addresses and routing rules, and returns a file descriptor 45 * to the application. Each read from the descriptor retrieves an outgoing 46 * packet which was routed to the interface. Each write to the descriptor 47 * injects an incoming packet just like it was received from the interface. 48 * The interface is running on Internet Protocol (IP), so packets are 49 * always started with IP headers. The application then completes a VPN 50 * connection by processing and exchanging packets with the remote server 51 * over a tunnel. 52 * 53 * <p>Letting applications intercept packets raises huge security concerns. 54 * A VPN application can easily break the network. Besides, two of them may 55 * conflict with each other. The system takes several actions to address 56 * these issues. Here are some key points: 57 * <ul> 58 * <li>User action is required to create a VPN connection.</li> 59 * <li>There can be only one VPN connection running at the same time. The 60 * existing interface is deactivated when a new one is created.</li> 61 * <li>A system-managed notification is shown during the lifetime of a 62 * VPN connection.</li> 63 * <li>A system-managed dialog gives the information of the current VPN 64 * connection. It also provides a button to disconnect.</li> 65 * <li>The network is restored automatically when the file descriptor is 66 * closed. It also covers the cases when a VPN application is crashed 67 * or killed by the system.</li> 68 * </ul> 69 * 70 * <p>There are two primary methods in this class: {@link #prepare} and 71 * {@link Builder#establish}. The former deals with user action and stops 72 * the VPN connection created by another application. The latter creates 73 * a VPN interface using the parameters supplied to the {@link Builder}. 74 * An application must call {@link #prepare} to grant the right to use 75 * other methods in this class, and the right can be revoked at any time. 76 * Here are the general steps to create a VPN connection: 77 * <ol> 78 * <li>When the user press the button to connect, call {@link #prepare} 79 * and launch the returned intent.</li> 80 * <li>When the application becomes prepared, start the service.</li> 81 * <li>Create a tunnel to the remote server and negotiate the network 82 * parameters for the VPN connection.</li> 83 * <li>Supply those parameters to a {@link Builder} and create a VPN 84 * interface by calling {@link Builder#establish}.</li> 85 * <li>Process and exchange packets between the tunnel and the returned 86 * file descriptor.</li> 87 * <li>When {@link #onRevoke} is invoked, close the file descriptor and 88 * shut down the tunnel gracefully.</li> 89 * </ol> 90 * 91 * <p>Services extended this class need to be declared with appropriate 92 * permission and intent filter. Their access must be secured by 93 * {@link android.Manifest.permission#BIND_VPN_SERVICE} permission, and 94 * their intent filter must match {@link #SERVICE_INTERFACE} action. Here 95 * is an example of declaring a VPN service in {@code AndroidManifest.xml}: 96 * <pre> 97 * <service android:name=".ExampleVpnService" 98 * android:permission="android.permission.BIND_VPN_SERVICE"> 99 * <intent-filter> 100 * <action android:name="android.net.VpnService"/> 101 * </intent-filter> 102 * </service></pre> 103 * 104 * @see Builder 105 */ 106public class VpnService extends Service { 107 108 /** 109 * The action must be matched by the intent filter of this service. It also 110 * needs to require {@link android.Manifest.permission#BIND_VPN_SERVICE} 111 * permission so that other applications cannot abuse it. 112 */ 113 public static final String SERVICE_INTERFACE = VpnConfig.SERVICE_INTERFACE; 114 115 /** 116 * Use IConnectivityManager since those methods are hidden and not 117 * available in ConnectivityManager. 118 */ 119 private static IConnectivityManager getService() { 120 return IConnectivityManager.Stub.asInterface( 121 ServiceManager.getService(Context.CONNECTIVITY_SERVICE)); 122 } 123 124 /** 125 * Prepare to establish a VPN connection. This method returns {@code null} 126 * if the VPN application is already prepared. Otherwise, it returns an 127 * {@link Intent} to a system activity. The application should launch the 128 * activity using {@link Activity#startActivityForResult} to get itself 129 * prepared. The activity may pop up a dialog to require user action, and 130 * the result will come back via its {@link Activity#onActivityResult}. 131 * If the result is {@link Activity#RESULT_OK}, the application becomes 132 * prepared and is granted to use other methods in this class. 133 * 134 * <p>Only one application can be granted at the same time. The right 135 * is revoked when another application is granted. The application 136 * losing the right will be notified via its {@link #onRevoke}. Unless 137 * it becomes prepared again, subsequent calls to other methods in this 138 * class will fail. 139 * 140 * @see #onRevoke 141 */ 142 public static Intent prepare(Context context) { 143 try { 144 if (getService().prepareVpn(context.getPackageName(), null)) { 145 return null; 146 } 147 } catch (RemoteException e) { 148 // ignore 149 } 150 return VpnConfig.getIntentForConfirmation(); 151 } 152 153 /** 154 * Protect a socket from VPN connections. The socket will be bound to the 155 * current default network interface, so its traffic will not be forwarded 156 * through VPN. This method is useful if some connections need to be kept 157 * outside of VPN. For example, a VPN tunnel should protect itself if its 158 * destination is covered by VPN routes. Otherwise its outgoing packets 159 * will be sent back to the VPN interface and cause an infinite loop. This 160 * method will fail if the application is not prepared or is revoked. 161 * 162 * <p class="note">The socket is NOT closed by this method. 163 * 164 * @return {@code true} on success. 165 */ 166 public boolean protect(int socket) { 167 ParcelFileDescriptor dup = null; 168 try { 169 dup = ParcelFileDescriptor.fromFd(socket); 170 return getService().protectVpn(dup); 171 } catch (Exception e) { 172 return false; 173 } finally { 174 try { 175 dup.close(); 176 } catch (Exception e) { 177 // ignore 178 } 179 } 180 } 181 182 /** 183 * Convenience method to protect a {@link Socket} from VPN connections. 184 * 185 * @return {@code true} on success. 186 * @see #protect(int) 187 */ 188 public boolean protect(Socket socket) { 189 return protect(socket.getFileDescriptor$().getInt$()); 190 } 191 192 /** 193 * Convenience method to protect a {@link DatagramSocket} from VPN 194 * connections. 195 * 196 * @return {@code true} on success. 197 * @see #protect(int) 198 */ 199 public boolean protect(DatagramSocket socket) { 200 return protect(socket.getFileDescriptor$().getInt$()); 201 } 202 203 /** 204 * Return the communication interface to the service. This method returns 205 * {@code null} on {@link Intent}s other than {@link #SERVICE_INTERFACE} 206 * action. Applications overriding this method must identify the intent 207 * and return the corresponding interface accordingly. 208 * 209 * @see Service#onBind 210 */ 211 @Override 212 public IBinder onBind(Intent intent) { 213 if (intent != null && SERVICE_INTERFACE.equals(intent.getAction())) { 214 return new Callback(); 215 } 216 return null; 217 } 218 219 /** 220 * Invoked when the application is revoked. At this moment, the VPN 221 * interface is already deactivated by the system. The application should 222 * close the file descriptor and shut down gracefully. The default 223 * implementation of this method is calling {@link Service#stopSelf()}. 224 * 225 * <p class="note">Calls to this method may not happen on the main thread 226 * of the process. 227 * 228 * @see #prepare 229 */ 230 public void onRevoke() { 231 stopSelf(); 232 } 233 234 /** 235 * Use raw Binder instead of AIDL since now there is only one usage. 236 */ 237 private class Callback extends Binder { 238 @Override 239 protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) { 240 if (code == IBinder.LAST_CALL_TRANSACTION) { 241 onRevoke(); 242 return true; 243 } 244 return false; 245 } 246 } 247 248 /** 249 * Helper class to create a VPN interface. This class should be always 250 * used within the scope of the outer {@link VpnService}. 251 * 252 * @see VpnService 253 */ 254 public class Builder { 255 256 private final VpnConfig mConfig = new VpnConfig(); 257 private final List<LinkAddress> mAddresses = new ArrayList<LinkAddress>(); 258 private final List<RouteInfo> mRoutes = new ArrayList<RouteInfo>(); 259 260 public Builder() { 261 mConfig.user = VpnService.this.getClass().getName(); 262 } 263 264 /** 265 * Set the name of this session. It will be displayed in 266 * system-managed dialogs and notifications. This is recommended 267 * not required. 268 */ 269 public Builder setSession(String session) { 270 mConfig.session = session; 271 return this; 272 } 273 274 /** 275 * Set the {@link PendingIntent} to an activity for users to 276 * configure the VPN connection. If it is not set, the button 277 * to configure will not be shown in system-managed dialogs. 278 */ 279 public Builder setConfigureIntent(PendingIntent intent) { 280 mConfig.configureIntent = intent; 281 return this; 282 } 283 284 /** 285 * Set the maximum transmission unit (MTU) of the VPN interface. If 286 * it is not set, the default value in the operating system will be 287 * used. 288 * 289 * @throws IllegalArgumentException if the value is not positive. 290 */ 291 public Builder setMtu(int mtu) { 292 if (mtu <= 0) { 293 throw new IllegalArgumentException("Bad mtu"); 294 } 295 mConfig.mtu = mtu; 296 return this; 297 } 298 299 /** 300 * Private method to validate address and prefixLength. 301 */ 302 private void check(InetAddress address, int prefixLength) { 303 if (address.isLoopbackAddress()) { 304 throw new IllegalArgumentException("Bad address"); 305 } 306 if (address instanceof Inet4Address) { 307 if (prefixLength < 0 || prefixLength > 32) { 308 throw new IllegalArgumentException("Bad prefixLength"); 309 } 310 } else if (address instanceof Inet6Address) { 311 if (prefixLength < 0 || prefixLength > 128) { 312 throw new IllegalArgumentException("Bad prefixLength"); 313 } 314 } else { 315 throw new IllegalArgumentException("Unsupported family"); 316 } 317 } 318 319 /** 320 * Add a network address to the VPN interface. Both IPv4 and IPv6 321 * addresses are supported. At least one address must be set before 322 * calling {@link #establish}. 323 * 324 * @throws IllegalArgumentException if the address is invalid. 325 */ 326 public Builder addAddress(InetAddress address, int prefixLength) { 327 check(address, prefixLength); 328 329 if (address.isAnyLocalAddress()) { 330 throw new IllegalArgumentException("Bad address"); 331 } 332 mAddresses.add(new LinkAddress(address, prefixLength)); 333 return this; 334 } 335 336 /** 337 * Convenience method to add a network address to the VPN interface 338 * using a numeric address string. See {@link InetAddress} for the 339 * definitions of numeric address formats. 340 * 341 * @throws IllegalArgumentException if the address is invalid. 342 * @see #addAddress(InetAddress, int) 343 */ 344 public Builder addAddress(String address, int prefixLength) { 345 return addAddress(InetAddress.parseNumericAddress(address), prefixLength); 346 } 347 348 /** 349 * Add a network route to the VPN interface. Both IPv4 and IPv6 350 * routes are supported. 351 * 352 * @throws IllegalArgumentException if the route is invalid. 353 */ 354 public Builder addRoute(InetAddress address, int prefixLength) { 355 check(address, prefixLength); 356 357 int offset = prefixLength / 8; 358 byte[] bytes = address.getAddress(); 359 if (offset < bytes.length) { 360 for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) { 361 if (bytes[offset] != 0) { 362 throw new IllegalArgumentException("Bad address"); 363 } 364 } 365 } 366 mRoutes.add(new RouteInfo(new LinkAddress(address, prefixLength), null)); 367 return this; 368 } 369 370 /** 371 * Convenience method to add a network route to the VPN interface 372 * using a numeric address string. See {@link InetAddress} for the 373 * definitions of numeric address formats. 374 * 375 * @throws IllegalArgumentException if the route is invalid. 376 * @see #addRoute(InetAddress, int) 377 */ 378 public Builder addRoute(String address, int prefixLength) { 379 return addRoute(InetAddress.parseNumericAddress(address), prefixLength); 380 } 381 382 /** 383 * Add a DNS server to the VPN connection. Both IPv4 and IPv6 384 * addresses are supported. If none is set, the DNS servers of 385 * the default network will be used. 386 * 387 * @throws IllegalArgumentException if the address is invalid. 388 */ 389 public Builder addDnsServer(InetAddress address) { 390 if (address.isLoopbackAddress() || address.isAnyLocalAddress()) { 391 throw new IllegalArgumentException("Bad address"); 392 } 393 if (mConfig.dnsServers == null) { 394 mConfig.dnsServers = new ArrayList<String>(); 395 } 396 mConfig.dnsServers.add(address.getHostAddress()); 397 return this; 398 } 399 400 /** 401 * Convenience method to add a DNS server to the VPN connection 402 * using a numeric address string. See {@link InetAddress} for the 403 * definitions of numeric address formats. 404 * 405 * @throws IllegalArgumentException if the address is invalid. 406 * @see #addDnsServer(InetAddress) 407 */ 408 public Builder addDnsServer(String address) { 409 return addDnsServer(InetAddress.parseNumericAddress(address)); 410 } 411 412 /** 413 * Add a search domain to the DNS resolver. 414 */ 415 public Builder addSearchDomain(String domain) { 416 if (mConfig.searchDomains == null) { 417 mConfig.searchDomains = new ArrayList<String>(); 418 } 419 mConfig.searchDomains.add(domain); 420 return this; 421 } 422 423 /** 424 * Create a VPN interface using the parameters supplied to this 425 * builder. The interface works on IP packets, and a file descriptor 426 * is returned for the application to access them. Each read 427 * retrieves an outgoing packet which was routed to the interface. 428 * Each write injects an incoming packet just like it was received 429 * from the interface. The file descriptor is put into non-blocking 430 * mode by default to avoid blocking Java threads. To use the file 431 * descriptor completely in native space, see 432 * {@link ParcelFileDescriptor#detachFd()}. The application MUST 433 * close the file descriptor when the VPN connection is terminated. 434 * The VPN interface will be removed and the network will be 435 * restored by the system automatically. 436 * 437 * <p>To avoid conflicts, there can be only one active VPN interface 438 * at the same time. Usually network parameters are never changed 439 * during the lifetime of a VPN connection. It is also common for an 440 * application to create a new file descriptor after closing the 441 * previous one. However, it is rare but not impossible to have two 442 * interfaces while performing a seamless handover. In this case, the 443 * old interface will be deactivated when the new one is created 444 * successfully. Both file descriptors are valid but now outgoing 445 * packets will be routed to the new interface. Therefore, after 446 * draining the old file descriptor, the application MUST close it 447 * and start using the new file descriptor. If the new interface 448 * cannot be created, the existing interface and its file descriptor 449 * remain untouched. 450 * 451 * <p>An exception will be thrown if the interface cannot be created 452 * for any reason. However, this method returns {@code null} if the 453 * application is not prepared or is revoked. This helps solve 454 * possible race conditions between other VPN applications. 455 * 456 * @return {@link ParcelFileDescriptor} of the VPN interface, or 457 * {@code null} if the application is not prepared. 458 * @throws IllegalArgumentException if a parameter is not accepted 459 * by the operating system. 460 * @throws IllegalStateException if a parameter cannot be applied 461 * by the operating system. 462 * @throws SecurityException if the service is not properly declared 463 * in {@code AndroidManifest.xml}. 464 * @see VpnService 465 */ 466 public ParcelFileDescriptor establish() { 467 mConfig.addresses = mAddresses; 468 mConfig.routes = mRoutes; 469 470 try { 471 return getService().establishVpn(mConfig); 472 } catch (RemoteException e) { 473 throw new IllegalStateException(e); 474 } 475 } 476 } 477} 478