blob: e9de79daca1fa71d2a835a8d5b8579c34cdd2cde [file] [log] [blame]
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001/*
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
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -070019import static android.system.OsConstants.AF_INET;
20import static android.system.OsConstants.AF_INET6;
21
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070022import android.app.Activity;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070023import android.app.PendingIntent;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070024import android.app.Service;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070025import android.content.Context;
26import android.content.Intent;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040027import android.net.NetworkUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070028import android.os.Binder;
29import android.os.IBinder;
30import android.os.Parcel;
31import android.os.ParcelFileDescriptor;
32import android.os.RemoteException;
33import android.os.ServiceManager;
34
35import com.android.internal.net.VpnConfig;
36
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070037import java.net.DatagramSocket;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070038import java.net.Inet4Address;
39import java.net.Inet6Address;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070040import java.net.InetAddress;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070041import java.net.Socket;
42import java.util.ArrayList;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070043import java.util.List;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070044
45/**
46 * VpnService is a base class for applications to extend and build their
47 * own VPN solutions. In general, it creates a virtual network interface,
48 * configures addresses and routing rules, and returns a file descriptor
49 * to the application. Each read from the descriptor retrieves an outgoing
50 * packet which was routed to the interface. Each write to the descriptor
51 * injects an incoming packet just like it was received from the interface.
52 * The interface is running on Internet Protocol (IP), so packets are
53 * always started with IP headers. The application then completes a VPN
54 * connection by processing and exchanging packets with the remote server
55 * over a tunnel.
56 *
57 * <p>Letting applications intercept packets raises huge security concerns.
58 * A VPN application can easily break the network. Besides, two of them may
59 * conflict with each other. The system takes several actions to address
60 * these issues. Here are some key points:
61 * <ul>
62 * <li>User action is required to create a VPN connection.</li>
63 * <li>There can be only one VPN connection running at the same time. The
64 * existing interface is deactivated when a new one is created.</li>
65 * <li>A system-managed notification is shown during the lifetime of a
66 * VPN connection.</li>
67 * <li>A system-managed dialog gives the information of the current VPN
68 * connection. It also provides a button to disconnect.</li>
69 * <li>The network is restored automatically when the file descriptor is
70 * closed. It also covers the cases when a VPN application is crashed
71 * or killed by the system.</li>
72 * </ul>
73 *
74 * <p>There are two primary methods in this class: {@link #prepare} and
75 * {@link Builder#establish}. The former deals with user action and stops
76 * the VPN connection created by another application. The latter creates
77 * a VPN interface using the parameters supplied to the {@link Builder}.
78 * An application must call {@link #prepare} to grant the right to use
79 * other methods in this class, and the right can be revoked at any time.
80 * Here are the general steps to create a VPN connection:
81 * <ol>
82 * <li>When the user press the button to connect, call {@link #prepare}
83 * and launch the returned intent.</li>
84 * <li>When the application becomes prepared, start the service.</li>
85 * <li>Create a tunnel to the remote server and negotiate the network
86 * parameters for the VPN connection.</li>
87 * <li>Supply those parameters to a {@link Builder} and create a VPN
88 * interface by calling {@link Builder#establish}.</li>
89 * <li>Process and exchange packets between the tunnel and the returned
90 * file descriptor.</li>
91 * <li>When {@link #onRevoke} is invoked, close the file descriptor and
92 * shut down the tunnel gracefully.</li>
93 * </ol>
94 *
95 * <p>Services extended this class need to be declared with appropriate
96 * permission and intent filter. Their access must be secured by
97 * {@link android.Manifest.permission#BIND_VPN_SERVICE} permission, and
98 * their intent filter must match {@link #SERVICE_INTERFACE} action. Here
99 * is an example of declaring a VPN service in {@code AndroidManifest.xml}:
100 * <pre>
101 * &lt;service android:name=".ExampleVpnService"
102 * android:permission="android.permission.BIND_VPN_SERVICE"&gt;
103 * &lt;intent-filter&gt;
104 * &lt;action android:name="android.net.VpnService"/&gt;
105 * &lt;/intent-filter&gt;
106 * &lt;/service&gt;</pre>
107 *
108 * @see Builder
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700109 */
110public class VpnService extends Service {
111
112 /**
113 * The action must be matched by the intent filter of this service. It also
114 * needs to require {@link android.Manifest.permission#BIND_VPN_SERVICE}
115 * permission so that other applications cannot abuse it.
116 */
117 public static final String SERVICE_INTERFACE = VpnConfig.SERVICE_INTERFACE;
118
119 /**
120 * Use IConnectivityManager since those methods are hidden and not
121 * available in ConnectivityManager.
122 */
123 private static IConnectivityManager getService() {
124 return IConnectivityManager.Stub.asInterface(
125 ServiceManager.getService(Context.CONNECTIVITY_SERVICE));
126 }
127
128 /**
129 * Prepare to establish a VPN connection. This method returns {@code null}
130 * if the VPN application is already prepared. Otherwise, it returns an
131 * {@link Intent} to a system activity. The application should launch the
132 * activity using {@link Activity#startActivityForResult} to get itself
133 * prepared. The activity may pop up a dialog to require user action, and
134 * the result will come back via its {@link Activity#onActivityResult}.
135 * If the result is {@link Activity#RESULT_OK}, the application becomes
136 * prepared and is granted to use other methods in this class.
137 *
138 * <p>Only one application can be granted at the same time. The right
139 * is revoked when another application is granted. The application
140 * losing the right will be notified via its {@link #onRevoke}. Unless
141 * it becomes prepared again, subsequent calls to other methods in this
142 * class will fail.
143 *
144 * @see #onRevoke
145 */
146 public static Intent prepare(Context context) {
147 try {
148 if (getService().prepareVpn(context.getPackageName(), null)) {
149 return null;
150 }
151 } catch (RemoteException e) {
152 // ignore
153 }
154 return VpnConfig.getIntentForConfirmation();
155 }
156
157 /**
Chad Brubakerbcf12b32014-02-11 14:18:56 -0800158 * Protect a socket from VPN connections. After protecting, data sent
159 * through this socket will go directly to the underlying network,
160 * so its traffic will not be forwarded through the VPN.
161 * This method is useful if some connections need to be kept
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700162 * outside of VPN. For example, a VPN tunnel should protect itself if its
163 * destination is covered by VPN routes. Otherwise its outgoing packets
164 * will be sent back to the VPN interface and cause an infinite loop. This
165 * method will fail if the application is not prepared or is revoked.
166 *
167 * <p class="note">The socket is NOT closed by this method.
168 *
169 * @return {@code true} on success.
170 */
171 public boolean protect(int socket) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400172 return NetworkUtils.protectFromVpn(socket);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700173 }
174
175 /**
176 * Convenience method to protect a {@link Socket} from VPN connections.
177 *
178 * @return {@code true} on success.
179 * @see #protect(int)
180 */
181 public boolean protect(Socket socket) {
182 return protect(socket.getFileDescriptor$().getInt$());
183 }
184
185 /**
186 * Convenience method to protect a {@link DatagramSocket} from VPN
187 * connections.
188 *
189 * @return {@code true} on success.
190 * @see #protect(int)
191 */
192 public boolean protect(DatagramSocket socket) {
193 return protect(socket.getFileDescriptor$().getInt$());
194 }
195
196 /**
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700197 * Adds a network address to the VPN interface.
198 *
199 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
200 * address is already in use or cannot be assigned to the interface for any other reason.
201 *
Sreeram Ramachandran13846052014-07-10 12:35:23 -0700202 * Adding an address implicitly allows traffic from that address family (i.e., IPv4 or IPv6) to
203 * be routed over the VPN. @see Builder#allowFamily
204 *
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700205 * @throws {@link IllegalArgumentException} if the address is invalid.
206 *
207 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
208 * @param prefixLength The prefix length of the address.
209 *
210 * @return {@code true} on success.
211 * @see Builder#addAddress
212 */
213 public boolean addAddress(InetAddress address, int prefixLength) {
214 // TODO
215 return true;
216 }
217
218 /**
219 * Removes a network address from the VPN interface.
220 *
221 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
222 * address is not assigned to the VPN interface, or if it is the only address assigned (thus
223 * cannot be removed), or if the address cannot be removed for any other reason.
224 *
Sreeram Ramachandran13846052014-07-10 12:35:23 -0700225 * After removing an address, if there are no addresses, routes or DNS servers of a particular
226 * address family (i.e., IPv4 or IPv6) configured on the VPN, that <b>DOES NOT</b> block that
227 * family from being routed. In other words, once an address family has been allowed, it stays
228 * allowed for the rest of the VPN's session. @see Builder#allowFamily
229 *
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700230 * @throws {@link IllegalArgumentException} if the address is invalid.
231 *
232 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
233 * @param prefixLength The prefix length of the address.
234 *
235 * @return {@code true} on success.
236 */
237 public boolean removeAddress(InetAddress address, int prefixLength) {
238 // TODO
239 return true;
240 }
241
242 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700243 * Return the communication interface to the service. This method returns
244 * {@code null} on {@link Intent}s other than {@link #SERVICE_INTERFACE}
245 * action. Applications overriding this method must identify the intent
246 * and return the corresponding interface accordingly.
247 *
248 * @see Service#onBind
249 */
250 @Override
251 public IBinder onBind(Intent intent) {
252 if (intent != null && SERVICE_INTERFACE.equals(intent.getAction())) {
253 return new Callback();
254 }
255 return null;
256 }
257
258 /**
259 * Invoked when the application is revoked. At this moment, the VPN
260 * interface is already deactivated by the system. The application should
261 * close the file descriptor and shut down gracefully. The default
262 * implementation of this method is calling {@link Service#stopSelf()}.
263 *
264 * <p class="note">Calls to this method may not happen on the main thread
265 * of the process.
266 *
267 * @see #prepare
268 */
269 public void onRevoke() {
270 stopSelf();
271 }
272
273 /**
274 * Use raw Binder instead of AIDL since now there is only one usage.
275 */
276 private class Callback extends Binder {
277 @Override
278 protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
279 if (code == IBinder.LAST_CALL_TRANSACTION) {
280 onRevoke();
281 return true;
282 }
283 return false;
284 }
285 }
286
287 /**
288 * Helper class to create a VPN interface. This class should be always
289 * used within the scope of the outer {@link VpnService}.
290 *
291 * @see VpnService
292 */
293 public class Builder {
294
295 private final VpnConfig mConfig = new VpnConfig();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700296 private final List<LinkAddress> mAddresses = new ArrayList<LinkAddress>();
297 private final List<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700298
299 public Builder() {
300 mConfig.user = VpnService.this.getClass().getName();
301 }
302
303 /**
304 * Set the name of this session. It will be displayed in
305 * system-managed dialogs and notifications. This is recommended
306 * not required.
307 */
308 public Builder setSession(String session) {
309 mConfig.session = session;
310 return this;
311 }
312
313 /**
314 * Set the {@link PendingIntent} to an activity for users to
315 * configure the VPN connection. If it is not set, the button
316 * to configure will not be shown in system-managed dialogs.
317 */
318 public Builder setConfigureIntent(PendingIntent intent) {
319 mConfig.configureIntent = intent;
320 return this;
321 }
322
323 /**
324 * Set the maximum transmission unit (MTU) of the VPN interface. If
325 * it is not set, the default value in the operating system will be
326 * used.
327 *
328 * @throws IllegalArgumentException if the value is not positive.
329 */
330 public Builder setMtu(int mtu) {
331 if (mtu <= 0) {
332 throw new IllegalArgumentException("Bad mtu");
333 }
334 mConfig.mtu = mtu;
335 return this;
336 }
337
338 /**
339 * Private method to validate address and prefixLength.
340 */
341 private void check(InetAddress address, int prefixLength) {
342 if (address.isLoopbackAddress()) {
343 throw new IllegalArgumentException("Bad address");
344 }
345 if (address instanceof Inet4Address) {
346 if (prefixLength < 0 || prefixLength > 32) {
347 throw new IllegalArgumentException("Bad prefixLength");
348 }
349 } else if (address instanceof Inet6Address) {
350 if (prefixLength < 0 || prefixLength > 128) {
351 throw new IllegalArgumentException("Bad prefixLength");
352 }
353 } else {
354 throw new IllegalArgumentException("Unsupported family");
355 }
356 }
357
358 /**
359 * Add a network address to the VPN interface. Both IPv4 and IPv6
360 * addresses are supported. At least one address must be set before
361 * calling {@link #establish}.
362 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700363 * Adding an address implicitly allows traffic from that address family
364 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
365 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700366 * @throws IllegalArgumentException if the address is invalid.
367 */
368 public Builder addAddress(InetAddress address, int prefixLength) {
369 check(address, prefixLength);
370
371 if (address.isAnyLocalAddress()) {
372 throw new IllegalArgumentException("Bad address");
373 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700374 mAddresses.add(new LinkAddress(address, prefixLength));
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700375 return this;
376 }
377
378 /**
379 * Convenience method to add a network address to the VPN interface
380 * using a numeric address string. See {@link InetAddress} for the
381 * definitions of numeric address formats.
382 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700383 * Adding an address implicitly allows traffic from that address family
384 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
385 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700386 * @throws IllegalArgumentException if the address is invalid.
387 * @see #addAddress(InetAddress, int)
388 */
389 public Builder addAddress(String address, int prefixLength) {
390 return addAddress(InetAddress.parseNumericAddress(address), prefixLength);
391 }
392
393 /**
394 * Add a network route to the VPN interface. Both IPv4 and IPv6
395 * routes are supported.
396 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700397 * Adding a route implicitly allows traffic from that address family
398 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
399 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700400 * @throws IllegalArgumentException if the route is invalid.
401 */
402 public Builder addRoute(InetAddress address, int prefixLength) {
403 check(address, prefixLength);
404
405 int offset = prefixLength / 8;
406 byte[] bytes = address.getAddress();
407 if (offset < bytes.length) {
408 for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) {
409 if (bytes[offset] != 0) {
410 throw new IllegalArgumentException("Bad address");
411 }
412 }
413 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700414 mRoutes.add(new RouteInfo(new LinkAddress(address, prefixLength), null));
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700415 return this;
416 }
417
418 /**
419 * Convenience method to add a network route to the VPN interface
420 * using a numeric address string. See {@link InetAddress} for the
421 * definitions of numeric address formats.
422 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700423 * Adding a route implicitly allows traffic from that address family
424 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
425 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700426 * @throws IllegalArgumentException if the route is invalid.
427 * @see #addRoute(InetAddress, int)
428 */
429 public Builder addRoute(String address, int prefixLength) {
430 return addRoute(InetAddress.parseNumericAddress(address), prefixLength);
431 }
432
433 /**
434 * Add a DNS server to the VPN connection. Both IPv4 and IPv6
435 * addresses are supported. If none is set, the DNS servers of
436 * the default network will be used.
437 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700438 * Adding a server implicitly allows traffic from that address family
439 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
440 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700441 * @throws IllegalArgumentException if the address is invalid.
442 */
443 public Builder addDnsServer(InetAddress address) {
444 if (address.isLoopbackAddress() || address.isAnyLocalAddress()) {
445 throw new IllegalArgumentException("Bad address");
446 }
447 if (mConfig.dnsServers == null) {
448 mConfig.dnsServers = new ArrayList<String>();
449 }
450 mConfig.dnsServers.add(address.getHostAddress());
451 return this;
452 }
453
454 /**
455 * Convenience method to add a DNS server to the VPN connection
456 * using a numeric address string. See {@link InetAddress} for the
457 * definitions of numeric address formats.
458 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700459 * Adding a server implicitly allows traffic from that address family
460 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
461 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700462 * @throws IllegalArgumentException if the address is invalid.
463 * @see #addDnsServer(InetAddress)
464 */
465 public Builder addDnsServer(String address) {
466 return addDnsServer(InetAddress.parseNumericAddress(address));
467 }
468
469 /**
470 * Add a search domain to the DNS resolver.
471 */
472 public Builder addSearchDomain(String domain) {
473 if (mConfig.searchDomains == null) {
474 mConfig.searchDomains = new ArrayList<String>();
475 }
476 mConfig.searchDomains.add(domain);
477 return this;
478 }
479
480 /**
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700481 * Allows traffic from the specified address family.
482 *
483 * By default, if no address, route or DNS server of a specific family (IPv4 or IPv6) is
484 * added to this VPN, then all outgoing traffic of that family is blocked. If any address,
485 * route or DNS server is added, that family is allowed.
486 *
487 * This method allows an address family to be unblocked even without adding an address,
488 * route or DNS server of that family. Traffic of that family will then typically
489 * fall-through to the underlying network if it's supported.
490 *
491 * {@code family} must be either {@code AF_INET} (for IPv4) or {@code AF_INET6} (for IPv6).
492 * {@link IllegalArgumentException} is thrown if it's neither.
493 *
494 * @param family The address family ({@code AF_INET} or {@code AF_INET6}) to allow.
495 *
496 * @return this {@link Builder} object to facilitate chaining of method calls.
497 */
498 public Builder allowFamily(int family) {
499 // TODO
500 return this;
501 }
502
503 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700504 * Create a VPN interface using the parameters supplied to this
505 * builder. The interface works on IP packets, and a file descriptor
506 * is returned for the application to access them. Each read
507 * retrieves an outgoing packet which was routed to the interface.
508 * Each write injects an incoming packet just like it was received
509 * from the interface. The file descriptor is put into non-blocking
510 * mode by default to avoid blocking Java threads. To use the file
511 * descriptor completely in native space, see
512 * {@link ParcelFileDescriptor#detachFd()}. The application MUST
513 * close the file descriptor when the VPN connection is terminated.
514 * The VPN interface will be removed and the network will be
515 * restored by the system automatically.
516 *
517 * <p>To avoid conflicts, there can be only one active VPN interface
518 * at the same time. Usually network parameters are never changed
519 * during the lifetime of a VPN connection. It is also common for an
520 * application to create a new file descriptor after closing the
521 * previous one. However, it is rare but not impossible to have two
522 * interfaces while performing a seamless handover. In this case, the
523 * old interface will be deactivated when the new one is created
524 * successfully. Both file descriptors are valid but now outgoing
525 * packets will be routed to the new interface. Therefore, after
526 * draining the old file descriptor, the application MUST close it
527 * and start using the new file descriptor. If the new interface
528 * cannot be created, the existing interface and its file descriptor
529 * remain untouched.
530 *
531 * <p>An exception will be thrown if the interface cannot be created
532 * for any reason. However, this method returns {@code null} if the
533 * application is not prepared or is revoked. This helps solve
534 * possible race conditions between other VPN applications.
535 *
536 * @return {@link ParcelFileDescriptor} of the VPN interface, or
537 * {@code null} if the application is not prepared.
538 * @throws IllegalArgumentException if a parameter is not accepted
539 * by the operating system.
540 * @throws IllegalStateException if a parameter cannot be applied
541 * by the operating system.
542 * @throws SecurityException if the service is not properly declared
543 * in {@code AndroidManifest.xml}.
544 * @see VpnService
545 */
546 public ParcelFileDescriptor establish() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700547 mConfig.addresses = mAddresses;
548 mConfig.routes = mRoutes;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700549
550 try {
551 return getService().establishVpn(mConfig);
552 } catch (RemoteException e) {
553 throw new IllegalStateException(e);
554 }
555 }
556 }
557}