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