blob: 1d89eaebada14d5e9300e067efccf07f0de35f1f [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 *
202 * @throws {@link IllegalArgumentException} if the address is invalid.
203 *
204 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
205 * @param prefixLength The prefix length of the address.
206 *
207 * @return {@code true} on success.
208 * @see Builder#addAddress
209 */
210 public boolean addAddress(InetAddress address, int prefixLength) {
211 // TODO
212 return true;
213 }
214
215 /**
216 * Removes a network address from the VPN interface.
217 *
218 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
219 * address is not assigned to the VPN interface, or if it is the only address assigned (thus
220 * cannot be removed), or if the address cannot be removed for any other reason.
221 *
222 * @throws {@link IllegalArgumentException} if the address is invalid.
223 *
224 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
225 * @param prefixLength The prefix length of the address.
226 *
227 * @return {@code true} on success.
228 */
229 public boolean removeAddress(InetAddress address, int prefixLength) {
230 // TODO
231 return true;
232 }
233
234 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700235 * Return the communication interface to the service. This method returns
236 * {@code null} on {@link Intent}s other than {@link #SERVICE_INTERFACE}
237 * action. Applications overriding this method must identify the intent
238 * and return the corresponding interface accordingly.
239 *
240 * @see Service#onBind
241 */
242 @Override
243 public IBinder onBind(Intent intent) {
244 if (intent != null && SERVICE_INTERFACE.equals(intent.getAction())) {
245 return new Callback();
246 }
247 return null;
248 }
249
250 /**
251 * Invoked when the application is revoked. At this moment, the VPN
252 * interface is already deactivated by the system. The application should
253 * close the file descriptor and shut down gracefully. The default
254 * implementation of this method is calling {@link Service#stopSelf()}.
255 *
256 * <p class="note">Calls to this method may not happen on the main thread
257 * of the process.
258 *
259 * @see #prepare
260 */
261 public void onRevoke() {
262 stopSelf();
263 }
264
265 /**
266 * Use raw Binder instead of AIDL since now there is only one usage.
267 */
268 private class Callback extends Binder {
269 @Override
270 protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
271 if (code == IBinder.LAST_CALL_TRANSACTION) {
272 onRevoke();
273 return true;
274 }
275 return false;
276 }
277 }
278
279 /**
280 * Helper class to create a VPN interface. This class should be always
281 * used within the scope of the outer {@link VpnService}.
282 *
283 * @see VpnService
284 */
285 public class Builder {
286
287 private final VpnConfig mConfig = new VpnConfig();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700288 private final List<LinkAddress> mAddresses = new ArrayList<LinkAddress>();
289 private final List<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700290
291 public Builder() {
292 mConfig.user = VpnService.this.getClass().getName();
293 }
294
295 /**
296 * Set the name of this session. It will be displayed in
297 * system-managed dialogs and notifications. This is recommended
298 * not required.
299 */
300 public Builder setSession(String session) {
301 mConfig.session = session;
302 return this;
303 }
304
305 /**
306 * Set the {@link PendingIntent} to an activity for users to
307 * configure the VPN connection. If it is not set, the button
308 * to configure will not be shown in system-managed dialogs.
309 */
310 public Builder setConfigureIntent(PendingIntent intent) {
311 mConfig.configureIntent = intent;
312 return this;
313 }
314
315 /**
316 * Set the maximum transmission unit (MTU) of the VPN interface. If
317 * it is not set, the default value in the operating system will be
318 * used.
319 *
320 * @throws IllegalArgumentException if the value is not positive.
321 */
322 public Builder setMtu(int mtu) {
323 if (mtu <= 0) {
324 throw new IllegalArgumentException("Bad mtu");
325 }
326 mConfig.mtu = mtu;
327 return this;
328 }
329
330 /**
331 * Private method to validate address and prefixLength.
332 */
333 private void check(InetAddress address, int prefixLength) {
334 if (address.isLoopbackAddress()) {
335 throw new IllegalArgumentException("Bad address");
336 }
337 if (address instanceof Inet4Address) {
338 if (prefixLength < 0 || prefixLength > 32) {
339 throw new IllegalArgumentException("Bad prefixLength");
340 }
341 } else if (address instanceof Inet6Address) {
342 if (prefixLength < 0 || prefixLength > 128) {
343 throw new IllegalArgumentException("Bad prefixLength");
344 }
345 } else {
346 throw new IllegalArgumentException("Unsupported family");
347 }
348 }
349
350 /**
351 * Add a network address to the VPN interface. Both IPv4 and IPv6
352 * addresses are supported. At least one address must be set before
353 * calling {@link #establish}.
354 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700355 * Adding an address implicitly allows traffic from that address family
356 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
357 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700358 * @throws IllegalArgumentException if the address is invalid.
359 */
360 public Builder addAddress(InetAddress address, int prefixLength) {
361 check(address, prefixLength);
362
363 if (address.isAnyLocalAddress()) {
364 throw new IllegalArgumentException("Bad address");
365 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700366 mAddresses.add(new LinkAddress(address, prefixLength));
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700367 return this;
368 }
369
370 /**
371 * Convenience method to add a network address to the VPN interface
372 * using a numeric address string. See {@link InetAddress} for the
373 * definitions of numeric address formats.
374 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700375 * Adding an address implicitly allows traffic from that address family
376 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
377 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700378 * @throws IllegalArgumentException if the address is invalid.
379 * @see #addAddress(InetAddress, int)
380 */
381 public Builder addAddress(String address, int prefixLength) {
382 return addAddress(InetAddress.parseNumericAddress(address), prefixLength);
383 }
384
385 /**
386 * Add a network route to the VPN interface. Both IPv4 and IPv6
387 * routes are supported.
388 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700389 * Adding a route implicitly allows traffic from that address family
390 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
391 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700392 * @throws IllegalArgumentException if the route is invalid.
393 */
394 public Builder addRoute(InetAddress address, int prefixLength) {
395 check(address, prefixLength);
396
397 int offset = prefixLength / 8;
398 byte[] bytes = address.getAddress();
399 if (offset < bytes.length) {
400 for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) {
401 if (bytes[offset] != 0) {
402 throw new IllegalArgumentException("Bad address");
403 }
404 }
405 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700406 mRoutes.add(new RouteInfo(new LinkAddress(address, prefixLength), null));
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700407 return this;
408 }
409
410 /**
411 * Convenience method to add a network route to the VPN interface
412 * using a numeric address string. See {@link InetAddress} for the
413 * definitions of numeric address formats.
414 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700415 * Adding a route implicitly allows traffic from that address family
416 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
417 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700418 * @throws IllegalArgumentException if the route is invalid.
419 * @see #addRoute(InetAddress, int)
420 */
421 public Builder addRoute(String address, int prefixLength) {
422 return addRoute(InetAddress.parseNumericAddress(address), prefixLength);
423 }
424
425 /**
426 * Add a DNS server to the VPN connection. Both IPv4 and IPv6
427 * addresses are supported. If none is set, the DNS servers of
428 * the default network will be used.
429 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700430 * Adding a server implicitly allows traffic from that address family
431 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
432 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700433 * @throws IllegalArgumentException if the address is invalid.
434 */
435 public Builder addDnsServer(InetAddress address) {
436 if (address.isLoopbackAddress() || address.isAnyLocalAddress()) {
437 throw new IllegalArgumentException("Bad address");
438 }
439 if (mConfig.dnsServers == null) {
440 mConfig.dnsServers = new ArrayList<String>();
441 }
442 mConfig.dnsServers.add(address.getHostAddress());
443 return this;
444 }
445
446 /**
447 * Convenience method to add a DNS server to the VPN connection
448 * using a numeric address string. See {@link InetAddress} for the
449 * definitions of numeric address formats.
450 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700451 * Adding a server implicitly allows traffic from that address family
452 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
453 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700454 * @throws IllegalArgumentException if the address is invalid.
455 * @see #addDnsServer(InetAddress)
456 */
457 public Builder addDnsServer(String address) {
458 return addDnsServer(InetAddress.parseNumericAddress(address));
459 }
460
461 /**
462 * Add a search domain to the DNS resolver.
463 */
464 public Builder addSearchDomain(String domain) {
465 if (mConfig.searchDomains == null) {
466 mConfig.searchDomains = new ArrayList<String>();
467 }
468 mConfig.searchDomains.add(domain);
469 return this;
470 }
471
472 /**
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700473 * Allows traffic from the specified address family.
474 *
475 * By default, if no address, route or DNS server of a specific family (IPv4 or IPv6) is
476 * added to this VPN, then all outgoing traffic of that family is blocked. If any address,
477 * route or DNS server is added, that family is allowed.
478 *
479 * This method allows an address family to be unblocked even without adding an address,
480 * route or DNS server of that family. Traffic of that family will then typically
481 * fall-through to the underlying network if it's supported.
482 *
483 * {@code family} must be either {@code AF_INET} (for IPv4) or {@code AF_INET6} (for IPv6).
484 * {@link IllegalArgumentException} is thrown if it's neither.
485 *
486 * @param family The address family ({@code AF_INET} or {@code AF_INET6}) to allow.
487 *
488 * @return this {@link Builder} object to facilitate chaining of method calls.
489 */
490 public Builder allowFamily(int family) {
491 // TODO
492 return this;
493 }
494
495 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700496 * Create a VPN interface using the parameters supplied to this
497 * builder. The interface works on IP packets, and a file descriptor
498 * is returned for the application to access them. Each read
499 * retrieves an outgoing packet which was routed to the interface.
500 * Each write injects an incoming packet just like it was received
501 * from the interface. The file descriptor is put into non-blocking
502 * mode by default to avoid blocking Java threads. To use the file
503 * descriptor completely in native space, see
504 * {@link ParcelFileDescriptor#detachFd()}. The application MUST
505 * close the file descriptor when the VPN connection is terminated.
506 * The VPN interface will be removed and the network will be
507 * restored by the system automatically.
508 *
509 * <p>To avoid conflicts, there can be only one active VPN interface
510 * at the same time. Usually network parameters are never changed
511 * during the lifetime of a VPN connection. It is also common for an
512 * application to create a new file descriptor after closing the
513 * previous one. However, it is rare but not impossible to have two
514 * interfaces while performing a seamless handover. In this case, the
515 * old interface will be deactivated when the new one is created
516 * successfully. Both file descriptors are valid but now outgoing
517 * packets will be routed to the new interface. Therefore, after
518 * draining the old file descriptor, the application MUST close it
519 * and start using the new file descriptor. If the new interface
520 * cannot be created, the existing interface and its file descriptor
521 * remain untouched.
522 *
523 * <p>An exception will be thrown if the interface cannot be created
524 * for any reason. However, this method returns {@code null} if the
525 * application is not prepared or is revoked. This helps solve
526 * possible race conditions between other VPN applications.
527 *
528 * @return {@link ParcelFileDescriptor} of the VPN interface, or
529 * {@code null} if the application is not prepared.
530 * @throws IllegalArgumentException if a parameter is not accepted
531 * by the operating system.
532 * @throws IllegalStateException if a parameter cannot be applied
533 * by the operating system.
534 * @throws SecurityException if the service is not properly declared
535 * in {@code AndroidManifest.xml}.
536 * @see VpnService
537 */
538 public ParcelFileDescriptor establish() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700539 mConfig.addresses = mAddresses;
540 mConfig.routes = mRoutes;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700541
542 try {
543 return getService().establishVpn(mConfig);
544 } catch (RemoteException e) {
545 throw new IllegalStateException(e);
546 }
547 }
548 }
549}