blob: 1bd560751f42091d3647baad38b0b24aa56fa0b4 [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
19import android.app.Activity;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070020import android.app.PendingIntent;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070021import android.app.Service;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070022import 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
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070033import java.net.DatagramSocket;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070034import java.net.Inet4Address;
35import java.net.Inet6Address;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070036import java.net.InetAddress;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070037import java.net.Socket;
38import java.util.ArrayList;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070039import java.util.List;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070040
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 * &lt;service android:name=".ExampleVpnService"
98 * android:permission="android.permission.BIND_VPN_SERVICE"&gt;
99 * &lt;intent-filter&gt;
100 * &lt;action android:name="android.net.VpnService"/&gt;
101 * &lt;/intent-filter&gt;
102 * &lt;/service&gt;</pre>
103 *
104 * @see Builder
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700105 */
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 /**
Chad Brubakerbcf12b32014-02-11 14:18:56 -0800154 * Protect a socket from VPN connections. After protecting, data sent
155 * through this socket will go directly to the underlying network,
156 * so its traffic will not be forwarded through the VPN.
157 * This method is useful if some connections need to be kept
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700158 * outside of VPN. For example, a VPN tunnel should protect itself if its
159 * destination is covered by VPN routes. Otherwise its outgoing packets
160 * will be sent back to the VPN interface and cause an infinite loop. This
161 * method will fail if the application is not prepared or is revoked.
162 *
163 * <p class="note">The socket is NOT closed by this method.
164 *
165 * @return {@code true} on success.
166 */
167 public boolean protect(int socket) {
168 ParcelFileDescriptor dup = null;
169 try {
170 dup = ParcelFileDescriptor.fromFd(socket);
171 return getService().protectVpn(dup);
172 } catch (Exception e) {
173 return false;
174 } finally {
175 try {
176 dup.close();
177 } catch (Exception e) {
178 // ignore
179 }
180 }
181 }
182
183 /**
184 * Convenience method to protect a {@link Socket} from VPN connections.
185 *
186 * @return {@code true} on success.
187 * @see #protect(int)
188 */
189 public boolean protect(Socket socket) {
190 return protect(socket.getFileDescriptor$().getInt$());
191 }
192
193 /**
194 * Convenience method to protect a {@link DatagramSocket} from VPN
195 * connections.
196 *
197 * @return {@code true} on success.
198 * @see #protect(int)
199 */
200 public boolean protect(DatagramSocket socket) {
201 return protect(socket.getFileDescriptor$().getInt$());
202 }
203
204 /**
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700205 * Adds a network address to the VPN interface.
206 *
207 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
208 * address is already in use or cannot be assigned to the interface for any other reason.
209 *
210 * @throws {@link IllegalArgumentException} if the address is invalid.
211 *
212 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
213 * @param prefixLength The prefix length of the address.
214 *
215 * @return {@code true} on success.
216 * @see Builder#addAddress
217 */
218 public boolean addAddress(InetAddress address, int prefixLength) {
219 // TODO
220 return true;
221 }
222
223 /**
224 * Removes a network address from the VPN interface.
225 *
226 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
227 * address is not assigned to the VPN interface, or if it is the only address assigned (thus
228 * cannot be removed), or if the address cannot be removed for any other reason.
229 *
230 * @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 *
363 * @throws IllegalArgumentException if the address is invalid.
364 */
365 public Builder addAddress(InetAddress address, int prefixLength) {
366 check(address, prefixLength);
367
368 if (address.isAnyLocalAddress()) {
369 throw new IllegalArgumentException("Bad address");
370 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700371 mAddresses.add(new LinkAddress(address, prefixLength));
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700372 return this;
373 }
374
375 /**
376 * Convenience method to add a network address to the VPN interface
377 * using a numeric address string. See {@link InetAddress} for the
378 * definitions of numeric address formats.
379 *
380 * @throws IllegalArgumentException if the address is invalid.
381 * @see #addAddress(InetAddress, int)
382 */
383 public Builder addAddress(String address, int prefixLength) {
384 return addAddress(InetAddress.parseNumericAddress(address), prefixLength);
385 }
386
387 /**
388 * Add a network route to the VPN interface. Both IPv4 and IPv6
389 * routes are supported.
390 *
391 * @throws IllegalArgumentException if the route is invalid.
392 */
393 public Builder addRoute(InetAddress address, int prefixLength) {
394 check(address, prefixLength);
395
396 int offset = prefixLength / 8;
397 byte[] bytes = address.getAddress();
398 if (offset < bytes.length) {
399 for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) {
400 if (bytes[offset] != 0) {
401 throw new IllegalArgumentException("Bad address");
402 }
403 }
404 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700405 mRoutes.add(new RouteInfo(new LinkAddress(address, prefixLength), null));
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700406 return this;
407 }
408
409 /**
410 * Convenience method to add a network route to the VPN interface
411 * using a numeric address string. See {@link InetAddress} for the
412 * definitions of numeric address formats.
413 *
414 * @throws IllegalArgumentException if the route is invalid.
415 * @see #addRoute(InetAddress, int)
416 */
417 public Builder addRoute(String address, int prefixLength) {
418 return addRoute(InetAddress.parseNumericAddress(address), prefixLength);
419 }
420
421 /**
422 * Add a DNS server to the VPN connection. Both IPv4 and IPv6
423 * addresses are supported. If none is set, the DNS servers of
424 * the default network will be used.
425 *
426 * @throws IllegalArgumentException if the address is invalid.
427 */
428 public Builder addDnsServer(InetAddress address) {
429 if (address.isLoopbackAddress() || address.isAnyLocalAddress()) {
430 throw new IllegalArgumentException("Bad address");
431 }
432 if (mConfig.dnsServers == null) {
433 mConfig.dnsServers = new ArrayList<String>();
434 }
435 mConfig.dnsServers.add(address.getHostAddress());
436 return this;
437 }
438
439 /**
440 * Convenience method to add a DNS server to the VPN connection
441 * using a numeric address string. See {@link InetAddress} for the
442 * definitions of numeric address formats.
443 *
444 * @throws IllegalArgumentException if the address is invalid.
445 * @see #addDnsServer(InetAddress)
446 */
447 public Builder addDnsServer(String address) {
448 return addDnsServer(InetAddress.parseNumericAddress(address));
449 }
450
451 /**
452 * Add a search domain to the DNS resolver.
453 */
454 public Builder addSearchDomain(String domain) {
455 if (mConfig.searchDomains == null) {
456 mConfig.searchDomains = new ArrayList<String>();
457 }
458 mConfig.searchDomains.add(domain);
459 return this;
460 }
461
462 /**
463 * Create a VPN interface using the parameters supplied to this
464 * builder. The interface works on IP packets, and a file descriptor
465 * is returned for the application to access them. Each read
466 * retrieves an outgoing packet which was routed to the interface.
467 * Each write injects an incoming packet just like it was received
468 * from the interface. The file descriptor is put into non-blocking
469 * mode by default to avoid blocking Java threads. To use the file
470 * descriptor completely in native space, see
471 * {@link ParcelFileDescriptor#detachFd()}. The application MUST
472 * close the file descriptor when the VPN connection is terminated.
473 * The VPN interface will be removed and the network will be
474 * restored by the system automatically.
475 *
476 * <p>To avoid conflicts, there can be only one active VPN interface
477 * at the same time. Usually network parameters are never changed
478 * during the lifetime of a VPN connection. It is also common for an
479 * application to create a new file descriptor after closing the
480 * previous one. However, it is rare but not impossible to have two
481 * interfaces while performing a seamless handover. In this case, the
482 * old interface will be deactivated when the new one is created
483 * successfully. Both file descriptors are valid but now outgoing
484 * packets will be routed to the new interface. Therefore, after
485 * draining the old file descriptor, the application MUST close it
486 * and start using the new file descriptor. If the new interface
487 * cannot be created, the existing interface and its file descriptor
488 * remain untouched.
489 *
490 * <p>An exception will be thrown if the interface cannot be created
491 * for any reason. However, this method returns {@code null} if the
492 * application is not prepared or is revoked. This helps solve
493 * possible race conditions between other VPN applications.
494 *
495 * @return {@link ParcelFileDescriptor} of the VPN interface, or
496 * {@code null} if the application is not prepared.
497 * @throws IllegalArgumentException if a parameter is not accepted
498 * by the operating system.
499 * @throws IllegalStateException if a parameter cannot be applied
500 * by the operating system.
501 * @throws SecurityException if the service is not properly declared
502 * in {@code AndroidManifest.xml}.
503 * @see VpnService
504 */
505 public ParcelFileDescriptor establish() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700506 mConfig.addresses = mAddresses;
507 mConfig.routes = mRoutes;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700508
509 try {
510 return getService().establishVpn(mConfig);
511 } catch (RemoteException e) {
512 throw new IllegalStateException(e);
513 }
514 }
515 }
516}